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