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