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