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