Ruby 4.0.0dev (2025-12-20 revision 8274c5e1428b5b88e885857d466822cbadc19761)
vm_method.c (8274c5e1428b5b88e885857d466822cbadc19761)
1/*
2 * This file is included by vm.c
3 */
4
5#include "id_table.h"
6#include "yjit.h"
7
8#define METHOD_DEBUG 0
9
10static int vm_redefinition_check_flag(VALUE klass);
11static void rb_vm_check_redefinition_opt_method(const rb_method_entry_t *me, VALUE klass);
12static inline rb_method_entry_t *lookup_method_table(VALUE klass, ID id);
13
14#define object_id idObject_id
15#define added idMethod_added
16#define singleton_added idSingleton_method_added
17#define removed idMethod_removed
18#define singleton_removed idSingleton_method_removed
19#define undefined idMethod_undefined
20#define singleton_undefined idSingleton_method_undefined
21
22#define ruby_running (GET_VM()->running)
23/* int ruby_running = 0; */
24
25static enum rb_id_table_iterator_result
26mark_cc_entry_i(VALUE ccs_ptr, void *data)
27{
28 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_ptr;
29
30 VM_ASSERT(vm_ccs_p(ccs));
31
32 if (METHOD_ENTRY_INVALIDATED(ccs->cme)) {
33 /* Before detaching the CCs from this class, we need to invalidate the cc
34 * since we will no longer be marking the cme on their behalf.
35 */
36 for (int i = 0; i < ccs->len; i++) {
37 const struct rb_callcache *cc = ccs->entries[i].cc;
38 if (cc->klass == Qundef) continue; // already invalidated
39 VM_ASSERT(cc->klass == Qundef || vm_cc_check_cme(cc, ccs->cme));
40 VM_ASSERT(!vm_cc_super_p(cc) && !vm_cc_refinement_p(cc));
41 vm_cc_invalidate(cc);
42 }
43 ruby_xfree(ccs);
44 return ID_TABLE_DELETE;
45 }
46 else {
47 rb_gc_mark_movable((VALUE)ccs->cme);
48
49 for (int i = 0; i < ccs->len; i++) {
50 const struct rb_callcache *cc = ccs->entries[i].cc;
51 VM_ASSERT(cc->klass == Qundef || vm_cc_check_cme(cc, ccs->cme));
52
53 rb_gc_mark_movable((VALUE)cc);
54 }
55 return ID_TABLE_CONTINUE;
56 }
57}
58
59static void
60vm_cc_table_mark(void *data)
61{
62 struct rb_id_table *tbl = (struct rb_id_table *)data;
63 if (tbl) {
64 rb_id_table_foreach_values(tbl, mark_cc_entry_i, NULL);
65 }
66}
67
68static enum rb_id_table_iterator_result
69cc_table_free_i(VALUE ccs_ptr, void *data)
70{
71 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_ptr;
72 VM_ASSERT(vm_ccs_p(ccs));
73
74 ruby_xfree(ccs);
75
76 return ID_TABLE_CONTINUE;
77}
78
79static void
80vm_cc_table_free(void *data)
81{
82 struct rb_id_table *tbl = (struct rb_id_table *)data;
83
84 rb_id_table_foreach_values(tbl, cc_table_free_i, NULL);
85 rb_managed_id_table_type.function.dfree(data);
86}
87
88static enum rb_id_table_iterator_result
89cc_table_memsize_i(VALUE ccs_ptr, void *data_ptr)
90{
91 size_t *total_size = data_ptr;
92 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_ptr;
93 *total_size += sizeof(*ccs);
94 *total_size += sizeof(ccs->entries[0]) * ccs->capa;
95 return ID_TABLE_CONTINUE;
96}
97
98static size_t
99vm_cc_table_memsize(const void *data)
100{
101 size_t memsize = rb_managed_id_table_type.function.dsize(data);
102 struct rb_id_table *tbl = (struct rb_id_table *)data;
103 rb_id_table_foreach_values(tbl, cc_table_memsize_i, &memsize);
104 return memsize;
105}
106
107static enum rb_id_table_iterator_result
108compact_cc_entry_i(VALUE ccs_ptr, void *data)
109{
110 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_ptr;
111
112 ccs->cme = (const struct rb_callable_method_entry_struct *)rb_gc_location((VALUE)ccs->cme);
113 VM_ASSERT(vm_ccs_p(ccs));
114
115 for (int i=0; i<ccs->len; i++) {
116 ccs->entries[i].cc = (const struct rb_callcache *)rb_gc_location((VALUE)ccs->entries[i].cc);
117 }
118
119 return ID_TABLE_CONTINUE;
120}
121
122static void
123vm_cc_table_compact(void *data)
124{
125 struct rb_id_table *tbl = (struct rb_id_table *)data;
126 rb_id_table_foreach_values(tbl, compact_cc_entry_i, NULL);
127}
128
129static const rb_data_type_t cc_table_type = {
130 .wrap_struct_name = "VM/cc_table",
131 .function = {
132 .dmark = vm_cc_table_mark,
133 .dfree = vm_cc_table_free,
134 .dsize = vm_cc_table_memsize,
135 .dcompact = vm_cc_table_compact,
136 },
137 .parent = &rb_managed_id_table_type,
138 .flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE,
139};
140
141VALUE
142rb_vm_cc_table_create(size_t capa)
143{
144 return rb_managed_id_table_create(&cc_table_type, capa);
145}
146
147static enum rb_id_table_iterator_result
148vm_cc_table_dup_i(ID key, VALUE old_ccs_ptr, void *data)
149{
150 VALUE new_table = (VALUE)data;
151 struct rb_class_cc_entries *old_ccs = (struct rb_class_cc_entries *)old_ccs_ptr;
152
153 if (METHOD_ENTRY_INVALIDATED(old_ccs->cme)) {
154 // Invalidated CME. This entry will be removed from the old table on
155 // the next GC mark, so it's unsafe (and undesirable) to copy
156 return ID_TABLE_CONTINUE;
157 }
158
159 size_t memsize = vm_ccs_alloc_size(old_ccs->capa);
160 struct rb_class_cc_entries *new_ccs = ruby_xcalloc(1, memsize);
161 rb_managed_id_table_insert(new_table, key, (VALUE)new_ccs);
162
163 // We hold the VM lock, so invalidation should not have happened between
164 // our earlier invalidation check and now.
165 VM_ASSERT(!METHOD_ENTRY_INVALIDATED(old_ccs->cme));
166
167 memcpy(new_ccs, old_ccs, memsize);
168
169#if VM_CHECK_MODE > 0
170 new_ccs->debug_sig = ~(VALUE)new_ccs;
171#endif
172
173 RB_OBJ_WRITTEN(new_table, Qundef, (VALUE)new_ccs->cme);
174 for (int index = 0; index < new_ccs->len; index++) {
175 RB_OBJ_WRITTEN(new_table, Qundef, new_ccs->entries[index].cc);
176 }
177 return ID_TABLE_CONTINUE;
178}
179
180VALUE
181rb_vm_cc_table_dup(VALUE old_table)
182{
183 ASSERT_vm_locking();
184 VALUE new_table = rb_vm_cc_table_create(rb_managed_id_table_size(old_table));
185 rb_managed_id_table_foreach(old_table, vm_cc_table_dup_i, (void *)new_table);
186 return new_table;
187}
188
189static void
190vm_ccs_invalidate(struct rb_class_cc_entries *ccs)
191{
192 for (int i=0; i<ccs->len; i++) {
193 const struct rb_callcache *cc = ccs->entries[i].cc;
194 VM_ASSERT(!vm_cc_super_p(cc) && !vm_cc_refinement_p(cc));
195 vm_cc_invalidate(cc);
196 }
197}
198
199static void
200rb_vm_ccs_invalidate_and_free(struct rb_class_cc_entries *ccs)
201{
202 RB_DEBUG_COUNTER_INC(ccs_free);
203 vm_ccs_invalidate(ccs);
204 ruby_xfree(ccs);
205}
206
207void
208rb_vm_cc_table_delete(VALUE table, ID mid)
209{
210 VALUE ccs_obj;
211 if (rb_managed_id_table_lookup(table, mid, &ccs_obj)) {
212 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_obj;
213 rb_managed_id_table_delete(table, mid);
214 rb_vm_ccs_invalidate_and_free(ccs);
215 }
216}
217
218static enum rb_id_table_iterator_result
219vm_ccs_dump_i(ID mid, VALUE val, void *data)
220{
221 const struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)val;
222 fprintf(stderr, " | %s (len:%d) ", rb_id2name(mid), ccs->len);
223 rp(ccs->cme);
224
225 for (int i=0; i<ccs->len; i++) {
226 rp_m( " | \t", ccs->entries[i].cc);
227 }
228
229 return ID_TABLE_CONTINUE;
230}
231
232static void
233vm_ccs_dump(VALUE klass, ID target_mid)
234{
235 VALUE cc_tbl = RCLASS_WRITABLE_CC_TBL(klass);
236 if (cc_tbl) {
237 VALUE ccs;
238 if (target_mid) {
239 if (rb_managed_id_table_lookup(cc_tbl, target_mid, &ccs)) {
240 fprintf(stderr, " [CCTB] %p\n", (void *)cc_tbl);
241 vm_ccs_dump_i(target_mid, ccs, NULL);
242 }
243 }
244 else {
245 fprintf(stderr, " [CCTB] %p\n", (void *)cc_tbl);
246 rb_managed_id_table_foreach(cc_tbl, vm_ccs_dump_i, (void *)target_mid);
247 }
248 }
249}
250
251static enum rb_id_table_iterator_result
252vm_cme_dump_i(ID mid, VALUE val, void *data)
253{
254 ID target_mid = (ID)data;
255 if (target_mid == 0 || mid == target_mid) {
256 rp_m(" > ", val);
257 }
258 return ID_TABLE_CONTINUE;
259}
260
261static VALUE
262vm_mtbl_dump(VALUE klass, ID target_mid)
263{
264 fprintf(stderr, "# vm_mtbl\n");
265 while (klass) {
266 rp_m(" -> ", klass);
267 VALUE me;
268
269 if (RCLASS_M_TBL(klass)) {
270 if (target_mid != 0) {
271 if (rb_id_table_lookup(RCLASS_M_TBL(klass), target_mid, &me)) {
272 rp_m(" [MTBL] ", me);
273 }
274 }
275 else {
276 fprintf(stderr, " ## RCLASS_M_TBL (%p)\n", (void *)RCLASS_M_TBL(klass));
277 rb_id_table_foreach(RCLASS_M_TBL(klass), vm_cme_dump_i, NULL);
278 }
279 }
280 else {
281 fprintf(stderr, " MTBL: NULL\n");
282 }
283 if (RCLASS_WRITABLE_CALLABLE_M_TBL(klass)) {
284 if (target_mid != 0) {
285 if (rb_id_table_lookup(RCLASS_WRITABLE_CALLABLE_M_TBL(klass), target_mid, &me)) {
286 rp_m(" [CM**] ", me);
287 }
288 }
289 else {
290 fprintf(stderr, " ## RCLASS_CALLABLE_M_TBL\n");
291 rb_id_table_foreach(RCLASS_WRITABLE_CALLABLE_M_TBL(klass), vm_cme_dump_i, NULL);
292 }
293 }
294 if (RCLASS_WRITABLE_CC_TBL(klass)) {
295 vm_ccs_dump(klass, target_mid);
296 }
297 klass = RCLASS_SUPER(klass);
298 }
299 return Qnil;
300}
301
302void
303rb_vm_mtbl_dump(const char *msg, VALUE klass, ID target_mid)
304{
305 fprintf(stderr, "[%s] ", msg);
306 vm_mtbl_dump(klass, target_mid);
307}
308
309static inline void
310vm_cme_invalidate(rb_callable_method_entry_t *cme)
311{
312 VM_ASSERT(IMEMO_TYPE_P(cme, imemo_ment), "cme: %d", imemo_type((VALUE)cme));
313 VM_ASSERT(callable_method_entry_p(cme));
314 METHOD_ENTRY_INVALIDATED_SET(cme);
315 RB_DEBUG_COUNTER_INC(cc_cme_invalidate);
316
317 rb_yjit_cme_invalidate(cme);
318 rb_zjit_cme_invalidate(cme);
319}
320
321static int
322rb_clear_constant_cache_for_id_i(st_data_t ic, st_data_t arg)
323{
324 ((IC) ic)->entry = NULL;
325 return ST_CONTINUE;
326}
327
328// Here for backward compat.
329void rb_clear_constant_cache(void) {}
330
331void
333{
334 VALUE lookup_result;
335 rb_vm_t *vm = GET_VM();
336
337 if (rb_id_table_lookup(vm->constant_cache, id, &lookup_result)) {
338 set_table *ics = (set_table *)lookup_result;
339 set_table_foreach(ics, rb_clear_constant_cache_for_id_i, (st_data_t) NULL);
340 ruby_vm_constant_cache_invalidations += ics->num_entries;
341 }
342
343 rb_yjit_constant_state_changed(id);
344 rb_zjit_constant_state_changed(id);
345}
346
347static void
348invalidate_negative_cache(ID mid)
349{
350 VALUE cme;
351 rb_vm_t *vm = GET_VM();
352
353 if (rb_id_table_lookup(vm->negative_cme_table, mid, &cme)) {
354 rb_id_table_delete(vm->negative_cme_table, mid);
355 vm_cme_invalidate((rb_callable_method_entry_t *)cme);
356 RB_DEBUG_COUNTER_INC(cc_invalidate_negative);
357 }
358}
359
360const rb_method_entry_t * rb_method_entry_clone(const rb_method_entry_t *src_me);
361static const rb_callable_method_entry_t *complemented_callable_method_entry(VALUE klass, ID id);
362static const rb_callable_method_entry_t *lookup_overloaded_cme(const rb_callable_method_entry_t *cme);
363
364static void
365invalidate_method_cache_in_cc_table(VALUE tbl, ID mid)
366{
367 VALUE ccs_data;
368 if (tbl && rb_managed_id_table_lookup(tbl, mid, &ccs_data)) {
369 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_data;
370 rb_yjit_cme_invalidate((rb_callable_method_entry_t *)ccs->cme);
371 rb_zjit_cme_invalidate((rb_callable_method_entry_t *)ccs->cme);
372 if (NIL_P(ccs->cme->owner)) invalidate_negative_cache(mid);
373 rb_vm_ccs_invalidate_and_free(ccs);
374 rb_managed_id_table_delete(tbl, mid);
375 RB_DEBUG_COUNTER_INC(cc_invalidate_leaf_ccs);
376 }
377}
378
379static void
380invalidate_callable_method_entry_in_callable_m_table(struct rb_id_table *tbl, ID mid)
381{
382 VALUE cme;
383 if (tbl && rb_id_table_lookup(tbl, mid, &cme)) {
384 rb_yjit_cme_invalidate((rb_callable_method_entry_t *)cme);
385 rb_zjit_cme_invalidate((rb_callable_method_entry_t *)cme);
386 rb_id_table_delete(tbl, mid);
387 RB_DEBUG_COUNTER_INC(cc_invalidate_leaf_callable);
388 }
389}
390
392 VALUE klass;
393 ID mid;
394 const rb_method_entry_t *cme;
395 const rb_method_entry_t *newer;
396};
397
398static void
399invalidate_callable_method_entry_in_every_m_table_i(rb_classext_t *ext, bool is_prime, VALUE box_value, void *data)
400{
401 st_data_t me;
403 struct rb_id_table *tbl = RCLASSEXT_M_TBL(ext);
404
405 if (rb_id_table_lookup(tbl, arg->mid, &me) && arg->cme == (const rb_method_entry_t *)me) {
406 rb_method_table_insert(arg->klass, tbl, arg->mid, arg->newer);
407 }
408}
409
410static void
411invalidate_callable_method_entry_in_every_m_table(VALUE klass, ID mid, const rb_callable_method_entry_t *cme)
412{
413 // The argument cme must be invalidated later in the caller side
414 const rb_method_entry_t *newer = rb_method_entry_clone((const rb_method_entry_t *)cme);
416 .klass = klass,
417 .mid = mid,
418 .cme = (const rb_method_entry_t *) cme,
419 .newer = newer,
420 };
421 rb_class_classext_foreach(klass, invalidate_callable_method_entry_in_every_m_table_i, (void *)&arg);
422}
423
424static void
425invalidate_complemented_method_entry_in_callable_m_table(struct rb_id_table *tbl, ID mid)
426{
427 VALUE cme;
428 if (tbl && rb_id_table_lookup(tbl, mid, &cme)) {
429 rb_yjit_cme_invalidate((rb_callable_method_entry_t *)cme);
430 rb_zjit_cme_invalidate((rb_callable_method_entry_t *)cme);
431 rb_id_table_delete(tbl, mid);
432 RB_DEBUG_COUNTER_INC(cc_invalidate_tree_callable);
433 }
434}
435
436static void
437clear_method_cache_by_id_in_class(VALUE klass, ID mid)
438{
439 VM_ASSERT_TYPE2(klass, T_CLASS, T_ICLASS);
440 if (rb_objspace_garbage_object_p(klass)) return;
441
442 RB_VM_LOCKING() {
443 rb_vm_barrier();
444
445 if (LIKELY(RCLASS_SUBCLASSES_FIRST(klass) == NULL)) {
446 // no subclasses
447 // check only current class
448
449 // invalidate CCs
450 VALUE cc_tbl = RCLASS_WRITABLE_CC_TBL(klass);
451 invalidate_method_cache_in_cc_table(cc_tbl, mid);
452 if (RCLASS_CC_TBL_NOT_PRIME_P(klass, cc_tbl)) {
453 invalidate_method_cache_in_cc_table(RCLASS_PRIME_CC_TBL(klass), mid);
454 }
455
456 // remove from callable_m_tbl, if exists
457 struct rb_id_table *cm_tbl = RCLASS_WRITABLE_CALLABLE_M_TBL(klass);
458 invalidate_callable_method_entry_in_callable_m_table(cm_tbl, mid);
459 if (RCLASS_CALLABLE_M_TBL_NOT_PRIME_P(klass, cm_tbl)) {
460 invalidate_callable_method_entry_in_callable_m_table(RCLASS_PRIME_CALLABLE_M_TBL(klass), mid);
461 }
462
463 RB_DEBUG_COUNTER_INC(cc_invalidate_leaf);
464 }
465 else {
466 const rb_callable_method_entry_t *cme = complemented_callable_method_entry(klass, mid);
467
468 if (cme) {
469 // invalidate cme if found to invalidate the inline method cache.
470 if (METHOD_ENTRY_CACHED(cme)) {
471 if (METHOD_ENTRY_COMPLEMENTED(cme)) {
472 // do nothing
473 }
474 else {
475 // invalidate cc by invalidating cc->cme
476 VALUE owner = cme->owner;
477 VM_ASSERT_TYPE(owner, T_CLASS);
478 VALUE klass_housing_cme;
479 if (cme->def->type == VM_METHOD_TYPE_REFINED && !cme->def->body.refined.orig_me) {
480 klass_housing_cme = owner;
481 }
482 else {
483 klass_housing_cme = RCLASS_ORIGIN(owner);
484 }
485
486 // replace the cme that will be invalid in the all classexts
487 invalidate_callable_method_entry_in_every_m_table(klass_housing_cme, mid, cme);
488 }
489
490 vm_cme_invalidate((rb_callable_method_entry_t *)cme);
491 RB_DEBUG_COUNTER_INC(cc_invalidate_tree_cme);
492
493 // In case of refinement ME, also invalidate the wrapped ME that
494 // could be cached at some callsite and is unreachable from any
495 // RCLASS_WRITABLE_CC_TBL.
496 if (cme->def->type == VM_METHOD_TYPE_REFINED && cme->def->body.refined.orig_me) {
497 vm_cme_invalidate((rb_callable_method_entry_t *)cme->def->body.refined.orig_me);
498 }
499
500 if (cme->def->iseq_overload) {
501 rb_callable_method_entry_t *monly_cme = (rb_callable_method_entry_t *)lookup_overloaded_cme(cme);
502 if (monly_cme) {
503 vm_cme_invalidate(monly_cme);
504 }
505 }
506 }
507
508 // invalidate complement tbl
509 if (METHOD_ENTRY_COMPLEMENTED(cme)) {
510 VALUE defined_class = cme->defined_class;
511 struct rb_id_table *cm_tbl = RCLASS_WRITABLE_CALLABLE_M_TBL(defined_class);
512 invalidate_complemented_method_entry_in_callable_m_table(cm_tbl, mid);
513 if (RCLASS_CALLABLE_M_TBL_NOT_PRIME_P(defined_class, cm_tbl)) {
514 struct rb_id_table *prime_cm_table = RCLASS_PRIME_CALLABLE_M_TBL(defined_class);
515 invalidate_complemented_method_entry_in_callable_m_table(prime_cm_table, mid);
516 }
517 }
518
519 RB_DEBUG_COUNTER_INC(cc_invalidate_tree);
520 }
521 else {
522 invalidate_negative_cache(mid);
523 }
524 }
525
526 rb_gccct_clear_table(Qnil);
527 }
528}
529
530static void
531clear_iclass_method_cache_by_id(VALUE iclass, VALUE d)
532{
533 VM_ASSERT_TYPE(iclass, T_ICLASS);
534 ID mid = (ID)d;
535 clear_method_cache_by_id_in_class(iclass, mid);
536}
537
538static void
539clear_iclass_method_cache_by_id_for_refinements(VALUE klass, VALUE d)
540{
541 if (RB_TYPE_P(klass, T_ICLASS)) {
542 ID mid = (ID)d;
543 clear_method_cache_by_id_in_class(klass, mid);
544 }
545}
546
547void
548rb_clear_method_cache(VALUE klass_or_module, ID mid)
549{
550 if (RB_TYPE_P(klass_or_module, T_MODULE)) {
551 VALUE module = klass_or_module; // alias
552
553 if (FL_TEST(module, RMODULE_IS_REFINEMENT)) {
554 VALUE refined_class = rb_refinement_module_get_refined_class(module);
555 rb_clear_method_cache(refined_class, mid);
556 rb_class_foreach_subclass(refined_class, clear_iclass_method_cache_by_id_for_refinements, mid);
557 rb_clear_all_refinement_method_cache();
558 }
559 rb_class_foreach_subclass(module, clear_iclass_method_cache_by_id, mid);
560 }
561 else {
562 clear_method_cache_by_id_in_class(klass_or_module, mid);
563 }
564}
565
566static enum rb_id_table_iterator_result
567invalidate_method_entry_in_iclass_callable_m_tbl(VALUE cme, void *data)
568{
569 vm_cme_invalidate((rb_callable_method_entry_t *)cme);
570 return ID_TABLE_DELETE;
571}
572
573static enum rb_id_table_iterator_result
574invalidate_ccs_in_iclass_cc_tbl(VALUE value, void *data)
575{
576 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)value;
577 vm_cme_invalidate((rb_callable_method_entry_t *)ccs->cme);
578 xfree(ccs);
579 return ID_TABLE_DELETE;
580}
581
582void
583rb_invalidate_method_caches(struct rb_id_table *cm_tbl, VALUE cc_tbl)
584{
585 if (cm_tbl) {
586 rb_id_table_foreach_values(cm_tbl, invalidate_method_entry_in_iclass_callable_m_tbl, NULL);
587 }
588 if (cc_tbl) {
589 rb_managed_id_table_foreach_values(cc_tbl, invalidate_ccs_in_iclass_cc_tbl, NULL);
590 }
591}
592
593static int
594invalidate_cc_refinement(st_data_t key, st_data_t data)
595{
596 VALUE v = (VALUE)key;
597 void *ptr = rb_asan_poisoned_object_p(v);
598 rb_asan_unpoison_object(v, false);
599
600 if (rb_gc_pointer_to_heap_p(v) &&
601 !rb_objspace_garbage_object_p(v) &&
602 RBASIC(v)->flags) { // liveness check
603 const struct rb_callcache *cc = (const struct rb_callcache *)v;
604
605 VM_ASSERT(vm_cc_refinement_p(cc));
606
607 if (vm_cc_valid(cc)) {
608 vm_cc_invalidate(cc);
609 }
610 }
611
612 if (ptr) {
613 rb_asan_poison_object(v);
614 }
615
616 return ST_CONTINUE;
617}
618
619static st_index_t
620vm_ci_hash(VALUE v)
621{
622 const struct rb_callinfo *ci = (const struct rb_callinfo *)v;
623 st_index_t h;
624 h = rb_hash_start(ci->mid);
625 h = rb_hash_uint(h, ci->flag);
626 h = rb_hash_uint(h, ci->argc);
627 if (ci->kwarg) {
628 for (int i = 0; i < ci->kwarg->keyword_len; i++) {
629 h = rb_hash_uint(h, ci->kwarg->keywords[i]);
630 }
631 }
632 return h;
633}
634
635static int
636vm_ci_hash_cmp(VALUE v1, VALUE v2)
637{
638 const struct rb_callinfo *ci1 = (const struct rb_callinfo *)v1;
639 const struct rb_callinfo *ci2 = (const struct rb_callinfo *)v2;
640 if (ci1->mid != ci2->mid) return 1;
641 if (ci1->flag != ci2->flag) return 1;
642 if (ci1->argc != ci2->argc) return 1;
643 if (ci1->kwarg != NULL) {
644 VM_ASSERT(ci2->kwarg != NULL); // implied by matching flags
645
646 if (ci1->kwarg->keyword_len != ci2->kwarg->keyword_len)
647 return 1;
648
649 for (int i = 0; i < ci1->kwarg->keyword_len; i++) {
650 if (ci1->kwarg->keywords[i] != ci2->kwarg->keywords[i]) {
651 return 1;
652 }
653 }
654 }
655 else {
656 VM_ASSERT(ci2->kwarg == NULL); // implied by matching flags
657 }
658 return 0;
659}
660
661static const struct st_hash_type vm_ci_hashtype = {
662 vm_ci_hash_cmp,
663 vm_ci_hash
664};
665
666static int
667ci_lookup_i(st_data_t *key, st_data_t *value, st_data_t data, int existing)
668{
669 const struct rb_callinfo *ci = (const struct rb_callinfo *)*key;
670 st_data_t *ret = (st_data_t *)data;
671
672 if (existing) {
673 if (rb_objspace_garbage_object_p((VALUE)ci)) {
674 *ret = (st_data_t)NULL;
675 return ST_DELETE;
676 }
677 else {
678 *ret = *key;
679 return ST_STOP;
680 }
681 }
682 else {
683 *key = *value = *ret = (st_data_t)ci;
684 return ST_CONTINUE;
685 }
686}
687
688const struct rb_callinfo *
689rb_vm_ci_lookup(ID mid, unsigned int flag, unsigned int argc, const struct rb_callinfo_kwarg *kwarg)
690{
691 rb_vm_t *vm = GET_VM();
692 const struct rb_callinfo *ci = NULL;
693
694 if (kwarg) {
695 ((struct rb_callinfo_kwarg *)kwarg)->references++;
696 }
697
698 struct rb_callinfo *new_ci = SHAREABLE_IMEMO_NEW(struct rb_callinfo, imemo_callinfo, (VALUE)kwarg);
699 new_ci->mid = mid;
700 new_ci->flag = flag;
701 new_ci->argc = argc;
702
703 RB_VM_LOCKING() {
704 st_table *ci_table = vm->ci_table;
705 VM_ASSERT(ci_table);
706
707 do {
708 st_update(ci_table, (st_data_t)new_ci, ci_lookup_i, (st_data_t)&ci);
709 } while (ci == NULL);
710 }
711
712 VM_ASSERT(ci);
713
714 return ci;
715}
716
717void
718rb_vm_ci_free(const struct rb_callinfo *ci)
719{
720 ASSERT_vm_locking();
721
722 rb_vm_t *vm = GET_VM();
723
724 st_data_t key = (st_data_t)ci;
725 st_delete(vm->ci_table, &key, NULL);
726}
727
728void
729rb_vm_insert_cc_refinement(const struct rb_callcache *cc)
730{
731 st_data_t key = (st_data_t)cc;
732
733 rb_vm_t *vm = GET_VM();
734 RB_VM_LOCK_ENTER();
735 {
736 rb_set_insert(vm->cc_refinement_table, key);
737 }
738 RB_VM_LOCK_LEAVE();
739}
740
741void
742rb_vm_delete_cc_refinement(const struct rb_callcache *cc)
743{
744 ASSERT_vm_locking();
745
746 rb_vm_t *vm = GET_VM();
747 st_data_t key = (st_data_t)cc;
748
749 rb_set_table_delete(vm->cc_refinement_table, &key);
750}
751
752void
753rb_clear_all_refinement_method_cache(void)
754{
755 rb_vm_t *vm = GET_VM();
756
757 RB_VM_LOCK_ENTER();
758 {
759 rb_set_table_foreach(vm->cc_refinement_table, invalidate_cc_refinement, (st_data_t)NULL);
760 rb_set_table_clear(vm->cc_refinement_table);
761 rb_set_compact_table(vm->cc_refinement_table);
762 }
763 RB_VM_LOCK_LEAVE();
764
765 rb_yjit_invalidate_all_method_lookup_assumptions();
766}
767
768void
769rb_method_table_insert(VALUE klass, struct rb_id_table *table, ID method_id, const rb_method_entry_t *me)
770{
771 RB_VM_LOCKING() {
772 rb_method_table_insert0(klass, table, method_id, me, RB_TYPE_P(klass, T_ICLASS) && !RICLASS_OWNS_M_TBL_P(klass));
773 }
774}
775
776void
777rb_method_table_insert0(VALUE klass, struct rb_id_table *table, ID method_id, const rb_method_entry_t *me, bool iclass_shared_mtbl)
778{
779 VALUE table_owner = klass;
780 if (iclass_shared_mtbl) {
781 table_owner = RBASIC(table_owner)->klass;
782 }
783 VM_ASSERT_TYPE3(table_owner, T_CLASS, T_ICLASS, T_MODULE);
784 rb_id_table_insert(table, method_id, (VALUE)me);
785 RB_OBJ_WRITTEN(table_owner, Qundef, (VALUE)me);
786}
787
788// rb_f_notimplement has an extra trailing argument to distinguish it from other methods
789// at compile-time to override arity to be -1. But the trailing argument introduces a
790// signature mismatch between caller and callee, so rb_define_method family inserts a
791// method entry with rb_f_notimplement_internal, which has canonical arity=-1 signature,
792// instead of rb_f_notimplement.
793NORETURN(static VALUE rb_f_notimplement_internal(int argc, const VALUE *argv, VALUE obj));
794
795static VALUE
796rb_f_notimplement_internal(int argc, const VALUE *argv, VALUE obj)
797{
799
801}
802
803VALUE
804rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
805{
806 rb_f_notimplement_internal(argc, argv, obj);
807}
808
809static void
810rb_define_notimplement_method_id(VALUE mod, ID id, rb_method_visibility_t visi)
811{
812 rb_add_method(mod, id, VM_METHOD_TYPE_NOTIMPLEMENTED, (void *)1, visi);
813}
814
815void
816rb_add_method_cfunc(VALUE klass, ID mid, VALUE (*func)(ANYARGS), int argc, rb_method_visibility_t visi)
817{
818 if (argc < -2 || 15 < argc) rb_raise(rb_eArgError, "arity out of range: %d for -2..15", argc);
819 if (func != (VALUE(*)(ANYARGS))rb_f_notimplement) {
821 opt.func = func;
822 opt.argc = argc;
823 rb_add_method(klass, mid, VM_METHOD_TYPE_CFUNC, &opt, visi);
824 }
825 else {
826 rb_define_notimplement_method_id(klass, mid, visi);
827 }
828}
829
830void
831rb_add_method_optimized(VALUE klass, ID mid, enum method_optimized_type opt_type, unsigned int index, rb_method_visibility_t visi)
832{
834 .type = opt_type,
835 .index = index,
836 };
837 rb_add_method(klass, mid, VM_METHOD_TYPE_OPTIMIZED, &opt, visi);
838}
839
840static void
841method_definition_release(rb_method_definition_t *def)
842{
843 if (def != NULL) {
844 const unsigned int reference_count_was = RUBY_ATOMIC_FETCH_SUB(def->reference_count, 1);
845
846 RUBY_ASSERT_ALWAYS(reference_count_was != 0);
847
848 if (reference_count_was == 1) {
849 if (METHOD_DEBUG) fprintf(stderr, "-%p-%s:1->0 (remove)\n", (void *)def,
850 rb_id2name(def->original_id));
851 xfree(def);
852 }
853 else {
854 if (METHOD_DEBUG) fprintf(stderr, "-%p-%s:%d->%d (dec)\n", (void *)def, rb_id2name(def->original_id),
855 reference_count_was, reference_count_was - 1);
856 }
857 }
858}
859
860void
861rb_method_definition_release(rb_method_definition_t *def)
862{
863 method_definition_release(def);
864}
865
866static void delete_overloaded_cme(const rb_callable_method_entry_t *cme);
867
868void
869rb_free_method_entry_vm_weak_references(const rb_method_entry_t *me)
870{
871 if (me->def && me->def->iseq_overload) {
872 delete_overloaded_cme((const rb_callable_method_entry_t *)me);
873 }
874}
875
876void
877rb_free_method_entry(const rb_method_entry_t *me)
878{
879#if USE_ZJIT
880 if (METHOD_ENTRY_CACHED(me)) {
881 rb_zjit_cme_free((const rb_callable_method_entry_t *)me);
882 }
883#endif
884
885#if USE_YJIT
886 // YJIT rb_yjit_root_mark() roots CMEs in `Invariants`,
887 // to remove from `Invariants` here.
888#endif
889
890 method_definition_release(me->def);
891}
892
893static inline rb_method_entry_t *search_method(VALUE klass, ID id, VALUE *defined_class_ptr);
894extern int rb_method_definition_eq(const rb_method_definition_t *d1, const rb_method_definition_t *d2);
895
896static VALUE
897(*call_cfunc_invoker_func(int argc))(VALUE recv, int argc, const VALUE *, VALUE (*func)(ANYARGS))
898{
899 if (!GET_THREAD()->ext_config.ractor_safe) {
900 switch (argc) {
901 case -2: return &call_cfunc_m2;
902 case -1: return &call_cfunc_m1;
903 case 0: return &call_cfunc_0;
904 case 1: return &call_cfunc_1;
905 case 2: return &call_cfunc_2;
906 case 3: return &call_cfunc_3;
907 case 4: return &call_cfunc_4;
908 case 5: return &call_cfunc_5;
909 case 6: return &call_cfunc_6;
910 case 7: return &call_cfunc_7;
911 case 8: return &call_cfunc_8;
912 case 9: return &call_cfunc_9;
913 case 10: return &call_cfunc_10;
914 case 11: return &call_cfunc_11;
915 case 12: return &call_cfunc_12;
916 case 13: return &call_cfunc_13;
917 case 14: return &call_cfunc_14;
918 case 15: return &call_cfunc_15;
919 default:
920 rb_bug("unsupported length: %d", argc);
921 }
922 }
923 else {
924 switch (argc) {
925 case -2: return &ractor_safe_call_cfunc_m2;
926 case -1: return &ractor_safe_call_cfunc_m1;
927 case 0: return &ractor_safe_call_cfunc_0;
928 case 1: return &ractor_safe_call_cfunc_1;
929 case 2: return &ractor_safe_call_cfunc_2;
930 case 3: return &ractor_safe_call_cfunc_3;
931 case 4: return &ractor_safe_call_cfunc_4;
932 case 5: return &ractor_safe_call_cfunc_5;
933 case 6: return &ractor_safe_call_cfunc_6;
934 case 7: return &ractor_safe_call_cfunc_7;
935 case 8: return &ractor_safe_call_cfunc_8;
936 case 9: return &ractor_safe_call_cfunc_9;
937 case 10: return &ractor_safe_call_cfunc_10;
938 case 11: return &ractor_safe_call_cfunc_11;
939 case 12: return &ractor_safe_call_cfunc_12;
940 case 13: return &ractor_safe_call_cfunc_13;
941 case 14: return &ractor_safe_call_cfunc_14;
942 case 15: return &ractor_safe_call_cfunc_15;
943 default:
944 rb_bug("unsupported length: %d", argc);
945 }
946 }
947}
948
949static void
950setup_method_cfunc_struct(rb_method_cfunc_t *cfunc, VALUE (*func)(ANYARGS), int argc)
951{
952 cfunc->func = func;
953 cfunc->argc = argc;
954 cfunc->invoker = call_cfunc_invoker_func(argc);
955}
956
957
959method_definition_addref(rb_method_definition_t *def, bool complemented)
960{
961 unsigned int reference_count_was = RUBY_ATOMIC_FETCH_ADD(def->reference_count, 1);
962 if (!complemented && reference_count_was > 0) {
963 /* TODO: A Ractor can reach this via UnboundMethod#bind */
964 def->aliased = true;
965 }
966 if (METHOD_DEBUG) fprintf(stderr, "+%p-%s:%d->%d\n", (void *)def, rb_id2name(def->original_id), reference_count_was, reference_count_was+1);
967
968 return def;
969}
970
971void
972rb_method_definition_addref(rb_method_definition_t *def)
973{
974 method_definition_addref(def, false);
975}
976
977void
978rb_method_definition_set(const rb_method_entry_t *me, rb_method_definition_t *def, void *opts)
979{
980 method_definition_release(me->def);
981 *(rb_method_definition_t **)&me->def = method_definition_addref(def, METHOD_ENTRY_COMPLEMENTED(me));
982
983 if (!ruby_running) add_opt_method_entry(me);
984
985 if (opts != NULL) {
986 switch (def->type) {
987 case VM_METHOD_TYPE_ISEQ:
988 {
989 rb_method_iseq_t *iseq_body = (rb_method_iseq_t *)opts;
990 const rb_iseq_t *iseq = iseq_body->iseqptr;
991 rb_cref_t *method_cref, *cref = iseq_body->cref;
992
993 /* setup iseq first (before invoking GC) */
994 RB_OBJ_WRITE(me, &def->body.iseq.iseqptr, iseq);
995
996 // Methods defined in `with_jit` should be considered METHOD_ENTRY_BASIC
997 if (rb_iseq_attr_p(iseq, BUILTIN_ATTR_C_TRACE)) {
998 METHOD_ENTRY_BASIC_SET((rb_method_entry_t *)me, TRUE);
999 }
1000
1001 if (ISEQ_BODY(iseq)->mandatory_only_iseq) def->iseq_overload = 1;
1002
1003 if (0) vm_cref_dump("rb_method_definition_create", cref);
1004
1005 if (cref) {
1006 method_cref = cref;
1007 }
1008 else {
1009 method_cref = vm_cref_new_toplevel(GET_EC()); /* TODO: can we reuse? */
1010 }
1011
1012 RB_OBJ_WRITE(me, &def->body.iseq.cref, method_cref);
1013 return;
1014 }
1015 case VM_METHOD_TYPE_CFUNC:
1016 {
1017 rb_method_cfunc_t *cfunc = (rb_method_cfunc_t *)opts;
1018 setup_method_cfunc_struct(UNALIGNED_MEMBER_PTR(def, body.cfunc), cfunc->func, cfunc->argc);
1019 return;
1020 }
1021 case VM_METHOD_TYPE_ATTRSET:
1022 case VM_METHOD_TYPE_IVAR:
1023 {
1024 const rb_execution_context_t *ec = GET_EC();
1025 rb_control_frame_t *cfp;
1026 int line;
1027
1028 def->body.attr.id = (ID)(VALUE)opts;
1029
1030 cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
1031
1032 if (cfp && (line = rb_vm_get_sourceline(cfp))) {
1033 VALUE location = rb_ary_new3(2, rb_iseq_path(cfp->iseq), INT2FIX(line));
1034 rb_ary_freeze(location);
1035 RB_OBJ_SET_SHAREABLE(location);
1036 RB_OBJ_WRITE(me, &def->body.attr.location, location);
1037 }
1038 else {
1039 VM_ASSERT(def->body.attr.location == 0);
1040 }
1041 return;
1042 }
1043 case VM_METHOD_TYPE_BMETHOD:
1044 RB_OBJ_WRITE(me, &def->body.bmethod.proc, (VALUE)opts);
1045 def->body.bmethod.defined_ractor_id = rb_ec_ractor_id(GET_EC());
1046 return;
1047 case VM_METHOD_TYPE_NOTIMPLEMENTED:
1048 setup_method_cfunc_struct(UNALIGNED_MEMBER_PTR(def, body.cfunc), (VALUE(*)(ANYARGS))rb_f_notimplement_internal, -1);
1049 return;
1050 case VM_METHOD_TYPE_OPTIMIZED:
1051 def->body.optimized = *(rb_method_optimized_t *)opts;
1052 return;
1053 case VM_METHOD_TYPE_REFINED:
1054 {
1055 RB_OBJ_WRITE(me, &def->body.refined.orig_me, (rb_method_entry_t *)opts);
1056 return;
1057 }
1058 case VM_METHOD_TYPE_ALIAS:
1059 RB_OBJ_WRITE(me, &def->body.alias.original_me, (rb_method_entry_t *)opts);
1060 return;
1061 case VM_METHOD_TYPE_ZSUPER:
1062 case VM_METHOD_TYPE_UNDEF:
1063 case VM_METHOD_TYPE_MISSING:
1064 return;
1065 }
1066 }
1067}
1068
1069static void
1070method_definition_reset(const rb_method_entry_t *me)
1071{
1072 rb_method_definition_t *def = me->def;
1073
1074 switch (def->type) {
1075 case VM_METHOD_TYPE_ISEQ:
1076 RB_OBJ_WRITTEN(me, Qundef, def->body.iseq.iseqptr);
1077 RB_OBJ_WRITTEN(me, Qundef, def->body.iseq.cref);
1078 break;
1079 case VM_METHOD_TYPE_ATTRSET:
1080 case VM_METHOD_TYPE_IVAR:
1081 RB_OBJ_WRITTEN(me, Qundef, def->body.attr.location);
1082 break;
1083 case VM_METHOD_TYPE_BMETHOD:
1084 RB_OBJ_WRITTEN(me, Qundef, def->body.bmethod.proc);
1085 break;
1086 case VM_METHOD_TYPE_REFINED:
1087 RB_OBJ_WRITTEN(me, Qundef, def->body.refined.orig_me);
1088 break;
1089 case VM_METHOD_TYPE_ALIAS:
1090 RB_OBJ_WRITTEN(me, Qundef, def->body.alias.original_me);
1091 break;
1092 case VM_METHOD_TYPE_CFUNC:
1093 case VM_METHOD_TYPE_ZSUPER:
1094 case VM_METHOD_TYPE_MISSING:
1095 case VM_METHOD_TYPE_OPTIMIZED:
1096 case VM_METHOD_TYPE_UNDEF:
1097 case VM_METHOD_TYPE_NOTIMPLEMENTED:
1098 break;
1099 }
1100}
1101
1102static rb_atomic_t method_serial = 1;
1103
1105rb_method_definition_create(rb_method_type_t type, ID mid)
1106{
1109 def->type = type;
1110 def->original_id = mid;
1111 def->method_serial = (uintptr_t)RUBY_ATOMIC_FETCH_ADD(method_serial, 1);
1112 def->box = rb_current_box();
1113 return def;
1114}
1115
1116static rb_method_entry_t *
1117rb_method_entry_alloc(ID called_id, VALUE owner, VALUE defined_class, rb_method_definition_t *def, bool complement)
1118{
1119 if (def) method_definition_addref(def, complement);
1120 if (RTEST(defined_class)) {
1121 // not negative cache
1122 VM_ASSERT_TYPE2(defined_class, T_CLASS, T_ICLASS);
1123 }
1124 rb_method_entry_t *me = SHAREABLE_IMEMO_NEW(rb_method_entry_t, imemo_ment, defined_class);
1125 *((rb_method_definition_t **)&me->def) = def;
1126 me->called_id = called_id;
1127 me->owner = owner;
1128
1129 return me;
1130}
1131
1132static VALUE
1133filter_defined_class(VALUE klass)
1134{
1135 switch (BUILTIN_TYPE(klass)) {
1136 case T_CLASS:
1137 return klass;
1138 case T_MODULE:
1139 return 0;
1140 case T_ICLASS:
1141 break;
1142 default:
1143 break;
1144 }
1145 rb_bug("filter_defined_class: %s", rb_obj_info(klass));
1146}
1147
1149rb_method_entry_create(ID called_id, VALUE klass, rb_method_visibility_t visi, rb_method_definition_t *def)
1150{
1151 rb_method_entry_t *me = rb_method_entry_alloc(called_id, klass, filter_defined_class(klass), def, false);
1152 METHOD_ENTRY_FLAGS_SET(me, visi, ruby_running ? FALSE : TRUE);
1153 if (def != NULL) method_definition_reset(me);
1154 return me;
1155}
1156
1157// Return a cloned ME that's not invalidated (MEs are disposable for caching).
1158const rb_method_entry_t *
1159rb_method_entry_clone(const rb_method_entry_t *src_me)
1160{
1161 rb_method_entry_t *me = rb_method_entry_alloc(src_me->called_id, src_me->owner, src_me->defined_class, src_me->def, METHOD_ENTRY_COMPLEMENTED(src_me));
1162
1163 METHOD_ENTRY_FLAGS_COPY(me, src_me);
1164
1165 // Also clone inner ME in case of refinement ME
1166 if (src_me->def &&
1167 src_me->def->type == VM_METHOD_TYPE_REFINED &&
1168 src_me->def->body.refined.orig_me) {
1169 const rb_method_entry_t *orig_me = src_me->def->body.refined.orig_me;
1170 VM_ASSERT(orig_me->def->type != VM_METHOD_TYPE_REFINED);
1171
1172 rb_method_entry_t *orig_clone = rb_method_entry_alloc(orig_me->called_id,
1173 orig_me->owner, orig_me->defined_class, orig_me->def, METHOD_ENTRY_COMPLEMENTED(orig_me));
1174 METHOD_ENTRY_FLAGS_COPY(orig_clone, orig_me);
1175
1176 // Clone definition, since writing a VALUE to a shared definition
1177 // can create reference edges we can't run WBs for.
1178 rb_method_definition_t *clone_def =
1179 rb_method_definition_create(VM_METHOD_TYPE_REFINED, src_me->called_id);
1180 rb_method_definition_set(me, clone_def, orig_clone);
1181 }
1182 return me;
1183}
1184
1186rb_method_entry_complement_defined_class(const rb_method_entry_t *src_me, ID called_id, VALUE defined_class)
1187{
1188 rb_method_definition_t *def = src_me->def;
1190 const rb_method_entry_t *refined_orig_me = NULL;
1191
1192 if (!src_me->defined_class &&
1193 def->type == VM_METHOD_TYPE_REFINED &&
1194 def->body.refined.orig_me) {
1195 const rb_method_entry_t *orig_me =
1196 rb_method_entry_clone(def->body.refined.orig_me);
1197 RB_OBJ_WRITE((VALUE)orig_me, &orig_me->defined_class, defined_class);
1198 refined_orig_me = orig_me;
1199 def = NULL;
1200 }
1201
1202 me = rb_method_entry_alloc(called_id, src_me->owner, defined_class, def, true);
1203 METHOD_ENTRY_FLAGS_COPY(me, src_me);
1204 METHOD_ENTRY_COMPLEMENTED_SET(me);
1205 if (!def) {
1206 def = rb_method_definition_create(VM_METHOD_TYPE_REFINED, called_id);
1207 rb_method_definition_set(me, def, (void *)refined_orig_me);
1208 }
1209
1210 VM_ASSERT_TYPE(me->owner, T_MODULE);
1211
1212 return (rb_callable_method_entry_t *)me;
1213}
1214
1215void
1216rb_method_entry_copy(rb_method_entry_t *dst, const rb_method_entry_t *src)
1217{
1218 method_definition_release(dst->def);
1219 *(rb_method_definition_t **)&dst->def = method_definition_addref(src->def, METHOD_ENTRY_COMPLEMENTED(src));
1220 method_definition_reset(dst);
1221 dst->called_id = src->called_id;
1222 RB_OBJ_WRITE((VALUE)dst, &dst->owner, src->owner);
1223 RB_OBJ_WRITE((VALUE)dst, &dst->defined_class, src->defined_class);
1224 METHOD_ENTRY_FLAGS_COPY(dst, src);
1225}
1226
1227static void
1228make_method_entry_refined(VALUE owner, rb_method_entry_t *me)
1229{
1230 if (me->def->type == VM_METHOD_TYPE_REFINED) {
1231 return;
1232 }
1233 else {
1235
1236 rb_vm_check_redefinition_opt_method(me, me->owner);
1237
1238 struct rb_method_entry_struct *orig_me =
1239 rb_method_entry_alloc(me->called_id,
1240 me->owner,
1241 me->defined_class,
1242 me->def,
1243 true);
1244 METHOD_ENTRY_FLAGS_COPY(orig_me, me);
1245
1246 def = rb_method_definition_create(VM_METHOD_TYPE_REFINED, me->called_id);
1247 rb_method_definition_set(me, def, orig_me);
1248 METHOD_ENTRY_VISI_SET(me, METHOD_VISI_PUBLIC);
1249 }
1250}
1251
1252static inline rb_method_entry_t *
1253lookup_method_table(VALUE klass, ID id)
1254{
1255 st_data_t body;
1256 struct rb_id_table *m_tbl = RCLASS_M_TBL(klass);
1257
1258 if (rb_id_table_lookup(m_tbl, id, &body)) {
1259 return (rb_method_entry_t *) body;
1260 }
1261 else {
1262 return 0;
1263 }
1264}
1265
1266void
1267rb_add_refined_method_entry(VALUE refined_class, ID mid)
1268{
1269 rb_method_entry_t *me = lookup_method_table(refined_class, mid);
1270
1271 if (me) {
1272 make_method_entry_refined(refined_class, me);
1273 rb_clear_method_cache(refined_class, mid);
1274 }
1275 else {
1276 rb_add_method(refined_class, mid, VM_METHOD_TYPE_REFINED, 0, METHOD_VISI_PUBLIC);
1277 }
1278}
1279
1280static void
1281check_override_opt_method_i(VALUE klass, VALUE arg)
1282{
1283 ID mid = (ID)arg;
1284 const rb_method_entry_t *me, *newme;
1285
1286 if (vm_redefinition_check_flag(klass)) {
1287 me = lookup_method_table(RCLASS_ORIGIN(klass), mid);
1288 if (me) {
1289 newme = rb_method_entry(klass, mid);
1290 if (newme != me) rb_vm_check_redefinition_opt_method(me, me->owner);
1291 }
1292 }
1293 rb_class_foreach_subclass(klass, check_override_opt_method_i, (VALUE)mid);
1294}
1295
1296static void
1297check_override_opt_method(VALUE klass, VALUE mid)
1298{
1299 if (rb_vm_check_optimizable_mid(mid)) {
1300 check_override_opt_method_i(klass, mid);
1301 }
1302}
1303
1304static inline rb_method_entry_t* search_method0(VALUE klass, ID id, VALUE *defined_class_ptr, bool skip_refined);
1305/*
1306 * klass->method_table[mid] = method_entry(defined_class, visi, def)
1307 *
1308 * If def is given (!= NULL), then just use it and ignore original_id and otps.
1309 * If not given, then make a new def with original_id and opts.
1310 */
1311static rb_method_entry_t *
1312rb_method_entry_make(VALUE klass, ID mid, VALUE defined_class, rb_method_visibility_t visi,
1313 rb_method_type_t type, rb_method_definition_t *def, ID original_id, void *opts)
1314{
1316 struct rb_id_table *mtbl;
1317 st_data_t data;
1318 int make_refined = 0;
1319 VALUE orig_klass;
1320
1321 if (NIL_P(klass)) {
1322 klass = rb_cObject;
1323 }
1324 orig_klass = klass;
1325
1326 if (!RCLASS_SINGLETON_P(klass) &&
1327 type != VM_METHOD_TYPE_NOTIMPLEMENTED &&
1328 type != VM_METHOD_TYPE_ZSUPER) {
1329 switch (mid) {
1330 case idInitialize:
1331 case idInitialize_copy:
1332 case idInitialize_clone:
1333 case idInitialize_dup:
1334 case idRespond_to_missing:
1335 visi = METHOD_VISI_PRIVATE;
1336 }
1337 }
1338
1339 if (type != VM_METHOD_TYPE_REFINED) {
1340 rb_class_modify_check(klass);
1341 }
1342
1343 if (RB_TYPE_P(klass, T_MODULE) && FL_TEST(klass, RMODULE_IS_REFINEMENT)) {
1344 VALUE refined_class = rb_refinement_module_get_refined_class(klass);
1345 bool search_superclass = type == VM_METHOD_TYPE_ZSUPER && !lookup_method_table(refined_class, mid);
1346 rb_add_refined_method_entry(refined_class, mid);
1347 if (search_superclass) {
1348 rb_method_entry_t *me = lookup_method_table(refined_class, mid);
1349 me->def->body.refined.orig_me = search_method0(refined_class, mid, NULL, true);
1350 }
1351 }
1352 if (type == VM_METHOD_TYPE_REFINED) {
1353 rb_method_entry_t *old_me = lookup_method_table(RCLASS_ORIGIN(klass), mid);
1354 if (old_me) rb_vm_check_redefinition_opt_method(old_me, klass);
1355 }
1356 else {
1357 klass = RCLASS_ORIGIN(klass);
1358 if (klass != orig_klass) {
1359 rb_clear_method_cache(orig_klass, mid);
1360 }
1361 }
1362 mtbl = RCLASS_WRITABLE_M_TBL(klass);
1363
1364 /* check re-definition */
1365 if (rb_id_table_lookup(mtbl, mid, &data)) {
1366 rb_method_entry_t *old_me = (rb_method_entry_t *)data;
1367 rb_method_definition_t *old_def = old_me->def;
1368
1369 if (rb_method_definition_eq(old_def, def)) return old_me;
1370 rb_vm_check_redefinition_opt_method(old_me, klass);
1371
1372 if (old_def->type == VM_METHOD_TYPE_REFINED) make_refined = 1;
1373
1374 if (RTEST(ruby_verbose) &&
1375 type != VM_METHOD_TYPE_UNDEF &&
1376 (old_def->aliased == false) &&
1377 (!old_def->no_redef_warning) &&
1378 !make_refined &&
1379 old_def->type != VM_METHOD_TYPE_UNDEF &&
1380 old_def->type != VM_METHOD_TYPE_ZSUPER &&
1381 old_def->type != VM_METHOD_TYPE_ALIAS) {
1382 const rb_iseq_t *iseq = 0;
1383
1384 switch (old_def->type) {
1385 case VM_METHOD_TYPE_ISEQ:
1386 iseq = def_iseq_ptr(old_def);
1387 break;
1388 case VM_METHOD_TYPE_BMETHOD:
1389 iseq = rb_proc_get_iseq(old_def->body.bmethod.proc, 0);
1390 break;
1391 default:
1392 break;
1393 }
1394 if (iseq) {
1395 rb_warning(
1396 "method redefined; discarding old %"PRIsVALUE"\n%s:%d: warning: previous definition of %"PRIsVALUE" was here",
1397 rb_id2str(mid),
1398 RSTRING_PTR(rb_iseq_path(iseq)),
1399 ISEQ_BODY(iseq)->location.first_lineno,
1400 rb_id2str(old_def->original_id)
1401 );
1402 }
1403 else {
1404 rb_warning("method redefined; discarding old %"PRIsVALUE, rb_id2str(mid));
1405 }
1406 }
1407 }
1408
1409 /* create method entry */
1410 me = rb_method_entry_create(mid, defined_class, visi, NULL);
1411 if (def == NULL) {
1412 def = rb_method_definition_create(type, original_id);
1413 }
1414 rb_method_definition_set(me, def, opts);
1415
1416 rb_clear_method_cache(klass, mid);
1417
1418 /* check mid */
1419 if (klass == rb_cObject) {
1420 switch (mid) {
1421 case idInitialize:
1422 case idRespond_to_missing:
1423 case idMethodMissing:
1424 case idRespond_to:
1425 rb_warn("redefining Object#%s may cause infinite loop", rb_id2name(mid));
1426 }
1427 }
1428 /* check mid */
1429 if (mid == object_id || mid == id__id__ || mid == id__send__) {
1430 if (type != VM_METHOD_TYPE_CFUNC && search_method(klass, mid, 0)) {
1431 rb_warn("redefining '%s' may cause serious problems", rb_id2name(mid));
1432 }
1433 }
1434
1435 if (make_refined) {
1436 make_method_entry_refined(klass, me);
1437 }
1438
1439 rb_method_table_insert(klass, mtbl, mid, me);
1440
1441 VM_ASSERT(me->def != NULL);
1442
1443 /* check optimized method override by a prepended module */
1444 if (RB_TYPE_P(orig_klass, T_MODULE)) {
1445 check_override_opt_method(klass, (VALUE)mid);
1446 }
1447
1448 return me;
1449}
1450
1451static st_table *
1452overloaded_cme_table(void)
1453{
1454 VM_ASSERT(GET_VM()->overloaded_cme_table != NULL);
1455 return GET_VM()->overloaded_cme_table;
1456}
1457
1458#if VM_CHECK_MODE > 0
1459static int
1460vm_dump_overloaded_cme_table(st_data_t key, st_data_t val, st_data_t dmy)
1461{
1462 fprintf(stderr, "key: "); rp(key);
1463 fprintf(stderr, "val: "); rp(val);
1464 return ST_CONTINUE;
1465}
1466
1467void
1468rb_vm_dump_overloaded_cme_table(void)
1469{
1470 fprintf(stderr, "== rb_vm_dump_overloaded_cme_table\n");
1471 st_foreach(overloaded_cme_table(), vm_dump_overloaded_cme_table, 0);
1472}
1473#endif
1474
1475static int
1476lookup_overloaded_cme_i(st_data_t *key, st_data_t *value, st_data_t data, int existing)
1477{
1478 if (existing) {
1479 const rb_callable_method_entry_t *cme = (const rb_callable_method_entry_t *)*key;
1480 const rb_callable_method_entry_t *monly_cme = (const rb_callable_method_entry_t *)*value;
1481 const rb_callable_method_entry_t **ptr = (const rb_callable_method_entry_t **)data;
1482
1483 if (rb_objspace_garbage_object_p((VALUE)cme) ||
1484 rb_objspace_garbage_object_p((VALUE)monly_cme)) {
1485 *ptr = NULL;
1486 return ST_DELETE;
1487 }
1488 else {
1489 *ptr = monly_cme;
1490 }
1491 }
1492
1493 return ST_STOP;
1494}
1495
1496static const rb_callable_method_entry_t *
1497lookup_overloaded_cme(const rb_callable_method_entry_t *cme)
1498{
1499 ASSERT_vm_locking();
1500
1501 const rb_callable_method_entry_t *monly_cme = NULL;
1502 st_update(overloaded_cme_table(), (st_data_t)cme, lookup_overloaded_cme_i, (st_data_t)&monly_cme);
1503 return monly_cme;
1504}
1505
1506#if VM_CHECK_MODE > 0
1508rb_vm_lookup_overloaded_cme(const rb_callable_method_entry_t *cme)
1509{
1510 return lookup_overloaded_cme(cme);
1511}
1512#endif
1513
1514static void
1515delete_overloaded_cme(const rb_callable_method_entry_t *cme)
1516{
1517 st_data_t cme_data = (st_data_t)cme;
1518 ASSERT_vm_locking();
1519 st_delete(overloaded_cme_table(), &cme_data, NULL);
1520}
1521
1522static const rb_callable_method_entry_t *
1523get_overloaded_cme(const rb_callable_method_entry_t *cme)
1524{
1525 const rb_callable_method_entry_t *monly_cme = lookup_overloaded_cme(cme);
1526
1527 if (monly_cme && !METHOD_ENTRY_INVALIDATED(monly_cme)) {
1528 return monly_cme;
1529 }
1530 else {
1531 // create
1532 rb_method_definition_t *def = rb_method_definition_create(VM_METHOD_TYPE_ISEQ, cme->def->original_id);
1533 rb_method_entry_t *me = rb_method_entry_alloc(cme->called_id,
1534 cme->owner,
1535 cme->defined_class,
1536 def,
1537 false);
1538
1539 RB_OBJ_WRITE(me, &def->body.iseq.cref, cme->def->body.iseq.cref);
1540 RB_OBJ_WRITE(me, &def->body.iseq.iseqptr, ISEQ_BODY(cme->def->body.iseq.iseqptr)->mandatory_only_iseq);
1541
1542 ASSERT_vm_locking();
1543 st_insert(overloaded_cme_table(), (st_data_t)cme, (st_data_t)me);
1544
1545 METHOD_ENTRY_VISI_SET(me, METHOD_ENTRY_VISI(cme));
1546 return (rb_callable_method_entry_t *)me;
1547 }
1548}
1549
1551rb_check_overloaded_cme(const rb_callable_method_entry_t *cme, const struct rb_callinfo * const ci)
1552{
1553 if (UNLIKELY(cme->def->iseq_overload) &&
1554 (vm_ci_flag(ci) & (VM_CALL_ARGS_SIMPLE)) &&
1555 (!(vm_ci_flag(ci) & VM_CALL_FORWARDING)) &&
1556 (int)vm_ci_argc(ci) == ISEQ_BODY(method_entry_iseqptr(cme))->param.lead_num) {
1557 VM_ASSERT(cme->def->type == VM_METHOD_TYPE_ISEQ, "type: %d", cme->def->type); // iseq_overload is marked only on ISEQ methods
1558
1559 cme = get_overloaded_cme(cme);
1560
1561 VM_ASSERT(cme != NULL);
1562 METHOD_ENTRY_CACHED_SET((struct rb_callable_method_entry_struct *)cme);
1563 }
1564
1565 return cme;
1566}
1567
1568#define CALL_METHOD_HOOK(klass, hook, mid) do { \
1569 const VALUE arg = ID2SYM(mid); \
1570 VALUE recv_class = (klass); \
1571 ID hook_id = (hook); \
1572 if (RCLASS_SINGLETON_P((klass))) { \
1573 recv_class = RCLASS_ATTACHED_OBJECT((klass)); \
1574 hook_id = singleton_##hook; \
1575 } \
1576 rb_funcallv(recv_class, hook_id, 1, &arg); \
1577 } while (0)
1578
1579static void
1580method_added(VALUE klass, ID mid)
1581{
1582 if (ruby_running) {
1583 CALL_METHOD_HOOK(klass, added, mid);
1584 }
1585}
1586
1587void
1588rb_add_method(VALUE klass, ID mid, rb_method_type_t type, void *opts, rb_method_visibility_t visi)
1589{
1590 RB_VM_LOCKING() {
1591 rb_method_entry_make(klass, mid, klass, visi, type, NULL, mid, opts);
1592 }
1593
1594 if (type != VM_METHOD_TYPE_UNDEF && type != VM_METHOD_TYPE_REFINED) {
1595 method_added(klass, mid);
1596 }
1597}
1598
1599void
1600rb_add_method_iseq(VALUE klass, ID mid, const rb_iseq_t *iseq, rb_cref_t *cref, rb_method_visibility_t visi)
1601{
1602 struct { /* should be same fields with rb_method_iseq_struct */
1603 const rb_iseq_t *iseqptr;
1604 rb_cref_t *cref;
1605 } iseq_body;
1606
1607 iseq_body.iseqptr = iseq;
1608 iseq_body.cref = cref;
1609
1610 rb_add_method(klass, mid, VM_METHOD_TYPE_ISEQ, &iseq_body, visi);
1611}
1612
1613static rb_method_entry_t *
1614method_entry_set(VALUE klass, ID mid, const rb_method_entry_t *me,
1615 rb_method_visibility_t visi, VALUE defined_class)
1616{
1617 rb_method_entry_t *newme;
1618 RB_VM_LOCKING() {
1619 newme = rb_method_entry_make(klass, mid, defined_class, visi,
1620 me->def->type, me->def, 0, NULL);
1621 if (newme == me) {
1622 me->def->no_redef_warning = TRUE;
1623 METHOD_ENTRY_FLAGS_SET(newme, visi, FALSE);
1624 }
1625 }
1626
1627 method_added(klass, mid);
1628 return newme;
1629}
1630
1632rb_method_entry_set(VALUE klass, ID mid, const rb_method_entry_t *me, rb_method_visibility_t visi)
1633{
1634 return method_entry_set(klass, mid, me, visi, klass);
1635}
1636
1637#define UNDEF_ALLOC_FUNC ((rb_alloc_func_t)-1)
1638
1639void
1640rb_define_alloc_func(VALUE klass, VALUE (*func)(VALUE))
1641{
1642 Check_Type(klass, T_CLASS);
1643 if (RCLASS_SINGLETON_P(klass)) {
1644 rb_raise(rb_eTypeError, "can't define an allocator for a singleton class");
1645 }
1646 RCLASS_SET_ALLOCATOR(klass, func);
1647}
1648
1649void
1651{
1652 rb_define_alloc_func(klass, UNDEF_ALLOC_FUNC);
1653}
1654
1657{
1658 RBIMPL_ASSERT_TYPE(klass, T_CLASS);
1659
1660 rb_alloc_func_t allocator = RCLASS_ALLOCATOR(klass);
1661 if (allocator == UNDEF_ALLOC_FUNC) return 0;
1662 if (allocator) return allocator;
1663
1664 VALUE *superclasses = RCLASS_SUPERCLASSES(klass);
1665 size_t depth = RCLASS_SUPERCLASS_DEPTH(klass);
1666
1667 for (size_t i = depth; i > 0; i--) {
1668 klass = superclasses[i - 1];
1669 RBIMPL_ASSERT_TYPE(klass, T_CLASS);
1670
1671 allocator = RCLASS_ALLOCATOR(klass);
1672 if (allocator == UNDEF_ALLOC_FUNC) break;
1673 if (allocator) return allocator;
1674 }
1675 return 0;
1676}
1677
1678const rb_method_entry_t *
1679rb_method_entry_at(VALUE klass, ID id)
1680{
1681 return lookup_method_table(klass, id);
1682}
1683
1684static inline rb_method_entry_t*
1685search_method0(VALUE klass, ID id, VALUE *defined_class_ptr, bool skip_refined)
1686{
1687 rb_method_entry_t *me = NULL;
1688
1689 RB_DEBUG_COUNTER_INC(mc_search);
1690
1691 for (; klass; klass = RCLASS_SUPER(klass)) {
1692 RB_DEBUG_COUNTER_INC(mc_search_super);
1693 if ((me = lookup_method_table(klass, id)) != 0) {
1694 if (!skip_refined || me->def->type != VM_METHOD_TYPE_REFINED ||
1695 me->def->body.refined.orig_me) {
1696 break;
1697 }
1698 }
1699 }
1700
1701 if (defined_class_ptr) *defined_class_ptr = klass;
1702
1703 if (me == NULL) RB_DEBUG_COUNTER_INC(mc_search_notfound);
1704
1705 VM_ASSERT(me == NULL || !METHOD_ENTRY_INVALIDATED(me),
1706 "invalid me, mid:%s, klass:%s(%s)",
1707 rb_id2name(id),
1708 RTEST(rb_mod_name(klass)) ? RSTRING_PTR(rb_mod_name(klass)) : "anonymous",
1709 rb_obj_info(klass));
1710 return me;
1711}
1712
1713static inline rb_method_entry_t*
1714search_method(VALUE klass, ID id, VALUE *defined_class_ptr)
1715{
1716 return search_method0(klass, id, defined_class_ptr, false);
1717}
1718
1719static rb_method_entry_t *
1720search_method_protect(VALUE klass, ID id, VALUE *defined_class_ptr)
1721{
1722 rb_method_entry_t *me = search_method(klass, id, defined_class_ptr);
1723
1724 if (!UNDEFINED_METHOD_ENTRY_P(me)) {
1725 return me;
1726 }
1727 else {
1728 return NULL;
1729 }
1730}
1731
1732const rb_method_entry_t *
1733rb_method_entry(VALUE klass, ID id)
1734{
1735 return search_method_protect(klass, id, NULL);
1736}
1737
1738static inline const rb_callable_method_entry_t *
1739prepare_callable_method_entry(VALUE defined_class, ID id, const rb_method_entry_t * const me, int create)
1740{
1741 struct rb_id_table *mtbl;
1742 const rb_callable_method_entry_t *cme;
1743 VALUE cme_data;
1744 int cme_found = 0;
1745
1746 if (me) {
1747 if (me->defined_class == 0) {
1748 RB_DEBUG_COUNTER_INC(mc_cme_complement);
1749 VM_ASSERT_TYPE2(defined_class, T_ICLASS, T_MODULE);
1750
1751 mtbl = RCLASS_WRITABLE_CALLABLE_M_TBL(defined_class);
1752 if (mtbl && rb_id_table_lookup(mtbl, id, &cme_data)) {
1753 cme = (rb_callable_method_entry_t *)cme_data;
1754 cme_found = 1;
1755 }
1756 if (cme_found) {
1757 RB_DEBUG_COUNTER_INC(mc_cme_complement_hit);
1758 VM_ASSERT(callable_method_entry_p(cme));
1759 VM_ASSERT(!METHOD_ENTRY_INVALIDATED(cme));
1760 }
1761 else if (create) {
1762 if (!mtbl) {
1763 mtbl = rb_id_table_create(0);
1764 RCLASS_WRITE_CALLABLE_M_TBL(defined_class, mtbl);
1765 }
1766 cme = rb_method_entry_complement_defined_class(me, me->called_id, defined_class);
1767 rb_id_table_insert(mtbl, id, (VALUE)cme);
1768 RB_OBJ_WRITTEN(defined_class, Qundef, (VALUE)cme);
1769 VM_ASSERT(callable_method_entry_p(cme));
1770 }
1771 else {
1772 return NULL;
1773 }
1774 }
1775 else {
1776 cme = (const rb_callable_method_entry_t *)me;
1777 VM_ASSERT(callable_method_entry_p(cme));
1778 VM_ASSERT(!METHOD_ENTRY_INVALIDATED(cme));
1779 }
1780 return cme;
1781 }
1782 else {
1783 return NULL;
1784 }
1785}
1786
1787static const rb_callable_method_entry_t *
1788complemented_callable_method_entry(VALUE klass, ID id)
1789{
1790 VALUE defined_class;
1791 rb_method_entry_t *me = search_method(klass, id, &defined_class);
1792 return prepare_callable_method_entry(defined_class, id, me, FALSE);
1793}
1794
1795static const rb_callable_method_entry_t *
1796cached_callable_method_entry(VALUE klass, ID mid)
1797{
1798 ASSERT_vm_locking();
1799
1800 VALUE cc_tbl = RCLASS_WRITABLE_CC_TBL(klass);
1801 VALUE ccs_data;
1802
1803 if (cc_tbl && rb_managed_id_table_lookup(cc_tbl, mid, &ccs_data)) {
1804 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_data;
1805 VM_ASSERT(vm_ccs_p(ccs));
1806
1807 if (LIKELY(!METHOD_ENTRY_INVALIDATED(ccs->cme))) {
1808 VM_ASSERT(ccs->cme->called_id == mid);
1809 RB_DEBUG_COUNTER_INC(ccs_found);
1810 return ccs->cme;
1811 }
1812 else {
1813 rb_vm_barrier();
1814
1815 rb_managed_id_table_delete(cc_tbl, mid);
1816 rb_vm_ccs_invalidate_and_free(ccs);
1817 }
1818 }
1819
1820 RB_DEBUG_COUNTER_INC(ccs_not_found);
1821 return NULL;
1822}
1823
1824static void
1825cache_callable_method_entry(VALUE klass, ID mid, const rb_callable_method_entry_t *cme)
1826{
1827 ASSERT_vm_locking();
1828 VM_ASSERT(cme != NULL);
1829
1830 VALUE cc_tbl = RCLASS_WRITABLE_CC_TBL(klass);
1831 VALUE ccs_data;
1832
1833 if (!cc_tbl) {
1834 cc_tbl = rb_vm_cc_table_create(2);
1835 RCLASS_WRITE_CC_TBL(klass, cc_tbl);
1836 }
1837
1838 if (rb_managed_id_table_lookup(cc_tbl, mid, &ccs_data)) {
1839#if VM_CHECK_MODE > 0
1840 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_data;
1841 VM_ASSERT(ccs->cme == cme);
1842#endif
1843 }
1844 else {
1845 if (rb_multi_ractor_p()) {
1846 VALUE new_cc_tbl = rb_vm_cc_table_dup(cc_tbl);
1847 vm_ccs_create(klass, new_cc_tbl, mid, cme);
1848 RB_OBJ_ATOMIC_WRITE(klass, &RCLASSEXT_CC_TBL(RCLASS_EXT_WRITABLE(klass)), new_cc_tbl);
1849 }
1850 else {
1851 vm_ccs_create(klass, cc_tbl, mid, cme);
1852 }
1853 }
1854}
1855
1856static const rb_callable_method_entry_t *
1857negative_cme(ID mid)
1858{
1859 rb_vm_t *vm = GET_VM();
1860 const rb_callable_method_entry_t *cme;
1861 VALUE cme_data;
1862
1863 if (rb_id_table_lookup(vm->negative_cme_table, mid, &cme_data)) {
1864 cme = (rb_callable_method_entry_t *)cme_data;
1865 }
1866 else {
1867 cme = (rb_callable_method_entry_t *)rb_method_entry_alloc(mid, Qnil, Qnil, NULL, false);
1868 rb_id_table_insert(vm->negative_cme_table, mid, (VALUE)cme);
1869 }
1870
1871 VM_ASSERT(cme != NULL);
1872 return cme;
1873}
1874
1875static const rb_callable_method_entry_t *
1876callable_method_entry_or_negative(VALUE klass, ID mid, VALUE *defined_class_ptr)
1877{
1878 const rb_callable_method_entry_t *cme;
1879
1880 VM_ASSERT_TYPE2(klass, T_CLASS, T_ICLASS);
1881
1882 /* Fast path: lock-free read from cache */
1883 VALUE cc_tbl = RUBY_ATOMIC_VALUE_LOAD(RCLASS_WRITABLE_CC_TBL(klass));
1884 if (cc_tbl) {
1885 VALUE ccs_data;
1886 if (rb_managed_id_table_lookup(cc_tbl, mid, &ccs_data)) {
1887 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_data;
1888 VM_ASSERT(vm_ccs_p(ccs));
1889
1890 if (LIKELY(!METHOD_ENTRY_INVALIDATED(ccs->cme))) {
1891 VM_ASSERT(ccs->cme->called_id == mid);
1892 if (defined_class_ptr != NULL) *defined_class_ptr = ccs->cme->defined_class;
1893 RB_DEBUG_COUNTER_INC(ccs_found);
1894 return ccs->cme;
1895 }
1896 }
1897 }
1898
1899 /* Slow path: need to lock and potentially populate cache */
1900 RB_VM_LOCKING() {
1901 cme = cached_callable_method_entry(klass, mid);
1902
1903 if (cme) {
1904 if (defined_class_ptr != NULL) *defined_class_ptr = cme->defined_class;
1905 }
1906 else {
1907 VALUE defined_class;
1908 rb_method_entry_t *me = search_method(klass, mid, &defined_class);
1909 if (defined_class_ptr) *defined_class_ptr = defined_class;
1910
1911 if (me != NULL) {
1912 cme = prepare_callable_method_entry(defined_class, mid, me, TRUE);
1913 }
1914 else {
1915 cme = negative_cme(mid);
1916 }
1917
1918 cache_callable_method_entry(klass, mid, cme);
1919 }
1920 }
1921
1922 return cme;
1923}
1924
1925// This is exposed for YJIT so that we can make assumptions that methods are
1926// not defined.
1928rb_callable_method_entry_or_negative(VALUE klass, ID mid)
1929{
1930 return callable_method_entry_or_negative(klass, mid, NULL);
1931}
1932
1933static const rb_callable_method_entry_t *
1934callable_method_entry(VALUE klass, ID mid, VALUE *defined_class_ptr)
1935{
1936 const rb_callable_method_entry_t *cme;
1937 cme = callable_method_entry_or_negative(klass, mid, defined_class_ptr);
1938 return !UNDEFINED_METHOD_ENTRY_P(cme) ? cme : NULL;
1939}
1940
1942rb_callable_method_entry(VALUE klass, ID mid)
1943{
1944 return callable_method_entry(klass, mid, NULL);
1945}
1946
1947static const rb_method_entry_t *resolve_refined_method(VALUE refinements, const rb_method_entry_t *me, VALUE *defined_class_ptr);
1948
1949static const rb_method_entry_t *
1950method_entry_resolve_refinement(VALUE klass, ID id, int with_refinement, VALUE *defined_class_ptr)
1951{
1952 const rb_method_entry_t *me = search_method_protect(klass, id, defined_class_ptr);
1953
1954 if (me) {
1955 if (me->def->type == VM_METHOD_TYPE_REFINED) {
1956 if (with_refinement) {
1957 const rb_cref_t *cref = rb_vm_cref();
1958 VALUE refinements = cref ? CREF_REFINEMENTS(cref) : Qnil;
1959 me = resolve_refined_method(refinements, me, defined_class_ptr);
1960 }
1961 else {
1962 me = resolve_refined_method(Qnil, me, defined_class_ptr);
1963 }
1964
1965 if (UNDEFINED_METHOD_ENTRY_P(me)) me = NULL;
1966 }
1967 }
1968
1969 return me;
1970}
1971
1972const rb_method_entry_t *
1973rb_method_entry_with_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
1974{
1975 return method_entry_resolve_refinement(klass, id, TRUE, defined_class_ptr);
1976}
1977
1978static const rb_callable_method_entry_t *
1979callable_method_entry_refinements0(VALUE klass, ID id, VALUE *defined_class_ptr, bool with_refinements,
1980 const rb_callable_method_entry_t *cme)
1981{
1982 if (cme == NULL || LIKELY(cme->def->type != VM_METHOD_TYPE_REFINED)) {
1983 return cme;
1984 }
1985 else {
1986 VALUE defined_class, *dcp = defined_class_ptr ? defined_class_ptr : &defined_class;
1987 const rb_method_entry_t *me = method_entry_resolve_refinement(klass, id, with_refinements, dcp);
1988 return prepare_callable_method_entry(*dcp, id, me, TRUE);
1989 }
1990}
1991
1992static const rb_callable_method_entry_t *
1993callable_method_entry_refinements(VALUE klass, ID id, VALUE *defined_class_ptr, bool with_refinements)
1994{
1995 const rb_callable_method_entry_t *cme = callable_method_entry(klass, id, defined_class_ptr);
1996 return callable_method_entry_refinements0(klass, id, defined_class_ptr, with_refinements, cme);
1997}
1998
2000rb_callable_method_entry_with_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
2001{
2002 return callable_method_entry_refinements(klass, id, defined_class_ptr, true);
2003}
2004
2005static const rb_callable_method_entry_t *
2006callable_method_entry_without_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
2007{
2008 return callable_method_entry_refinements(klass, id, defined_class_ptr, false);
2009}
2010
2011const rb_method_entry_t *
2012rb_method_entry_without_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
2013{
2014 return method_entry_resolve_refinement(klass, id, FALSE, defined_class_ptr);
2015}
2016
2018rb_callable_method_entry_without_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
2019{
2020 VALUE defined_class, *dcp = defined_class_ptr ? defined_class_ptr : &defined_class;
2021 const rb_method_entry_t *me = method_entry_resolve_refinement(klass, id, FALSE, dcp);
2022 return prepare_callable_method_entry(*dcp, id, me, TRUE);
2023}
2024
2025static const rb_method_entry_t *
2026resolve_refined_method(VALUE refinements, const rb_method_entry_t *me, VALUE *defined_class_ptr)
2027{
2028 while (me && me->def->type == VM_METHOD_TYPE_REFINED) {
2029 VALUE refinement;
2030 const rb_method_entry_t *tmp_me;
2031 VALUE super;
2032
2033 refinement = find_refinement(refinements, me->owner);
2034 if (!NIL_P(refinement)) {
2035 tmp_me = search_method_protect(refinement, me->called_id, defined_class_ptr);
2036
2037 if (tmp_me && tmp_me->def->type != VM_METHOD_TYPE_REFINED) {
2038 return tmp_me;
2039 }
2040 }
2041
2042 tmp_me = me->def->body.refined.orig_me;
2043 if (tmp_me) {
2044 if (!tmp_me->defined_class) {
2045 VM_ASSERT_TYPE(tmp_me->owner, T_MODULE);
2046 }
2047 else if (defined_class_ptr) {
2048 *defined_class_ptr = tmp_me->defined_class;
2049 }
2050 return tmp_me;
2051 }
2052
2053 super = RCLASS_SUPER(me->owner);
2054 if (!super) {
2055 return 0;
2056 }
2057
2058 me = search_method_protect(super, me->called_id, defined_class_ptr);
2059 }
2060 return me;
2061}
2062
2063const rb_method_entry_t *
2064rb_resolve_refined_method(VALUE refinements, const rb_method_entry_t *me)
2065{
2066 return resolve_refined_method(refinements, me, NULL);
2067}
2068
2070rb_resolve_refined_method_callable(VALUE refinements, const rb_callable_method_entry_t *me)
2071{
2072 VALUE defined_class = me->defined_class;
2073 const rb_method_entry_t *resolved_me = resolve_refined_method(refinements, (const rb_method_entry_t *)me, &defined_class);
2074
2075 if (resolved_me && resolved_me->defined_class == 0) {
2076 return rb_method_entry_complement_defined_class(resolved_me, me->called_id, defined_class);
2077 }
2078 else {
2079 return (const rb_callable_method_entry_t *)resolved_me;
2080 }
2081}
2082
2083static void
2084remove_method(VALUE klass, ID mid)
2085{
2086 VALUE data;
2087 rb_method_entry_t *me = 0;
2088 VALUE self = klass;
2089
2090 rb_class_modify_check(klass);
2091 klass = RCLASS_ORIGIN(klass);
2092 if (mid == object_id || mid == id__id__ || mid == id__send__ || mid == idInitialize) {
2093 rb_warn("removing '%s' may cause serious problems", rb_id2name(mid));
2094 }
2095
2096 if (!rb_id_table_lookup(RCLASS_M_TBL(klass), mid, &data) ||
2097 !(me = (rb_method_entry_t *)data) ||
2098 (!me->def || me->def->type == VM_METHOD_TYPE_UNDEF) ||
2099 UNDEFINED_REFINED_METHOD_P(me->def)) {
2100 rb_name_err_raise("method '%1$s' not defined in %2$s",
2101 klass, ID2SYM(mid));
2102 }
2103
2104 if (klass != self) {
2105 rb_clear_method_cache(self, mid);
2106 }
2107 rb_clear_method_cache(klass, mid);
2108 rb_id_table_delete(RCLASS_WRITABLE_M_TBL(klass), mid);
2109
2110 rb_vm_check_redefinition_opt_method(me, klass);
2111
2112 if (me->def->type == VM_METHOD_TYPE_REFINED) {
2113 rb_add_refined_method_entry(klass, mid);
2114 }
2115
2116 CALL_METHOD_HOOK(self, removed, mid);
2117}
2118
2119void
2121{
2122 remove_method(klass, mid);
2123}
2124
2125void
2126rb_remove_method(VALUE klass, const char *name)
2127{
2128 remove_method(klass, rb_intern(name));
2129}
2130
2131/*
2132 * call-seq:
2133 * remove_method(symbol) -> self
2134 * remove_method(string) -> self
2135 *
2136 * Removes the method identified by _symbol_ from the current
2137 * class. For an example, see Module#undef_method.
2138 * String arguments are converted to symbols.
2139 */
2140
2141static VALUE
2142rb_mod_remove_method(int argc, VALUE *argv, VALUE mod)
2143{
2144 int i;
2145
2146 for (i = 0; i < argc; i++) {
2147 VALUE v = argv[i];
2148 ID id = rb_check_id(&v);
2149 if (!id) {
2150 rb_name_err_raise("method '%1$s' not defined in %2$s",
2151 mod, v);
2152 }
2153 remove_method(mod, id);
2154 }
2155 return mod;
2156}
2157
2158static void
2159rb_export_method(VALUE klass, ID name, rb_method_visibility_t visi)
2160{
2162 VALUE defined_class;
2163 VALUE origin_class = RCLASS_ORIGIN(klass);
2164
2165 me = search_method0(origin_class, name, &defined_class, true);
2166
2167 if (!me && RB_TYPE_P(klass, T_MODULE)) {
2168 me = search_method(rb_cObject, name, &defined_class);
2169 }
2170
2171 if (UNDEFINED_METHOD_ENTRY_P(me) ||
2172 UNDEFINED_REFINED_METHOD_P(me->def)) {
2173 rb_print_undef(klass, name, METHOD_VISI_UNDEF);
2174 }
2175
2176 if (METHOD_ENTRY_VISI(me) != visi) {
2177 rb_vm_check_redefinition_opt_method(me, klass);
2178
2179 if (klass == defined_class || origin_class == defined_class) {
2180 if (me->def->type == VM_METHOD_TYPE_REFINED) {
2181 // Refinement method entries should always be public because the refinement
2182 // search is always performed.
2183 if (me->def->body.refined.orig_me) {
2184 METHOD_ENTRY_VISI_SET((rb_method_entry_t *)me->def->body.refined.orig_me, visi);
2185 }
2186 }
2187 else {
2188 METHOD_ENTRY_VISI_SET(me, visi);
2189 }
2190 rb_clear_method_cache(klass, name);
2191 }
2192 else {
2193 rb_add_method(klass, name, VM_METHOD_TYPE_ZSUPER, 0, visi);
2194 }
2195 }
2196}
2197
2198#define BOUND_PRIVATE 0x01
2199#define BOUND_RESPONDS 0x02
2200
2201static int
2202method_boundp(VALUE klass, ID id, int ex)
2203{
2204 const rb_callable_method_entry_t *cme;
2205
2206 VM_ASSERT_TYPE2(klass, T_CLASS, T_ICLASS);
2207
2208 if (ex & BOUND_RESPONDS) {
2209 cme = rb_callable_method_entry_with_refinements(klass, id, NULL);
2210 }
2211 else {
2212 cme = callable_method_entry_without_refinements(klass, id, NULL);
2213 }
2214
2215 if (cme != NULL) {
2216 if (ex & ~BOUND_RESPONDS) {
2217 switch (METHOD_ENTRY_VISI(cme)) {
2218 case METHOD_VISI_PRIVATE:
2219 return 0;
2220 case METHOD_VISI_PROTECTED:
2221 if (ex & BOUND_RESPONDS) return 0;
2222 default:
2223 break;
2224 }
2225 }
2226
2227 if (cme->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) {
2228 if (ex & BOUND_RESPONDS) return 2;
2229 return 0;
2230 }
2231 return 1;
2232 }
2233 return 0;
2234}
2235
2236// deprecated
2237int
2238rb_method_boundp(VALUE klass, ID id, int ex)
2239{
2240 return method_boundp(klass, id, ex);
2241}
2242
2243static void
2244vm_cref_set_visibility(rb_method_visibility_t method_visi, int module_func)
2245{
2246 rb_scope_visibility_t *scope_visi = (rb_scope_visibility_t *)&rb_vm_cref()->scope_visi;
2247 scope_visi->method_visi = method_visi;
2248 scope_visi->module_func = module_func;
2249}
2250
2251void
2252rb_scope_visibility_set(rb_method_visibility_t visi)
2253{
2254 vm_cref_set_visibility(visi, FALSE);
2255}
2256
2257static void
2258scope_visibility_check(void)
2259{
2260 /* Check for public/protected/private/module_function called inside a method */
2261 rb_control_frame_t *cfp = GET_EC()->cfp+1;
2262 if (cfp && cfp->iseq && ISEQ_BODY(cfp->iseq)->type == ISEQ_TYPE_METHOD) {
2263 rb_warn("calling %s without arguments inside a method may not have the intended effect",
2264 rb_id2name(rb_frame_this_func()));
2265 }
2266}
2267
2268static void
2269rb_scope_module_func_set(void)
2270{
2271 scope_visibility_check();
2272 vm_cref_set_visibility(METHOD_VISI_PRIVATE, TRUE);
2273}
2274
2275const rb_cref_t *rb_vm_cref_in_context(VALUE self, VALUE cbase);
2276void
2277rb_attr(VALUE klass, ID id, int read, int write, int ex)
2278{
2279 ID attriv;
2280 rb_method_visibility_t visi;
2281 const rb_execution_context_t *ec = GET_EC();
2282 const rb_cref_t *cref = rb_vm_cref_in_context(klass, klass);
2283
2284 if (!ex || !cref) {
2285 visi = METHOD_VISI_PUBLIC;
2286 }
2287 else {
2288 switch (vm_scope_visibility_get(ec)) {
2289 case METHOD_VISI_PRIVATE:
2290 if (vm_scope_module_func_check(ec)) {
2291 rb_warning("attribute accessor as module_function");
2292 }
2293 visi = METHOD_VISI_PRIVATE;
2294 break;
2295 case METHOD_VISI_PROTECTED:
2296 visi = METHOD_VISI_PROTECTED;
2297 break;
2298 default:
2299 visi = METHOD_VISI_PUBLIC;
2300 break;
2301 }
2302 }
2303
2304 attriv = rb_intern_str(rb_sprintf("@%"PRIsVALUE, rb_id2str(id)));
2305 if (read) {
2306 rb_add_method(klass, id, VM_METHOD_TYPE_IVAR, (void *)attriv, visi);
2307 }
2308 if (write) {
2309 rb_add_method(klass, rb_id_attrset(id), VM_METHOD_TYPE_ATTRSET, (void *)attriv, visi);
2310 }
2311}
2312
2313void
2315{
2316 const rb_method_entry_t *me;
2317
2318 if (NIL_P(klass)) {
2319 rb_raise(rb_eTypeError, "no class to undef method");
2320 }
2321 rb_class_modify_check(klass);
2322 if (id == object_id || id == id__id__ || id == id__send__ || id == idInitialize) {
2323 rb_warn("undefining '%s' may cause serious problems", rb_id2name(id));
2324 }
2325
2326 me = search_method(klass, id, 0);
2327 if (me && me->def->type == VM_METHOD_TYPE_REFINED) {
2328 me = rb_resolve_refined_method(Qnil, me);
2329 }
2330
2331 if (UNDEFINED_METHOD_ENTRY_P(me) ||
2332 UNDEFINED_REFINED_METHOD_P(me->def)) {
2333 rb_method_name_error(klass, rb_id2str(id));
2334 }
2335
2336 rb_add_method(klass, id, VM_METHOD_TYPE_UNDEF, 0, METHOD_VISI_PUBLIC);
2337
2338 CALL_METHOD_HOOK(klass, undefined, id);
2339}
2340
2341/*
2342 * call-seq:
2343 * undef_method(symbol) -> self
2344 * undef_method(string) -> self
2345 *
2346 * Prevents the current class from responding to calls to the named
2347 * method. Contrast this with <code>remove_method</code>, which deletes
2348 * the method from the particular class; Ruby will still search
2349 * superclasses and mixed-in modules for a possible receiver.
2350 * String arguments are converted to symbols.
2351 *
2352 * class Parent
2353 * def hello
2354 * puts "In parent"
2355 * end
2356 * end
2357 * class Child < Parent
2358 * def hello
2359 * puts "In child"
2360 * end
2361 * end
2362 *
2363 *
2364 * c = Child.new
2365 * c.hello
2366 *
2367 *
2368 * class Child
2369 * remove_method :hello # remove from child, still in parent
2370 * end
2371 * c.hello
2372 *
2373 *
2374 * class Child
2375 * undef_method :hello # prevent any calls to 'hello'
2376 * end
2377 * c.hello
2378 *
2379 * <em>produces:</em>
2380 *
2381 * In child
2382 * In parent
2383 * prog.rb:23: undefined method 'hello' for #<Child:0x401b3bb4> (NoMethodError)
2384 */
2385
2386static VALUE
2387rb_mod_undef_method(int argc, VALUE *argv, VALUE mod)
2388{
2389 int i;
2390 for (i = 0; i < argc; i++) {
2391 VALUE v = argv[i];
2392 ID id = rb_check_id(&v);
2393 if (!id) {
2394 rb_method_name_error(mod, v);
2395 }
2396 rb_undef(mod, id);
2397 }
2398 return mod;
2399}
2400
2401static rb_method_visibility_t
2402check_definition_visibility(VALUE mod, int argc, VALUE *argv)
2403{
2404 const rb_method_entry_t *me;
2405 VALUE mid, include_super, lookup_mod = mod;
2406 int inc_super;
2407 ID id;
2408
2409 rb_scan_args(argc, argv, "11", &mid, &include_super);
2410 id = rb_check_id(&mid);
2411 if (!id) return METHOD_VISI_UNDEF;
2412
2413 if (argc == 1) {
2414 inc_super = 1;
2415 }
2416 else {
2417 inc_super = RTEST(include_super);
2418 if (!inc_super) {
2419 lookup_mod = RCLASS_ORIGIN(mod);
2420 }
2421 }
2422
2423 me = rb_method_entry_without_refinements(lookup_mod, id, NULL);
2424 if (me) {
2425 if (me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) return METHOD_VISI_UNDEF;
2426 if (!inc_super && me->owner != mod) return METHOD_VISI_UNDEF;
2427 return METHOD_ENTRY_VISI(me);
2428 }
2429 return METHOD_VISI_UNDEF;
2430}
2431
2432/*
2433 * call-seq:
2434 * mod.method_defined?(symbol, inherit=true) -> true or false
2435 * mod.method_defined?(string, inherit=true) -> true or false
2436 *
2437 * Returns +true+ if the named method is defined by
2438 * _mod_. If _inherit_ is set, the lookup will also search _mod_'s
2439 * ancestors. Public and protected methods are matched.
2440 * String arguments are converted to symbols.
2441 *
2442 * module A
2443 * def method1() end
2444 * def protected_method1() end
2445 * protected :protected_method1
2446 * end
2447 * class B
2448 * def method2() end
2449 * def private_method2() end
2450 * private :private_method2
2451 * end
2452 * class C < B
2453 * include A
2454 * def method3() end
2455 * end
2456 *
2457 * A.method_defined? :method1 #=> true
2458 * C.method_defined? "method1" #=> true
2459 * C.method_defined? "method2" #=> true
2460 * C.method_defined? "method2", true #=> true
2461 * C.method_defined? "method2", false #=> false
2462 * C.method_defined? "method3" #=> true
2463 * C.method_defined? "protected_method1" #=> true
2464 * C.method_defined? "method4" #=> false
2465 * C.method_defined? "private_method2" #=> false
2466 */
2467
2468static VALUE
2469rb_mod_method_defined(int argc, VALUE *argv, VALUE mod)
2470{
2471 rb_method_visibility_t visi = check_definition_visibility(mod, argc, argv);
2472 return RBOOL(visi == METHOD_VISI_PUBLIC || visi == METHOD_VISI_PROTECTED);
2473}
2474
2475static VALUE
2476check_definition(VALUE mod, int argc, VALUE *argv, rb_method_visibility_t visi)
2477{
2478 return RBOOL(check_definition_visibility(mod, argc, argv) == visi);
2479}
2480
2481/*
2482 * call-seq:
2483 * mod.public_method_defined?(symbol, inherit=true) -> true or false
2484 * mod.public_method_defined?(string, inherit=true) -> true or false
2485 *
2486 * Returns +true+ if the named public method is defined by
2487 * _mod_. If _inherit_ is set, the lookup will also search _mod_'s
2488 * ancestors.
2489 * String arguments are converted to symbols.
2490 *
2491 * module A
2492 * def method1() end
2493 * end
2494 * class B
2495 * protected
2496 * def method2() end
2497 * end
2498 * class C < B
2499 * include A
2500 * def method3() end
2501 * end
2502 *
2503 * A.method_defined? :method1 #=> true
2504 * C.public_method_defined? "method1" #=> true
2505 * C.public_method_defined? "method1", true #=> true
2506 * C.public_method_defined? "method1", false #=> true
2507 * C.public_method_defined? "method2" #=> false
2508 * C.method_defined? "method2" #=> true
2509 */
2510
2511static VALUE
2512rb_mod_public_method_defined(int argc, VALUE *argv, VALUE mod)
2513{
2514 return check_definition(mod, argc, argv, METHOD_VISI_PUBLIC);
2515}
2516
2517/*
2518 * call-seq:
2519 * mod.private_method_defined?(symbol, inherit=true) -> true or false
2520 * mod.private_method_defined?(string, inherit=true) -> true or false
2521 *
2522 * Returns +true+ if the named private method is defined by
2523 * _mod_. If _inherit_ is set, the lookup will also search _mod_'s
2524 * ancestors.
2525 * String arguments are converted to symbols.
2526 *
2527 * module A
2528 * def method1() end
2529 * end
2530 * class B
2531 * private
2532 * def method2() end
2533 * end
2534 * class C < B
2535 * include A
2536 * def method3() end
2537 * end
2538 *
2539 * A.method_defined? :method1 #=> true
2540 * C.private_method_defined? "method1" #=> false
2541 * C.private_method_defined? "method2" #=> true
2542 * C.private_method_defined? "method2", true #=> true
2543 * C.private_method_defined? "method2", false #=> false
2544 * C.method_defined? "method2" #=> false
2545 */
2546
2547static VALUE
2548rb_mod_private_method_defined(int argc, VALUE *argv, VALUE mod)
2549{
2550 return check_definition(mod, argc, argv, METHOD_VISI_PRIVATE);
2551}
2552
2553/*
2554 * call-seq:
2555 * mod.protected_method_defined?(symbol, inherit=true) -> true or false
2556 * mod.protected_method_defined?(string, inherit=true) -> true or false
2557 *
2558 * Returns +true+ if the named protected method is defined
2559 * _mod_. If _inherit_ is set, the lookup will also search _mod_'s
2560 * ancestors.
2561 * String arguments are converted to symbols.
2562 *
2563 * module A
2564 * def method1() end
2565 * end
2566 * class B
2567 * protected
2568 * def method2() end
2569 * end
2570 * class C < B
2571 * include A
2572 * def method3() end
2573 * end
2574 *
2575 * A.method_defined? :method1 #=> true
2576 * C.protected_method_defined? "method1" #=> false
2577 * C.protected_method_defined? "method2" #=> true
2578 * C.protected_method_defined? "method2", true #=> true
2579 * C.protected_method_defined? "method2", false #=> false
2580 * C.method_defined? "method2" #=> true
2581 */
2582
2583static VALUE
2584rb_mod_protected_method_defined(int argc, VALUE *argv, VALUE mod)
2585{
2586 return check_definition(mod, argc, argv, METHOD_VISI_PROTECTED);
2587}
2588
2589int
2590rb_method_entry_eq(const rb_method_entry_t *m1, const rb_method_entry_t *m2)
2591{
2592 return rb_method_definition_eq(m1->def, m2->def);
2593}
2594
2595static const rb_method_definition_t *
2596original_method_definition(const rb_method_definition_t *def)
2597{
2598 again:
2599 if (def) {
2600 switch (def->type) {
2601 case VM_METHOD_TYPE_REFINED:
2602 if (def->body.refined.orig_me) {
2603 def = def->body.refined.orig_me->def;
2604 goto again;
2605 }
2606 break;
2607 case VM_METHOD_TYPE_ALIAS:
2608 def = def->body.alias.original_me->def;
2609 goto again;
2610 default:
2611 break;
2612 }
2613 }
2614 return def;
2615}
2616
2617int
2618rb_method_definition_eq(const rb_method_definition_t *d1, const rb_method_definition_t *d2)
2619{
2620 d1 = original_method_definition(d1);
2621 d2 = original_method_definition(d2);
2622
2623 if (d1 == d2) return 1;
2624 if (!d1 || !d2) return 0;
2625 if (d1->type != d2->type) return 0;
2626
2627 switch (d1->type) {
2628 case VM_METHOD_TYPE_ISEQ:
2629 return d1->body.iseq.iseqptr == d2->body.iseq.iseqptr;
2630 case VM_METHOD_TYPE_CFUNC:
2631 return
2632 d1->body.cfunc.func == d2->body.cfunc.func &&
2633 d1->body.cfunc.argc == d2->body.cfunc.argc;
2634 case VM_METHOD_TYPE_ATTRSET:
2635 case VM_METHOD_TYPE_IVAR:
2636 return d1->body.attr.id == d2->body.attr.id;
2637 case VM_METHOD_TYPE_BMETHOD:
2638 return RTEST(rb_equal(d1->body.bmethod.proc, d2->body.bmethod.proc));
2639 case VM_METHOD_TYPE_MISSING:
2640 return d1->original_id == d2->original_id;
2641 case VM_METHOD_TYPE_ZSUPER:
2642 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2643 case VM_METHOD_TYPE_UNDEF:
2644 return 1;
2645 case VM_METHOD_TYPE_OPTIMIZED:
2646 return (d1->body.optimized.type == d2->body.optimized.type) &&
2647 (d1->body.optimized.index == d2->body.optimized.index);
2648 case VM_METHOD_TYPE_REFINED:
2649 case VM_METHOD_TYPE_ALIAS:
2650 break;
2651 }
2652 rb_bug("rb_method_definition_eq: unsupported type: %d", d1->type);
2653}
2654
2655static st_index_t
2656rb_hash_method_definition(st_index_t hash, const rb_method_definition_t *def)
2657{
2658 hash = rb_hash_uint(hash, def->type);
2659 def = original_method_definition(def);
2660
2661 if (!def) return hash;
2662
2663 switch (def->type) {
2664 case VM_METHOD_TYPE_ISEQ:
2665 return rb_hash_uint(hash, (st_index_t)def->body.iseq.iseqptr->body);
2666 case VM_METHOD_TYPE_CFUNC:
2667 hash = rb_hash_uint(hash, (st_index_t)def->body.cfunc.func);
2668 return rb_hash_uint(hash, def->body.cfunc.argc);
2669 case VM_METHOD_TYPE_ATTRSET:
2670 case VM_METHOD_TYPE_IVAR:
2671 return rb_hash_uint(hash, def->body.attr.id);
2672 case VM_METHOD_TYPE_BMETHOD:
2673 return rb_hash_proc(hash, def->body.bmethod.proc);
2674 case VM_METHOD_TYPE_MISSING:
2675 return rb_hash_uint(hash, def->original_id);
2676 case VM_METHOD_TYPE_ZSUPER:
2677 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2678 case VM_METHOD_TYPE_UNDEF:
2679 return hash;
2680 case VM_METHOD_TYPE_OPTIMIZED:
2681 hash = rb_hash_uint(hash, def->body.optimized.index);
2682 return rb_hash_uint(hash, def->body.optimized.type);
2683 case VM_METHOD_TYPE_REFINED:
2684 case VM_METHOD_TYPE_ALIAS:
2685 break; /* unreachable */
2686 }
2687 rb_bug("rb_hash_method_definition: unsupported method type (%d)", def->type);
2688}
2689
2690st_index_t
2691rb_hash_method_entry(st_index_t hash, const rb_method_entry_t *me)
2692{
2693 return rb_hash_method_definition(hash, me->def);
2694}
2695
2696void
2697rb_alias(VALUE klass, ID alias_name, ID original_name)
2698{
2699 const VALUE target_klass = klass;
2700 VALUE defined_class;
2701 const rb_method_entry_t *orig_me;
2702 rb_method_visibility_t visi = METHOD_VISI_UNDEF;
2703
2704 if (NIL_P(klass)) {
2705 rb_raise(rb_eTypeError, "no class to make alias");
2706 }
2707
2708 rb_class_modify_check(klass);
2709
2710 again:
2711 orig_me = search_method(klass, original_name, &defined_class);
2712
2713 if (orig_me && orig_me->def->type == VM_METHOD_TYPE_REFINED) {
2714 orig_me = rb_resolve_refined_method(Qnil, orig_me);
2715 }
2716
2717 if (UNDEFINED_METHOD_ENTRY_P(orig_me) ||
2718 UNDEFINED_REFINED_METHOD_P(orig_me->def)) {
2719 if ((!RB_TYPE_P(klass, T_MODULE)) ||
2720 (orig_me = search_method(rb_cObject, original_name, &defined_class),
2721 UNDEFINED_METHOD_ENTRY_P(orig_me))) {
2722 rb_print_undef(target_klass, original_name, METHOD_VISI_UNDEF);
2723 }
2724 }
2725
2726 switch (orig_me->def->type) {
2727 case VM_METHOD_TYPE_ZSUPER:
2728 klass = RCLASS_SUPER(klass);
2729 original_name = orig_me->def->original_id;
2730 visi = METHOD_ENTRY_VISI(orig_me);
2731 goto again;
2732 case VM_METHOD_TYPE_ALIAS:
2733 visi = METHOD_ENTRY_VISI(orig_me);
2734 orig_me = orig_me->def->body.alias.original_me;
2735 VM_ASSERT(orig_me->def->type != VM_METHOD_TYPE_ALIAS);
2736 break;
2737 default: break;
2738 }
2739
2740 if (visi == METHOD_VISI_UNDEF) visi = METHOD_ENTRY_VISI(orig_me);
2741
2742 if (orig_me->defined_class == 0) {
2743 rb_method_entry_make(target_klass, alias_name, target_klass, visi,
2744 VM_METHOD_TYPE_ALIAS, NULL, orig_me->called_id,
2745 (void *)rb_method_entry_clone(orig_me));
2746 method_added(target_klass, alias_name);
2747 }
2748 else {
2749 rb_method_entry_t *alias_me;
2750
2751 alias_me = method_entry_set(target_klass, alias_name, orig_me, visi, orig_me->owner);
2752 RB_OBJ_WRITE(alias_me, &alias_me->owner, target_klass);
2753
2754 if (RB_TYPE_P(target_klass, T_MODULE)) {
2755 // defined_class should not be set
2756 }
2757 else {
2758 RB_OBJ_WRITE(alias_me, &alias_me->defined_class, orig_me->defined_class);
2759 }
2760 }
2761}
2762
2763/*
2764 * call-seq:
2765 * alias_method(new_name, old_name) -> symbol
2766 *
2767 * Makes <i>new_name</i> a new copy of the method <i>old_name</i>. This can
2768 * be used to retain access to methods that are overridden.
2769 *
2770 * module Mod
2771 * alias_method :orig_exit, :exit #=> :orig_exit
2772 * def exit(code=0)
2773 * puts "Exiting with code #{code}"
2774 * orig_exit(code)
2775 * end
2776 * end
2777 * include Mod
2778 * exit(99)
2779 *
2780 * <em>produces:</em>
2781 *
2782 * Exiting with code 99
2783 */
2784
2785static VALUE
2786rb_mod_alias_method(VALUE mod, VALUE newname, VALUE oldname)
2787{
2788 ID oldid = rb_check_id(&oldname);
2789 if (!oldid) {
2790 rb_print_undef_str(mod, oldname);
2791 }
2792 VALUE id = rb_to_id(newname);
2793 rb_alias(mod, id, oldid);
2794 return ID2SYM(id);
2795}
2796
2797static void
2798check_and_export_method(VALUE self, VALUE name, rb_method_visibility_t visi)
2799{
2800 ID id = rb_check_id(&name);
2801 if (!id) {
2802 rb_print_undef_str(self, name);
2803 }
2804 rb_export_method(self, id, visi);
2805}
2806
2807static void
2808set_method_visibility(VALUE self, int argc, const VALUE *argv, rb_method_visibility_t visi)
2809{
2810 int i;
2811
2812 rb_check_frozen(self);
2813 if (argc == 0) {
2814 rb_warning("%"PRIsVALUE" with no argument is just ignored",
2815 QUOTE_ID(rb_frame_callee()));
2816 return;
2817 }
2818
2819
2820 VALUE v;
2821
2822 if (argc == 1 && (v = rb_check_array_type(argv[0])) != Qnil) {
2823 long j;
2824
2825 for (j = 0; j < RARRAY_LEN(v); j++) {
2826 check_and_export_method(self, RARRAY_AREF(v, j), visi);
2827 }
2828 }
2829 else {
2830 for (i = 0; i < argc; i++) {
2831 check_and_export_method(self, argv[i], visi);
2832 }
2833 }
2834}
2835
2836static VALUE
2837set_visibility(int argc, const VALUE *argv, VALUE module, rb_method_visibility_t visi)
2838{
2839 if (argc == 0) {
2840 scope_visibility_check();
2841 rb_scope_visibility_set(visi);
2842 return Qnil;
2843 }
2844
2845 set_method_visibility(module, argc, argv, visi);
2846 if (argc == 1) {
2847 return argv[0];
2848 }
2849 return rb_ary_new_from_values(argc, argv);
2850}
2851
2852/*
2853 * call-seq:
2854 * public -> nil
2855 * public(method_name) -> method_name
2856 * public(method_name, method_name, ...) -> array
2857 * public(array) -> array
2858 *
2859 * With no arguments, sets the default visibility for subsequently
2860 * defined methods to public. With arguments, sets the named methods to
2861 * have public visibility.
2862 * String arguments are converted to symbols.
2863 * An Array of Symbols and/or Strings is also accepted.
2864 * If a single argument is passed, it is returned.
2865 * If no argument is passed, nil is returned.
2866 * If multiple arguments are passed, the arguments are returned as an array.
2867 */
2868
2869static VALUE
2870rb_mod_public(int argc, VALUE *argv, VALUE module)
2871{
2872 return set_visibility(argc, argv, module, METHOD_VISI_PUBLIC);
2873}
2874
2875/*
2876 * call-seq:
2877 * protected -> nil
2878 * protected(method_name) -> method_name
2879 * protected(method_name, method_name, ...) -> array
2880 * protected(array) -> array
2881 *
2882 * Sets the visibility of a section or of a list of method names as protected.
2883 * Accepts no arguments, a splat of method names (symbols or strings) or an
2884 * array of method names. Returns the arguments that it received.
2885 *
2886 * == Important difference between protected in other languages
2887 *
2888 * Protected methods in Ruby are different from other languages such as Java,
2889 * where methods are marked as protected to give access to subclasses. In Ruby,
2890 * subclasses <b>already have access to all methods defined in the parent
2891 * class</b>, even private ones.
2892 *
2893 * Marking a method as protected allows <b>different objects of the same
2894 * class</b> to call it.
2895 *
2896 * One use case is for comparison methods, such as <code>==</code>, if we want
2897 * to expose a method for comparison between objects of the same class without
2898 * making the method public to objects of other classes.
2899 *
2900 * == Performance considerations
2901 *
2902 * Protected methods are slower than others because they can't use inline
2903 * cache.
2904 *
2905 * == Example
2906 *
2907 * class Account
2908 * # Mark balance as protected, so that we can compare between accounts
2909 * # without making it public.
2910 * attr_reader :balance
2911 * protected :balance
2912 *
2913 * def initialize(balance)
2914 * @balance = balance
2915 * end
2916 *
2917 * def >(other)
2918 * # The invocation to `other.balance` is allowed because `other` is a
2919 * # different object of the same class (Account).
2920 * balance > other.balance
2921 * end
2922 * end
2923 *
2924 * account1 = Account.new(100)
2925 * account2 = Account.new(50)
2926 *
2927 * account1 > account2 # => true (works)
2928 * account1.balance # => NoMethodError (fails because balance is not public)
2929 *
2930 * To show a private method on RDoc, use <code>:doc:</code> instead of this.
2931 */
2932
2933static VALUE
2934rb_mod_protected(int argc, VALUE *argv, VALUE module)
2935{
2936 return set_visibility(argc, argv, module, METHOD_VISI_PROTECTED);
2937}
2938
2939/*
2940 * call-seq:
2941 * private -> nil
2942 * private(method_name) -> method_name
2943 * private(method_name, method_name, ...) -> array
2944 * private(array) -> array
2945 *
2946 * With no arguments, sets the default visibility for subsequently
2947 * defined methods to private. With arguments, sets the named methods
2948 * to have private visibility.
2949 * String arguments are converted to symbols.
2950 * An Array of Symbols and/or Strings is also accepted.
2951 * If a single argument is passed, it is returned.
2952 * If no argument is passed, nil is returned.
2953 * If multiple arguments are passed, the arguments are returned as an array.
2954 *
2955 * module Mod
2956 * def a() end
2957 * def b() end
2958 * private
2959 * def c() end
2960 * private :a
2961 * end
2962 * Mod.private_instance_methods #=> [:a, :c]
2963 *
2964 * Note that to show a private method on RDoc, use <code>:doc:</code>.
2965 */
2966
2967static VALUE
2968rb_mod_private(int argc, VALUE *argv, VALUE module)
2969{
2970 return set_visibility(argc, argv, module, METHOD_VISI_PRIVATE);
2971}
2972
2973/*
2974 * call-seq:
2975 * ruby2_keywords(method_name, ...) -> nil
2976 *
2977 * For the given method names, marks the method as passing keywords through
2978 * a normal argument splat. This should only be called on methods that
2979 * accept an argument splat (<tt>*args</tt>) but not explicit keywords or
2980 * a keyword splat. It marks the method such that if the method is called
2981 * with keyword arguments, the final hash argument is marked with a special
2982 * flag such that if it is the final element of a normal argument splat to
2983 * another method call, and that method call does not include explicit
2984 * keywords or a keyword splat, the final element is interpreted as keywords.
2985 * In other words, keywords will be passed through the method to other
2986 * methods.
2987 *
2988 * This should only be used for methods that delegate keywords to another
2989 * method, and only for backwards compatibility with Ruby versions before 3.0.
2990 * See https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/
2991 * for details on why +ruby2_keywords+ exists and when and how to use it.
2992 *
2993 * This method will probably be removed at some point, as it exists only
2994 * for backwards compatibility. As it does not exist in Ruby versions before
2995 * 2.7, check that the module responds to this method before calling it:
2996 *
2997 * module Mod
2998 * def foo(meth, *args, &block)
2999 * send(:"do_#{meth}", *args, &block)
3000 * end
3001 * ruby2_keywords(:foo) if respond_to?(:ruby2_keywords, true)
3002 * end
3003 *
3004 * However, be aware that if the +ruby2_keywords+ method is removed, the
3005 * behavior of the +foo+ method using the above approach will change so that
3006 * the method does not pass through keywords.
3007 */
3008
3009static VALUE
3010rb_mod_ruby2_keywords(int argc, VALUE *argv, VALUE module)
3011{
3012 int i;
3013 VALUE origin_class = RCLASS_ORIGIN(module);
3014
3016 rb_check_frozen(module);
3017
3018 for (i = 0; i < argc; i++) {
3019 VALUE v = argv[i];
3020 ID name = rb_check_id(&v);
3022 VALUE defined_class;
3023
3024 if (!name) {
3025 rb_print_undef_str(module, v);
3026 }
3027
3028 me = search_method(origin_class, name, &defined_class);
3029 if (!me && RB_TYPE_P(module, T_MODULE)) {
3030 me = search_method(rb_cObject, name, &defined_class);
3031 }
3032
3033 if (UNDEFINED_METHOD_ENTRY_P(me) ||
3034 UNDEFINED_REFINED_METHOD_P(me->def)) {
3035 rb_print_undef(module, name, METHOD_VISI_UNDEF);
3036 }
3037
3038 if (module == defined_class || origin_class == defined_class) {
3039 switch (me->def->type) {
3040 case VM_METHOD_TYPE_ISEQ:
3041 if (ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_rest &&
3042 !ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_post &&
3043 !ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_kw &&
3044 !ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_kwrest) {
3045 ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.ruby2_keywords = 1;
3046 rb_clear_method_cache(module, name);
3047 }
3048 else {
3049 rb_warn("Skipping set of ruby2_keywords flag for %"PRIsVALUE" (method accepts keywords or post arguments or method does not accept argument splat)", QUOTE_ID(name));
3050 }
3051 break;
3052 case VM_METHOD_TYPE_BMETHOD: {
3053 VALUE procval = me->def->body.bmethod.proc;
3054 if (vm_block_handler_type(procval) == block_handler_type_proc) {
3055 procval = vm_proc_to_block_handler(VM_BH_TO_PROC(procval));
3056 }
3057
3058 if (vm_block_handler_type(procval) == block_handler_type_iseq) {
3059 const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(procval);
3060 const rb_iseq_t *iseq = rb_iseq_check(captured->code.iseq);
3061 if (ISEQ_BODY(iseq)->param.flags.has_rest &&
3062 !ISEQ_BODY(iseq)->param.flags.has_post &&
3063 !ISEQ_BODY(iseq)->param.flags.has_kw &&
3064 !ISEQ_BODY(iseq)->param.flags.has_kwrest) {
3065 ISEQ_BODY(iseq)->param.flags.ruby2_keywords = 1;
3066 rb_clear_method_cache(module, name);
3067 }
3068 else {
3069 rb_warn("Skipping set of ruby2_keywords flag for %"PRIsVALUE" (method accepts keywords or post arguments or method does not accept argument splat)", QUOTE_ID(name));
3070 }
3071 break;
3072 }
3073 }
3074 /* fallthrough */
3075 default:
3076 rb_warn("Skipping set of ruby2_keywords flag for %"PRIsVALUE" (method not defined in Ruby)", QUOTE_ID(name));
3077 break;
3078 }
3079 }
3080 else {
3081 rb_warn("Skipping set of ruby2_keywords flag for %"PRIsVALUE" (can only set in method defining module)", QUOTE_ID(name));
3082 }
3083 }
3084 return Qnil;
3085}
3086
3087/*
3088 * call-seq:
3089 * mod.public_class_method(symbol, ...) -> mod
3090 * mod.public_class_method(string, ...) -> mod
3091 * mod.public_class_method(array) -> mod
3092 *
3093 * Makes a list of existing class methods public.
3094 *
3095 * String arguments are converted to symbols.
3096 * An Array of Symbols and/or Strings is also accepted.
3097 */
3098
3099static VALUE
3100rb_mod_public_method(int argc, VALUE *argv, VALUE obj)
3101{
3102 set_method_visibility(rb_singleton_class(obj), argc, argv, METHOD_VISI_PUBLIC);
3103 return obj;
3104}
3105
3106/*
3107 * call-seq:
3108 * mod.private_class_method(symbol, ...) -> mod
3109 * mod.private_class_method(string, ...) -> mod
3110 * mod.private_class_method(array) -> mod
3111 *
3112 * Makes existing class methods private. Often used to hide the default
3113 * constructor <code>new</code>.
3114 *
3115 * String arguments are converted to symbols.
3116 * An Array of Symbols and/or Strings is also accepted.
3117 *
3118 * class SimpleSingleton # Not thread safe
3119 * private_class_method :new
3120 * def SimpleSingleton.create(*args, &block)
3121 * @me = new(*args, &block) if ! @me
3122 * @me
3123 * end
3124 * end
3125 */
3126
3127static VALUE
3128rb_mod_private_method(int argc, VALUE *argv, VALUE obj)
3129{
3130 set_method_visibility(rb_singleton_class(obj), argc, argv, METHOD_VISI_PRIVATE);
3131 return obj;
3132}
3133
3134/*
3135 * call-seq:
3136 * public
3137 * public(symbol, ...)
3138 * public(string, ...)
3139 * public(array)
3140 *
3141 * With no arguments, sets the default visibility for subsequently
3142 * defined methods to public. With arguments, sets the named methods to
3143 * have public visibility.
3144 *
3145 * String arguments are converted to symbols.
3146 * An Array of Symbols and/or Strings is also accepted.
3147 */
3148
3149static VALUE
3150top_public(int argc, VALUE *argv, VALUE _)
3151{
3152 return rb_mod_public(argc, argv, rb_top_main_class("public"));
3153}
3154
3155/*
3156 * call-seq:
3157 * private
3158 * private(symbol, ...)
3159 * private(string, ...)
3160 * private(array)
3161 *
3162 * With no arguments, sets the default visibility for subsequently
3163 * defined methods to private. With arguments, sets the named methods to
3164 * have private visibility.
3165 *
3166 * String arguments are converted to symbols.
3167 * An Array of Symbols and/or Strings is also accepted.
3168 */
3169static VALUE
3170top_private(int argc, VALUE *argv, VALUE _)
3171{
3172 return rb_mod_private(argc, argv, rb_top_main_class("private"));
3173}
3174
3175/*
3176 * call-seq:
3177 * ruby2_keywords(method_name, ...) -> self
3178 *
3179 * For the given method names, marks the method as passing keywords through
3180 * a normal argument splat. See Module#ruby2_keywords in detail.
3181 */
3182static VALUE
3183top_ruby2_keywords(int argc, VALUE *argv, VALUE module)
3184{
3185 return rb_mod_ruby2_keywords(argc, argv, rb_top_main_class("ruby2_keywords"));
3186}
3187
3188/*
3189 * call-seq:
3190 * module_function -> nil
3191 * module_function(method_name) -> method_name
3192 * module_function(method_name, method_name, ...) -> array
3193 *
3194 * Creates module functions for the named methods. These functions may
3195 * be called with the module as a receiver, and also become available
3196 * as instance methods to classes that mix in the module. Module
3197 * functions are copies of the original, and so may be changed
3198 * independently. The instance-method versions are made private. If
3199 * used with no arguments, subsequently defined methods become module
3200 * functions.
3201 * String arguments are converted to symbols.
3202 * If a single argument is passed, it is returned.
3203 * If no argument is passed, nil is returned.
3204 * If multiple arguments are passed, the arguments are returned as an array.
3205 *
3206 * module Mod
3207 * def one
3208 * "This is one"
3209 * end
3210 * module_function :one
3211 * end
3212 * class Cls
3213 * include Mod
3214 * def call_one
3215 * one
3216 * end
3217 * end
3218 * Mod.one #=> "This is one"
3219 * c = Cls.new
3220 * c.call_one #=> "This is one"
3221 * module Mod
3222 * def one
3223 * "This is the new one"
3224 * end
3225 * end
3226 * Mod.one #=> "This is one"
3227 * c.call_one #=> "This is the new one"
3228 */
3229
3230static VALUE
3231rb_mod_modfunc(int argc, VALUE *argv, VALUE module)
3232{
3233 int i;
3234 ID id;
3235 const rb_method_entry_t *me;
3236
3237 if (!RB_TYPE_P(module, T_MODULE)) {
3238 rb_raise(rb_eTypeError, "module_function must be called for modules");
3239 }
3240
3241 if (argc == 0) {
3242 rb_scope_module_func_set();
3243 return Qnil;
3244 }
3245
3246 set_method_visibility(module, argc, argv, METHOD_VISI_PRIVATE);
3247
3248 for (i = 0; i < argc; i++) {
3249 VALUE m = module;
3250
3251 id = rb_to_id(argv[i]);
3252 for (;;) {
3253 me = search_method(m, id, 0);
3254 if (me == 0) {
3255 me = search_method(rb_cObject, id, 0);
3256 }
3257 if (UNDEFINED_METHOD_ENTRY_P(me)) {
3258 rb_print_undef(module, id, METHOD_VISI_UNDEF);
3259 }
3260 if (me->def->type != VM_METHOD_TYPE_ZSUPER) {
3261 break; /* normal case: need not to follow 'super' link */
3262 }
3263 m = RCLASS_SUPER(m);
3264 if (!m)
3265 break;
3266 }
3267 rb_method_entry_set(rb_singleton_class(module), id, me, METHOD_VISI_PUBLIC);
3268 }
3269 if (argc == 1) {
3270 return argv[0];
3271 }
3272 return rb_ary_new_from_values(argc, argv);
3273}
3274
3275#ifdef __GNUC__
3276#pragma push_macro("rb_method_basic_definition_p")
3277#undef rb_method_basic_definition_p
3278#endif
3279int
3280rb_method_basic_definition_p(VALUE klass, ID id)
3281{
3282 const rb_callable_method_entry_t *cme;
3283 if (!klass) return TRUE; /* hidden object cannot be overridden */
3284 cme = rb_callable_method_entry(klass, id);
3285 return (cme && METHOD_ENTRY_BASIC(cme)) ? TRUE : FALSE;
3286}
3287#ifdef __GNUC__
3288#pragma pop_macro("rb_method_basic_definition_p")
3289#endif
3290
3291static VALUE
3292call_method_entry(rb_execution_context_t *ec, VALUE defined_class, VALUE obj, ID id,
3293 const rb_callable_method_entry_t *cme, int argc, const VALUE *argv, int kw_splat)
3294{
3295 VALUE passed_block_handler = vm_passed_block_handler(ec);
3296 VALUE result = rb_vm_call_kw(ec, obj, id, argc, argv, cme, kw_splat);
3297 vm_passed_block_handler_set(ec, passed_block_handler);
3298 return result;
3299}
3300
3301static VALUE
3302basic_obj_respond_to_missing(rb_execution_context_t *ec, VALUE klass, VALUE obj,
3303 VALUE mid, VALUE priv)
3304{
3305 VALUE defined_class, args[2];
3306 const ID rtmid = idRespond_to_missing;
3307 const rb_callable_method_entry_t *const cme = callable_method_entry(klass, rtmid, &defined_class);
3308
3309 if (!cme || METHOD_ENTRY_BASIC(cme)) return Qundef;
3310 args[0] = mid;
3311 args[1] = priv;
3312 return call_method_entry(ec, defined_class, obj, rtmid, cme, 2, args, RB_NO_KEYWORDS);
3313}
3314
3315static inline int
3316basic_obj_respond_to(rb_execution_context_t *ec, VALUE obj, ID id, int pub)
3317{
3318 VALUE klass = CLASS_OF(obj);
3319 VALUE ret;
3320
3321 switch (method_boundp(klass, id, pub|BOUND_RESPONDS)) {
3322 case 2:
3323 return FALSE;
3324 case 0:
3325 ret = basic_obj_respond_to_missing(ec, klass, obj, ID2SYM(id),
3326 RBOOL(!pub));
3327 return RTEST(ret) && !UNDEF_P(ret);
3328 default:
3329 return TRUE;
3330 }
3331}
3332
3333static int
3334vm_respond_to(rb_execution_context_t *ec, VALUE klass, VALUE obj, ID id, int priv)
3335{
3336 VALUE defined_class;
3337 const ID resid = idRespond_to;
3338 const rb_callable_method_entry_t *const cme = callable_method_entry(klass, resid, &defined_class);
3339
3340 if (!cme) return -1;
3341 if (METHOD_ENTRY_BASIC(cme)) {
3342 return -1;
3343 }
3344 else {
3345 int argc = 1;
3346 VALUE args[2];
3347 VALUE result;
3348
3349 args[0] = ID2SYM(id);
3350 args[1] = Qtrue;
3351 if (priv) {
3352 argc = rb_method_entry_arity((const rb_method_entry_t *)cme);
3353 if (argc > 2) {
3354 rb_raise(rb_eArgError,
3355 "respond_to? must accept 1 or 2 arguments (requires %d)",
3356 argc);
3357 }
3358 if (argc != 1) {
3359 argc = 2;
3360 }
3361 else if (!NIL_P(ruby_verbose)) {
3362 VALUE location = rb_method_entry_location((const rb_method_entry_t *)cme);
3364 "%"PRIsVALUE"%c""respond_to?(:%"PRIsVALUE") uses"
3365 " the deprecated method signature, which takes one parameter",
3366 (RCLASS_SINGLETON_P(klass) ? obj : klass),
3367 (RCLASS_SINGLETON_P(klass) ? '.' : '#'),
3368 QUOTE_ID(id));
3369 if (!NIL_P(location)) {
3370 VALUE path = RARRAY_AREF(location, 0);
3371 VALUE line = RARRAY_AREF(location, 1);
3372 if (!NIL_P(path)) {
3374 RSTRING_PTR(path), NUM2INT(line),
3375 "respond_to? is defined here");
3376 }
3377 }
3378 }
3379 }
3380 result = call_method_entry(ec, defined_class, obj, resid, cme, argc, args, RB_NO_KEYWORDS);
3381 return RTEST(result);
3382 }
3383}
3384
3385int
3386rb_obj_respond_to(VALUE obj, ID id, int priv)
3387{
3388 rb_execution_context_t *ec = GET_EC();
3389 return rb_ec_obj_respond_to(ec, obj, id, priv);
3390}
3391
3392int
3393rb_ec_obj_respond_to(rb_execution_context_t *ec, VALUE obj, ID id, int priv)
3394{
3395 VALUE klass = CLASS_OF(obj);
3396 int ret = vm_respond_to(ec, klass, obj, id, priv);
3397 if (ret == -1) ret = basic_obj_respond_to(ec, obj, id, !priv);
3398 return ret;
3399}
3400
3401int
3403{
3404 return rb_obj_respond_to(obj, id, FALSE);
3405}
3406
3407
3408/*
3409 * call-seq:
3410 * obj.respond_to?(symbol, include_all=false) -> true or false
3411 * obj.respond_to?(string, include_all=false) -> true or false
3412 *
3413 * Returns +true+ if _obj_ responds to the given method. Private and
3414 * protected methods are included in the search only if the optional
3415 * second parameter evaluates to +true+.
3416 *
3417 * If the method is not implemented,
3418 * as Process.fork on Windows, File.lchmod on GNU/Linux, etc.,
3419 * false is returned.
3420 *
3421 * If the method is not defined, <code>respond_to_missing?</code>
3422 * method is called and the result is returned.
3423 *
3424 * When the method name parameter is given as a string, the string is
3425 * converted to a symbol.
3426 */
3427
3428static VALUE
3429obj_respond_to(int argc, VALUE *argv, VALUE obj)
3430{
3431 VALUE mid, priv;
3432 ID id;
3433 rb_execution_context_t *ec = GET_EC();
3434
3435 rb_scan_args(argc, argv, "11", &mid, &priv);
3436 if (!(id = rb_check_id(&mid))) {
3437 VALUE ret = basic_obj_respond_to_missing(ec, CLASS_OF(obj), obj,
3438 rb_to_symbol(mid), priv);
3439 if (UNDEF_P(ret)) ret = Qfalse;
3440 return ret;
3441 }
3442 return RBOOL(basic_obj_respond_to(ec, obj, id, !RTEST(priv)));
3443}
3444
3445/*
3446 * call-seq:
3447 * obj.respond_to_missing?(symbol, include_all) -> true or false
3448 * obj.respond_to_missing?(string, include_all) -> true or false
3449 *
3450 * DO NOT USE THIS DIRECTLY.
3451 *
3452 * Hook method to return whether the _obj_ can respond to _id_ method
3453 * or not.
3454 *
3455 * When the method name parameter is given as a string, the string is
3456 * converted to a symbol.
3457 *
3458 * See #respond_to?, and the example of BasicObject.
3459 */
3460static VALUE
3461obj_respond_to_missing(VALUE obj, VALUE mid, VALUE priv)
3462{
3463 return Qfalse;
3464}
3465
3466void
3467Init_eval_method(void)
3468{
3469 rb_define_method(rb_mKernel, "respond_to?", obj_respond_to, -1);
3470 rb_define_method(rb_mKernel, "respond_to_missing?", obj_respond_to_missing, 2);
3471
3472 rb_define_method(rb_cModule, "remove_method", rb_mod_remove_method, -1);
3473 rb_define_method(rb_cModule, "undef_method", rb_mod_undef_method, -1);
3474 rb_define_method(rb_cModule, "alias_method", rb_mod_alias_method, 2);
3475 rb_define_private_method(rb_cModule, "public", rb_mod_public, -1);
3476 rb_define_private_method(rb_cModule, "protected", rb_mod_protected, -1);
3477 rb_define_private_method(rb_cModule, "private", rb_mod_private, -1);
3478 rb_define_private_method(rb_cModule, "module_function", rb_mod_modfunc, -1);
3479 rb_define_private_method(rb_cModule, "ruby2_keywords", rb_mod_ruby2_keywords, -1);
3480
3481 rb_define_method(rb_cModule, "method_defined?", rb_mod_method_defined, -1);
3482 rb_define_method(rb_cModule, "public_method_defined?", rb_mod_public_method_defined, -1);
3483 rb_define_method(rb_cModule, "private_method_defined?", rb_mod_private_method_defined, -1);
3484 rb_define_method(rb_cModule, "protected_method_defined?", rb_mod_protected_method_defined, -1);
3485 rb_define_method(rb_cModule, "public_class_method", rb_mod_public_method, -1);
3486 rb_define_method(rb_cModule, "private_class_method", rb_mod_private_method, -1);
3487
3489 "public", top_public, -1);
3491 "private", top_private, -1);
3493 "ruby2_keywords", top_ruby2_keywords, -1);
3494
3495 {
3496#define REPLICATE_METHOD(klass, id) do { \
3497 const rb_method_entry_t *me = rb_method_entry((klass), (id)); \
3498 rb_method_entry_set((klass), (id), me, METHOD_ENTRY_VISI(me)); \
3499 } while (0)
3500
3501 REPLICATE_METHOD(rb_eException, idMethodMissing);
3502 REPLICATE_METHOD(rb_eException, idRespond_to);
3503 REPLICATE_METHOD(rb_eException, idRespond_to_missing);
3504 }
3505}
#define RUBY_ASSERT_ALWAYS(expr,...)
A variant of RUBY_ASSERT that does not interface with RUBY_DEBUG.
Definition assert.h:199
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define RUBY_ATOMIC_FETCH_ADD(var, val)
Atomically replaces the value pointed by var with the result of addition of val to the old value of v...
Definition atomic.h:118
#define RUBY_ATOMIC_FETCH_SUB(var, val)
Atomically replaces the value pointed by var with the result of subtraction of val to the old value o...
Definition atomic.h:129
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2913
void rb_class_modify_check(VALUE klass)
Asserts that klass is not a frozen class.
Definition eval.c:421
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3246
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:130
void rb_notimplement(void)
Definition error.c:3840
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:476
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:475
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
void rb_category_compile_warn(rb_warning_category_t category, const char *file, int line, const char *fmt,...)
Identical to rb_compile_warn(), except it also accepts category.
Definition error.c:439
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
VALUE rb_eException
Mother of all exceptions.
Definition error.c:1423
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:497
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition error.h:48
VALUE rb_mKernel
Kernel module.
Definition object.c:60
VALUE rb_cModule
Module class.
Definition object.c:62
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:176
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:615
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:603
VALUE rb_ary_new_from_values(long n, const VALUE *elts)
Identical to rb_ary_new_from_args(), except how objects are passed.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
void rb_undef(VALUE mod, ID mid)
Inserts a method entry that hides previous method definition of the given name.
Definition vm_method.c:2314
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:941
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1776
VALUE rb_mod_name(VALUE mod)
Queries the name of a module.
Definition variable.c:136
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3402
VALUE(* rb_alloc_func_t)(VALUE klass)
This is the type of functions that ruby calls when trying to allocate an object.
Definition vm.h:219
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1650
void rb_alias(VALUE klass, ID dst, ID src)
Resembles alias.
Definition vm_method.c:2697
void rb_attr(VALUE klass, ID name, int need_reader, int need_writer, int honour_visibility)
This function resembles now-deprecated Module#attr.
Definition vm_method.c:2277
void rb_remove_method(VALUE klass, const char *name)
Removes a method.
Definition vm_method.c:2126
rb_alloc_func_t rb_get_alloc_func(VALUE klass)
Queries the allocator function of a class.
Definition vm_method.c:1656
void rb_clear_constant_cache_for_id(ID id)
Clears the inline constant caches associated with a particular ID.
Definition vm_method.c:332
void rb_remove_method_id(VALUE klass, ID mid)
Identical to rb_remove_method(), except it accepts the method name as ID.
Definition vm_method.c:2120
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
Definition vm_method.c:804
int rb_method_boundp(VALUE klass, ID id, int ex)
Queries if the klass has this method.
Definition vm_method.c:2238
int rb_obj_respond_to(VALUE obj, ID mid, int private_p)
Identical to rb_respond_to(), except it additionally takes the visibility parameter.
Definition vm_method.c:3386
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1133
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:12663
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:12653
int capa
Designed capacity of the buffer.
Definition io.h:11
VALUE type(ANYARGS)
ANYARGS-ed function type.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
Definition rclass.h:44
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
#define ANYARGS
Functions declared using this macro take arbitrary arguments, including void.
Definition stdarg.h:64
Definition vm_method.c:391
Definition method.h:63
CREF (Class REFerence)
Definition method.h:45
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:208
size_t(* dsize)(const void *)
This function is to query the size of the underlying memory regions.
Definition rtypeddata.h:248
RUBY_DATA_FUNC dfree
This function is called when the object is no longer used.
Definition rtypeddata.h:238
const char * wrap_struct_name
Name of structs of this kind.
Definition rtypeddata.h:215
struct rb_data_type_struct::@55 function
Function pointers.
VALUE flags
Type-specific behavioural characteristics.
Definition rtypeddata.h:317
Definition method.h:55
rb_cref_t * cref
class reference, should be marked
Definition method.h:144
const rb_iseq_t * iseqptr
iseq pointer, should be separated from iseqval
Definition method.h:143
Definition st.h:79
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:433
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376