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