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