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