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