Ruby 4.1.0dev (2026-09-21 revision 8befacf9e6c898a0f79dcb53bdd2e4cea24e0d1c)
class.c (8befacf9e6c898a0f79dcb53bdd2e4cea24e0d1c)
1/**********************************************************************
2
3 class.c -
4
5 $Author$
6 created at: Tue Aug 10 15:05:44 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
17#include "ruby/internal/config.h"
18#include <ctype.h>
19
20#include "constant.h"
21#include "debug_counter.h"
22#include "id_table.h"
23#include "internal.h"
24#include "internal/box.h"
25#include "internal/class.h"
26#include "internal/error.h"
27#include "internal/eval.h"
28#include "internal/gc.h"
29#include "internal/hash.h"
30#include "internal/object.h"
31#include "internal/string.h"
32#include "internal/variable.h"
33#include "internal/vm.h"
34#include "ruby/st.h"
35#include "vm_core.h"
36#include "ruby/ractor.h"
37#include "ractor_core.h"
38#include "yjit.h"
39#include "zjit.h"
40
41/* Flags of T_CLASS
42 *
43 * 0: RCLASS_IS_ROOT
44 * The class has been added to the VM roots. Will always be marked and pinned.
45 * This is done for classes defined from C to allow storing them in global variables.
46 * 1: RUBY_FL_SINGLETON
47 * This class is a singleton class.
48 * 2: RCLASS_PRIME_CLASSEXT_WRITABLE
49 * This class's prime classext is the only classext and writable from any boxes.
50 * If unset, the prime classext is writable only from the root box.
51 * 3: RCLASS_IS_INITIALIZED
52 * Class has been initialized.
53 * 4: RCLASS_BOXABLE
54 * Is a builtin class that may be boxed. It larger than a normal class.
55 */
56
57/* Flags of T_ICLASS
58 *
59 * 2: RCLASS_PRIME_CLASSEXT_WRITABLE
60 * This module's prime classext is the only classext and writable from any boxes.
61 * If unset, the prime classext is writable only from the root box.
62 * 4: RCLASS_BOXABLE
63 * Is a builtin class that may be boxed. It larger than a normal class.
64 */
65
66/* Flags of T_MODULE
67 *
68 * 0: RCLASS_IS_ROOT
69 * The class has been added to the VM roots. Will always be marked and pinned.
70 * This is done for classes defined from C to allow storing them in global variables.
71 * 1: <reserved>
72 * Ensures that RUBY_FL_SINGLETON is never set on a T_MODULE. See `rb_class_real`.
73 * 2: RCLASS_PRIME_CLASSEXT_WRITABLE
74 * This module's prime classext is the only classext and writable from any boxes.
75 * If unset, the prime classext is writable only from the root box.
76 * 3: RCLASS_IS_INITIALIZED
77 * Module has been initialized.
78 * 4: RCLASS_BOXABLE
79 * Is a builtin class that may be boxed. It larger than a normal class.
80 * 5: RMODULE_IS_REFINEMENT
81 * Module is used for refinements.
82 */
83
84#define METACLASS_OF(k) RBASIC(k)->klass
85#define SET_METACLASS_OF(k, cls) RBASIC_SET_CLASS(k, cls)
86
88rb_class_unlink_classext(VALUE klass, const rb_box_t *box)
89{
90 st_data_t ext;
91 st_data_t key = (st_data_t)box->box_object;
92 st_delete(box->classext_cow_classes, &klass, 0);
93 st_delete(RCLASS_CLASSEXT_TBL(klass), &key, &ext);
94 return (rb_classext_t *)ext;
95}
96
97void
98rb_class_classext_free(VALUE klass, rb_classext_t *ext, bool is_prime)
99{
100 struct rb_id_table *tbl;
101
102 rb_id_table_free(RCLASSEXT_M_TBL(ext));
103
104 if (!RCLASSEXT_SHARED_CONST_TBL(ext) && (tbl = RCLASSEXT_CONST_TBL(ext)) != NULL) {
105 rb_free_const_table(tbl);
106 }
107
108 if (RCLASSEXT_SUPERCLASSES_WITH_SELF(ext)) {
109 RUBY_ASSERT(is_prime); // superclasses should only be used on prime
110 size_t depth = RCLASSEXT_SUPERCLASS_DEPTH(ext);
111 if (depth != RCLASS_MAX_SUPERCLASS_DEPTH) {
112 depth++;
113 }
114 SIZED_FREE_N(RCLASSEXT_SUPERCLASSES(ext), depth);
115 }
116
117 if (!is_prime) { // the prime classext will be freed with RClass
118 SIZED_FREE(ext);
119 }
120}
121
122void
123rb_iclass_classext_free(VALUE klass, rb_classext_t *ext, bool is_prime)
124{
125 if (RCLASSEXT_ICLASS_IS_ORIGIN(ext) && !RCLASSEXT_ICLASS_ORIGIN_SHARED_MTBL(ext)) {
126 /* Method table is not shared for origin iclasses of classes */
127 rb_id_table_free(RCLASSEXT_M_TBL(ext));
128 }
129
130 if (RCLASSEXT_CALLABLE_M_TBL(ext) != NULL) {
131 rb_id_table_free(RCLASSEXT_CALLABLE_M_TBL(ext));
132 }
133
134 if (!is_prime) { // the prime classext will be freed with RClass
135 SIZED_FREE(ext);
136 }
137}
138
139static void
140iclass_free_orphan_classext(VALUE klass, rb_classext_t *ext)
141{
142 if (RCLASSEXT_ICLASS_IS_ORIGIN(ext) && !RCLASSEXT_ICLASS_ORIGIN_SHARED_MTBL(ext)) {
143 /* Method table is not shared for origin iclasses of classes */
144 rb_id_table_free(RCLASSEXT_M_TBL(ext));
145 }
146
147 if (RCLASSEXT_CALLABLE_M_TBL(ext) != NULL) {
148 rb_id_table_free(RCLASSEXT_CALLABLE_M_TBL(ext));
149 }
150
151 SIZED_FREE(ext);
152}
153
155 VALUE obj;
156 rb_classext_t *ext;
157};
158
159static int
160set_box_classext_update(st_data_t *key_ptr, st_data_t *val_ptr, st_data_t a, int existing)
161{
163
164 if (existing) {
165 if (LIKELY(BUILTIN_TYPE(args->obj) == T_ICLASS)) {
166 iclass_free_orphan_classext(args->obj, (rb_classext_t *)*val_ptr);
167 }
168 else {
169 rb_bug("Updating existing classext for non-iclass never happen");
170 }
171 }
172
173 *val_ptr = (st_data_t)args->ext;
174
175 return ST_CONTINUE;
176}
177
178void
179rb_class_set_box_classext(VALUE obj, const rb_box_t *box, rb_classext_t *ext)
180{
181 struct rb_class_set_box_classext_args args = {
182 .obj = obj,
183 .ext = ext,
184 };
185
186 VM_ASSERT(BOX_MUTABLE_P(box));
187
188 st_update(RCLASS_CLASSEXT_TBL(obj), (st_data_t)box->box_object, set_box_classext_update, (st_data_t)&args);
189
190 // The classext references are now visible via the classext table,
191 // so we must issue the write barrier before any further allocations
192 // (e.g. st_insert below) that could trigger GC.
193 rb_gc_writebarrier_remember(obj);
194
195 st_insert(box->classext_cow_classes, (st_data_t)obj, 0);
196}
197
198RUBY_EXTERN rb_serial_t ruby_vm_global_cvar_state;
199
201 struct rb_id_table *tbl;
202 VALUE klass;
203};
204
205static enum rb_id_table_iterator_result
206duplicate_classext_m_tbl_i(ID key, VALUE value, void *data)
207{
208 struct duplicate_id_tbl_data *arg = (struct duplicate_id_tbl_data *)data;
210 rb_method_table_insert0(arg->klass, arg->tbl, key, me, false);
211 return ID_TABLE_CONTINUE;
212}
213
214static struct rb_id_table *
215duplicate_classext_m_tbl(struct rb_id_table *orig, VALUE klass, bool init_missing)
216{
217 struct rb_id_table *tbl;
218 if (!orig) {
219 if (init_missing)
220 return rb_id_table_create(0);
221 else
222 return NULL;
223 }
224 tbl = rb_id_table_create(rb_id_table_size(orig));
225 struct duplicate_id_tbl_data data = {
226 .tbl = tbl,
227 .klass = klass,
228 };
229 rb_id_table_foreach(orig, duplicate_classext_m_tbl_i, &data);
230 return tbl;
231}
232
233static rb_const_entry_t *
234duplicate_classext_const_entry(rb_const_entry_t *src, VALUE klass)
235{
236 // See also: setup_const_entry (variable.c)
238
239 dst->flag = src->flag;
240 dst->line = src->line;
241 RB_OBJ_WRITE(klass, &dst->value, src->value);
242 RB_OBJ_WRITE(klass, &dst->file, src->file);
243
244 return dst;
245}
246
247static enum rb_id_table_iterator_result
248duplicate_classext_const_tbl_i(ID key, VALUE value, void *data)
249{
250 struct duplicate_id_tbl_data *arg = (struct duplicate_id_tbl_data *)data;
251 rb_const_entry_t *entry = duplicate_classext_const_entry((rb_const_entry_t *)value, arg->klass);
252
253 rb_id_table_insert(arg->tbl, key, (VALUE)entry);
254
255 return ID_TABLE_CONTINUE;
256}
257
258static struct rb_id_table *
259duplicate_classext_const_tbl(struct rb_id_table *src, VALUE klass)
260{
261 struct rb_id_table *dst;
262
263 if (!src)
264 return NULL;
265
266 dst = rb_id_table_create(rb_id_table_size(src));
267
268 struct duplicate_id_tbl_data data = {
269 .tbl = dst,
270 .klass = klass,
271 };
272 rb_id_table_foreach(src, duplicate_classext_const_tbl_i, (void *)&data);
273
274 return dst;
275}
276
277static void
278class_duplicate_iclass_classext(VALUE iclass, rb_classext_t *mod_ext, const rb_box_t *box)
279{
281
282 rb_classext_t *src = RCLASS_EXT_PRIME(iclass);
283 rb_classext_t *ext = RCLASS_EXT_TABLE_LOOKUP_INTERNAL(iclass, box);
284 int first_set = 0;
285
286 if (ext) {
287 // iclass classext for the ns is only for cc/callable_m_tbl if it's created earlier than module's one
288 rb_invalidate_method_caches(RCLASSEXT_CALLABLE_M_TBL(ext), RCLASSEXT_CC_TBL(ext));
289 }
290
291 ext = ZALLOC(rb_classext_t);
292
293 RCLASSEXT_BOX(ext) = box;
294
295 RCLASSEXT_SUPER(ext) = RCLASSEXT_SUPER(src);
296
297 // See also: rb_include_class_new()
298 if (RCLASSEXT_ICLASS_IS_ORIGIN(src) && !RCLASSEXT_ICLASS_ORIGIN_SHARED_MTBL(src)) {
299 RCLASSEXT_M_TBL(ext) = duplicate_classext_m_tbl(RCLASSEXT_M_TBL(src), iclass, true);
300 }
301 else {
302 RCLASSEXT_M_TBL(ext) = RCLASSEXT_M_TBL(mod_ext);
303 }
304
305 RCLASSEXT_CONST_TBL(ext) = RCLASSEXT_CONST_TBL(mod_ext);
306 RCLASSEXT_CVC_TBL(ext) = RCLASSEXT_CVC_TBL(mod_ext);
307
308 // Those are cache and should be recreated when methods are called
309 // RCLASSEXT_CALLABLE_M_TBL(ext) = NULL;
310 // RCLASSEXT_CC_TBL(ext) = NULL;
311
312 // Subclasses/back-pointers are only in the prime classext.
313
314 RCLASSEXT_SET_ORIGIN(ext, iclass, RCLASSEXT_ORIGIN(src));
315 RCLASSEXT_ICLASS_IS_ORIGIN(ext) = RCLASSEXT_ICLASS_IS_ORIGIN(src);
316 RCLASSEXT_ICLASS_ORIGIN_SHARED_MTBL(ext) = RCLASSEXT_ICLASS_ORIGIN_SHARED_MTBL(src);
317
318 RCLASSEXT_SET_INCLUDER(ext, iclass, RCLASSEXT_INCLUDER(src));
319
320 VM_ASSERT(FL_TEST_RAW(iclass, RCLASS_BOXABLE));
321
322 first_set = RCLASS_SET_BOX_CLASSEXT(iclass, box, ext);
323 if (first_set) {
324 RCLASS_SET_PRIME_CLASSEXT_WRITABLE(iclass, false);
325 }
326}
327
329rb_class_duplicate_classext(rb_classext_t *orig, VALUE klass, const rb_box_t *box)
330{
331 VM_ASSERT(RB_TYPE_P(klass, T_CLASS) || RB_TYPE_P(klass, T_MODULE) || RB_TYPE_P(klass, T_ICLASS));
332
334 bool dup_iclass = RB_TYPE_P(klass, T_MODULE) ? true : false;
335
336 RCLASSEXT_BOX(ext) = box;
337
338 RCLASSEXT_SUPER(ext) = RCLASSEXT_SUPER(orig);
339
340 RCLASSEXT_M_TBL(ext) = duplicate_classext_m_tbl(RCLASSEXT_M_TBL(orig), klass, dup_iclass);
341 RCLASSEXT_ICLASS_IS_ORIGIN(ext) = true;
342 RCLASSEXT_ICLASS_ORIGIN_SHARED_MTBL(ext) = false;
343
344 if (orig->fields_obj) {
345 RB_OBJ_WRITE(klass, &ext->fields_obj, rb_imemo_fields_clone(orig->fields_obj));
346 }
347
348 if (RCLASSEXT_SHARED_CONST_TBL(orig)) {
349 RCLASSEXT_CONST_TBL(ext) = RCLASSEXT_CONST_TBL(orig);
350 RCLASSEXT_SHARED_CONST_TBL(ext) = true;
351 }
352 else {
353 RCLASSEXT_CONST_TBL(ext) = duplicate_classext_const_tbl(RCLASSEXT_CONST_TBL(orig), klass);
354 RCLASSEXT_SHARED_CONST_TBL(ext) = false;
355 }
356 /*
357 * callable_m_tbl is for `super` chain, and entries will be created when the super chain is called.
358 * so initially, it can be NULL and let it be created lazily.
359 * RCLASSEXT_CALLABLE_M_TBL(ext) = NULL;
360 *
361 * cc_tbl is for method inline cache, and method calls from different boxes never occur on
362 * the same code, so the copied classext should have a different cc_tbl from the prime one.
363 * RCLASSEXT_CC_TBL(copy) = NULL
364 */
365
366 VALUE cvc_table = RCLASSEXT_CVC_TBL(orig);
367 if (cvc_table) {
368 cvc_table = rb_marked_id_table_dup(cvc_table);
369 }
370 else if (dup_iclass) {
371 cvc_table = rb_marked_id_table_new(2);
372 }
373 RB_OBJ_WRITE(klass, &RCLASSEXT_CVC_TBL(ext), cvc_table);
374
375 // Subclasses/back-pointers are only in the prime classext.
376
377 RCLASSEXT_SET_ORIGIN(ext, klass, RCLASSEXT_ORIGIN(orig));
378 /*
379 * Members not copied to box's classext values
380 * * refined_class
381 * * as.class.allocator / as.singleton_class.attached_object
382 * * includer
383 * * max IV count
384 * * variation count
385 */
386 RCLASSEXT_PERMANENT_CLASSPATH(ext) = RCLASSEXT_PERMANENT_CLASSPATH(orig);
387 RCLASSEXT_CLASSPATH(ext) = RCLASSEXT_CLASSPATH(orig);
388
389 /* For the usual T_CLASS/T_MODULE, iclass flags are always false */
390
391 if (dup_iclass) {
392 /*
393 * ICLASS has the same m_tbl/const_tbl/cvc_tbl with the included module.
394 * So the module's classext is copied, its tables should be also referred
395 * by the ICLASS's classext for the box.
396 *
397 * Subclasses are only in the prime classext, so read from orig.
398 */
399 VALUE subs_v = RCLASSEXT_SUBCLASSES(orig);
400 if (subs_v) {
401 struct rb_subclasses *subs = (struct rb_subclasses *)subs_v;
402 VALUE *entries = rb_imemo_subclasses_entries(subs_v);
403 for (uint32_t i = 0; i < subs->count; i++) {
404 VALUE iclass = entries[i];
405 if (!iclass) continue;
406
407 /* every node in the subclass list should be an ICLASS built from this module */
408 VM_ASSERT(RB_TYPE_P(iclass, T_ICLASS));
409 VM_ASSERT(RBASIC_CLASS(iclass) == klass);
410
411 if (FL_TEST_RAW(iclass, RCLASS_BOXABLE)) {
412 // Non-boxable ICLASSes (included by classes in main/user boxes) can't
413 // hold per-box classexts, and their includer classes also can't, so
414 // method lookup through them always uses the prime classext.
415 class_duplicate_iclass_classext(iclass, ext, box);
416 }
417 }
418 }
419 }
420
421 return ext;
422}
423
424void
425rb_class_ensure_writable(VALUE klass)
426{
427 VM_ASSERT(RB_TYPE_P(klass, T_CLASS) || RB_TYPE_P(klass, T_MODULE) || RB_TYPE_P(klass, T_ICLASS));
428 RCLASS_EXT_WRITABLE(klass);
429}
430
432 rb_class_classext_foreach_callback_func *func;
433 void * callback_arg;
434};
435
436static int
437class_classext_foreach_i(st_data_t key, st_data_t value, st_data_t arg)
438{
440 rb_class_classext_foreach_callback_func *func = foreach_arg->func;
441 func((rb_classext_t *)value, false, (VALUE)key, foreach_arg->callback_arg);
442 return ST_CONTINUE;
443}
444
445void
446rb_class_classext_foreach(VALUE klass, rb_class_classext_foreach_callback_func *func, void *arg)
447{
448 st_table *tbl = RCLASS_CLASSEXT_TBL(klass);
450 if (tbl) {
451 foreach_arg.func = func;
452 foreach_arg.callback_arg = arg;
453 rb_st_foreach(tbl, class_classext_foreach_i, (st_data_t)&foreach_arg);
454 }
455 func(RCLASS_EXT_PRIME(klass), true, (VALUE)NULL, arg);
456}
457
458VALUE
460{
461 return RCLASS_SUPER(klass);
462}
463
464VALUE
465rb_class_singleton_p(VALUE klass)
466{
467 return RCLASS_SINGLETON_P(klass);
468}
469
470unsigned char
471rb_class_variation_count(VALUE klass)
472{
473 return RCLASS_VARIATION_COUNT(klass);
474}
475
476static void
477push_subclass_entry_to_list(VALUE super, VALUE klass)
478{
480 (RB_TYPE_P(super, T_MODULE) && RB_TYPE_P(klass, T_ICLASS)) ||
481 (RB_TYPE_P(super, T_CLASS) && RB_TYPE_P(klass, T_CLASS)) ||
482 (RB_TYPE_P(klass, T_ICLASS) && !NIL_P(RCLASS_REFINED_CLASS(klass)))
483 );
484
485 RB_VM_LOCKING() {
486 VALUE subs_v = RCLASS_SUBCLASSES(super);
487 struct rb_subclasses *subs = (struct rb_subclasses *)subs_v;
488
489 if (!subs || subs->count == subs->capacity) {
490 VALUE *old_entries = subs ? rb_imemo_subclasses_entries(subs_v) : NULL;
491 uint32_t live = 0;
492 for (uint32_t i = 0; subs && i < subs->count; i++) {
493 if (old_entries[i]) live++;
494 }
495
496 uint32_t cap = subs ? subs->capacity : 2;
497 if (live * 2 >= cap) cap *= 2;
498
499 VALUE new_v = rb_imemo_subclasses_new(cap);
500 struct rb_subclasses *new_subs = (struct rb_subclasses *)new_v;
501 VALUE *new_entries = rb_imemo_subclasses_entries(new_v);
502 for (uint32_t i = 0; subs && i < subs->count; i++) {
503 VALUE entry = old_entries[i];
504 if (entry) {
505 new_entries[new_subs->count++] = entry;
506 RB_OBJ_WRITTEN(new_v, Qundef, entry);
507 }
508 }
509 RCLASS_SET_SUBCLASSES(super, new_v);
510 subs_v = new_v;
511 subs = new_subs;
512 }
513
514 rb_imemo_subclasses_entries(subs_v)[subs->count++] = klass;
515 RB_OBJ_WRITTEN(subs_v, Qundef, klass);
516 }
517}
518
519void
520rb_class_subclass_add(VALUE super, VALUE klass)
521{
522 if (super && !UNDEF_P(super)) {
523 RUBY_ASSERT(RB_TYPE_P(super, T_CLASS) || RB_TYPE_P(super, T_MODULE));
524 RUBY_ASSERT(RB_TYPE_P(klass, T_CLASS) || RB_TYPE_P(klass, T_ICLASS));
525 push_subclass_entry_to_list(super, klass);
526 }
527}
528
529static void
530rb_module_add_to_subclasses_list(VALUE module, VALUE iclass)
531{
532 if (module && !UNDEF_P(module)) {
535 push_subclass_entry_to_list(module, iclass);
536 }
537}
538
539void
540rb_class_foreach_subclass(VALUE klass, void (*f)(VALUE, VALUE), VALUE arg)
541{
542 VALUE subs_v = RCLASS_SUBCLASSES(klass);
543 if (!subs_v) return;
544
545 struct rb_subclasses *subs = (struct rb_subclasses *)subs_v;
546 VALUE *entries = rb_imemo_subclasses_entries(subs_v);
547 for (uint32_t i = 0; i < subs->count; i++) {
548 VALUE curklass = entries[i];
549 if (curklass) {
550 f(curklass, arg);
551 }
552 }
553}
554
555static void
556class_switch_superclass(VALUE super, VALUE klass)
557{
558 // No need to remove from old super's subclasses list — the GC
559 // will nullify the weak reference when appropriate.
560 rb_class_subclass_add(super, klass);
561}
562
573static VALUE
574class_alloc0(enum ruby_value_type type, VALUE klass, bool boxable)
575{
576 const rb_box_t *box = rb_current_box();
577
578 if (!ruby_box_init_done) {
579 boxable = true;
580 }
581
582 size_t alloc_size = sizeof(struct RClass_and_rb_classext_t);
583 if (boxable) {
584 alloc_size = sizeof(struct RClass_boxable);
585 }
586
588
589 VALUE flags = type | FL_SHAREABLE;
590 if (boxable) flags |= RCLASS_BOXABLE;
591
592 shape_id_t shape_id = ROOT_SHAPE_ID;
593 if (boxable) {
594 shape_id |= SHAPE_ID_LAYOUT_OTHER;
595 }
596 else {
597 shape_id |= SHAPE_ID_LAYOUT_RCLASS;
598 }
599
600 struct RClass *obj = (struct RClass *)rb_newobj(GET_EC(), klass, flags, shape_id, true, alloc_size);
601
602 obj->object_id = 0;
603
604 memset(RCLASS_EXT_PRIME(obj), 0, sizeof(rb_classext_t));
605
606 // The creating Ractor owns the new class/module; an iclass has no owner.
607 // Singleton classes of classes/modules override this below.
608 if (type != T_ICLASS && UNLIKELY(!rb_ractor_main_p())) {
609 RCLASS_SET_OWNER_RACTOR_ID((VALUE)obj, rb_ractor_id(GET_RACTOR()));
610 }
611
612 /* ZALLOC
613 RCLASS_CONST_TBL(obj) = 0;
614 RCLASS_M_TBL(obj) = 0;
615 RCLASS_FIELDS(obj) = 0;
616 RCLASS_SET_SUPER((VALUE)obj, 0);
617 */
618
619 if (boxable) {
620 ((struct RClass_boxable *)obj)->box_classext_tbl = NULL;
621 }
622
623 RCLASS_PRIME_BOX((VALUE)obj) = box;
624 // Classes/Modules defined in user boxes are
625 // writable directly because it exists only in a box.
626 RCLASS_SET_PRIME_CLASSEXT_WRITABLE((VALUE)obj, !boxable || BOX_USER_P(box));
627
628 RCLASS_SET_ORIGIN((VALUE)obj, (VALUE)obj);
629 RCLASS_SET_REFINED_CLASS((VALUE)obj, Qnil);
630
631 return (VALUE)obj;
632}
633
634static VALUE
635class_alloc(enum ruby_value_type type, VALUE klass)
636{
637 bool boxable = rb_box_available() && BOX_MASTER_P(rb_current_box());
638 return class_alloc0(type, klass, boxable);
639}
640
641bool
642rb_class_owned_by_ractor_p(rb_serial_t owner_id)
643{
644 return owner_id == rb_ractor_id(GET_RACTOR());
645}
646
647/* A singleton class has no class path of its own, so name it by the object it
648 * belongs to, as rb_class_modify_check does for a frozen one. No dispatch: the
649 * object belongs to another Ractor. */
650static VALUE
651class_owner_name(VALUE klass)
652{
653 if (!RCLASS_SINGLETON_P(klass)) return rb_class_path(klass);
654
655 VALUE obj = RCLASS_ATTACHED_OBJECT(klass);
656 return (RB_TYPE_P(obj, T_CLASS) || RB_TYPE_P(obj, T_MODULE)) ? rb_class_path(obj) : rb_any_to_s(obj);
657}
658
659/* The eigenclass of klass, if it has one of its own, else 0. */
660static VALUE
661class_own_metaclass(VALUE klass)
662{
663 VALUE meta = METACLASS_OF(klass);
664 return (RCLASS_SINGLETON_P(meta) && RCLASS_ATTACHED_OBJECT(meta) == klass) ? meta : 0;
665}
666
667/* Only for a singleton class whose attached object has just changed hands through
668 * Ractor#send(move: true). Deliberately unreachable from Ruby. */
669void
670rb_class_take_ownership(VALUE klass)
671{
672 // keep class_alloc0's "0 means main" encoding
673 rb_serial_t id = rb_ractor_main_p() ? 0 : rb_ractor_id(GET_RACTOR());
674
675 // and up the eigenclass chain: each one belongs to the class below it
676 do {
677 RCLASS_SET_OWNER_RACTOR_ID(klass, id);
678 } while ((klass = class_own_metaclass(klass)) != 0);
679}
680
681void
682rb_class_owner_check(VALUE klass)
683{
684 if (UNLIKELY(!rb_class_owned_p(klass))) {
685 rb_raise(rb_eRactorIsolationError,
686 "can not modify %"PRIsVALUE" because it is created by another Ractor",
687 class_owner_name(klass));
688 }
689}
690
691static VALUE
692class_associate_super(VALUE klass, VALUE super, bool init)
693{
694 if (super && !UNDEF_P(super)) {
695 // Only maintain subclass lists for T_CLASS→T_CLASS relationships.
696 // Include/prepend inserts ICLASSes into the super chain, but T_CLASS
697 // subclass lists should track only the immutable T_CLASS→T_CLASS link.
698 if (RB_TYPE_P(klass, T_CLASS) && RB_TYPE_P(super, T_CLASS)) {
699 if (RCLASS_SINGLETON_P(klass)) {
700 // Instead of adding singleton classes to the subclass list,
701 // just set a flag so that method cache invalidation takes the
702 // tree path.
703 FL_SET_RAW(super, RCLASS_HAS_SUBCLASSES);
704 }
705 else {
706 class_switch_superclass(super, klass);
707 }
708 }
709 }
710 if (init) {
711 RCLASS_SET_SUPER(klass, super);
712 }
713 else {
714 RCLASS_WRITE_SUPER(klass, super);
715 }
716 rb_class_update_superclasses(klass);
717 return super;
718}
719
720VALUE
721rb_class_set_super(VALUE klass, VALUE super)
722{
723 return class_associate_super(klass, super, false);
724}
725
726static void
727class_initialize_method_table(VALUE c)
728{
729 // initialize the prime classext m_tbl
730 RCLASS_SET_M_TBL(c, rb_id_table_create(0));
731}
732
733static void
734class_clear_method_table(VALUE c)
735{
736 RCLASS_WRITE_M_TBL(c, rb_id_table_create(0));
737}
738
739static VALUE
740class_boot_boxable(VALUE super, bool boxable)
741{
742 VALUE klass = class_alloc0(T_CLASS, rb_cClass, boxable);
743
744 // initialize method table prior to class_associate_super()
745 // because class_associate_super() may cause GC and promote klass
746 class_initialize_method_table(klass);
747
748 class_associate_super(klass, super, true);
749 if (super && !UNDEF_P(super)) {
750 RCLASS_SET_ALLOCATOR(klass, RCLASS_ALLOCATOR(super));
751 rb_class_set_initialized(klass);
752 }
753
754 return (VALUE)klass;
755}
756
766VALUE
768{
769 return class_boot_boxable(super, false);
770}
771
772static VALUE *
773class_superclasses_including_self(VALUE klass)
774{
775 if (RCLASS_SUPERCLASSES_WITH_SELF_P(klass))
776 return RCLASS_SUPERCLASSES(klass);
777
778 size_t depth = RCLASS_SUPERCLASS_DEPTH(klass);
779 VALUE *superclasses = xmalloc(sizeof(VALUE) * (depth + 1));
780 if (depth > 0)
781 memcpy(superclasses, RCLASS_SUPERCLASSES(klass), sizeof(VALUE) * depth);
782 superclasses[depth] = klass;
783
784 return superclasses;
785}
786
787void
788rb_class_update_superclasses(VALUE klass)
789{
790 VALUE *superclasses;
791 size_t super_depth;
792 VALUE super = RCLASS_SUPER(klass);
793
794 if (!RB_TYPE_P(klass, T_CLASS)) return;
795 if (UNDEF_P(super)) return;
796
797 // If the superclass array is already built
798 if (RCLASS_SUPERCLASSES(klass))
799 return;
800
801 // find the proper superclass
802 while (super != Qfalse && !RB_TYPE_P(super, T_CLASS)) {
803 super = RCLASS_SUPER(super);
804 }
805
806 // For BasicObject and uninitialized classes, depth=0 and ary=NULL
807 if (super == Qfalse)
808 return;
809
810 // Sometimes superclasses are set before the full ancestry tree is built
811 // This happens during metaclass construction
812 if (super != rb_cBasicObject && !RCLASS_SUPERCLASS_DEPTH(super)) {
813 rb_class_update_superclasses(super);
814
815 // If it is still unset we need to try later
816 if (!RCLASS_SUPERCLASS_DEPTH(super))
817 return;
818 }
819
820 super_depth = RCLASS_SUPERCLASS_DEPTH(super);
821 if (RCLASS_SUPERCLASSES_WITH_SELF_P(super)) {
822 superclasses = RCLASS_SUPERCLASSES(super);
823 }
824 else {
825 superclasses = class_superclasses_including_self(super);
826 RCLASS_WRITE_SUPERCLASSES(super, super_depth, superclasses, true);
827 }
828
829 size_t depth = super_depth == RCLASS_MAX_SUPERCLASS_DEPTH ? super_depth : super_depth + 1;
830 RCLASS_WRITE_SUPERCLASSES(klass, depth, superclasses, false);
831}
832
833void
835{
836 if (!RB_TYPE_P(super, T_CLASS)) {
837 rb_raise(rb_eTypeError, "superclass must be an instance of Class (given an instance of %"PRIsVALUE")",
838 rb_obj_class(super));
839 }
840 if (RCLASS_SINGLETON_P(super)) {
841 rb_raise(rb_eTypeError, "can't make subclass of singleton class");
842 }
843 if (super == rb_cClass) {
844 rb_raise(rb_eTypeError, "can't make subclass of Class");
845 }
846}
847
848VALUE
850{
851 Check_Type(super, T_CLASS);
853 VALUE klass = rb_class_boot(super);
854
855 RCLASS_SET_MAX_IV_COUNT(klass, RCLASS_MAX_IV_COUNT(super));
856 RUBY_ASSERT(getenv("RUBY_BOX") || RCLASS_PRIME_CLASSEXT_WRITABLE_P(klass));
857
858 return klass;
859}
860
861VALUE
862rb_class_s_alloc(VALUE klass)
863{
864 return rb_class_boot(0);
865}
866
867static void
868clone_method(VALUE new_klass, ID mid, const rb_method_entry_t *me)
869{
870 rb_method_entry_set(new_klass, mid, me, METHOD_ENTRY_VISI(me));
871}
872
874 VALUE new_klass;
875};
876
877static enum rb_id_table_iterator_result
878clone_method_i(ID key, VALUE value, void *data)
879{
880 const struct clone_method_arg *arg = (struct clone_method_arg *)data;
881 clone_method(arg->new_klass, key, (const rb_method_entry_t *)value);
882 return ID_TABLE_CONTINUE;
883}
884
886 VALUE klass;
887 struct rb_id_table *tbl;
888};
889
890static int
891clone_const(ID key, const rb_const_entry_t *ce, struct clone_const_arg *arg)
892{
894 MEMCPY(nce, ce, rb_const_entry_t, 1);
895 RB_OBJ_WRITTEN(arg->klass, Qundef, ce->value);
896 RB_OBJ_WRITTEN(arg->klass, Qundef, ce->file);
897
898 rb_id_table_insert(arg->tbl, key, (VALUE)nce);
899 return ID_TABLE_CONTINUE;
900}
901
902static enum rb_id_table_iterator_result
903clone_const_i(ID key, VALUE value, void *data)
904{
905 return clone_const(key, (const rb_const_entry_t *)value, data);
906}
907
908static void
909class_init_copy_check(VALUE clone, VALUE orig)
910{
911 if (orig == rb_cBasicObject) {
912 rb_raise(rb_eTypeError, "can't copy the root class");
913 }
914 if (RCLASS_INITIALIZED_P(clone)) {
915 rb_raise(rb_eTypeError, "already initialized class");
916 }
917 if (RCLASS_SINGLETON_P(orig)) {
918 rb_raise(rb_eTypeError, "can't copy singleton class");
919 }
920}
921
923 VALUE clone;
924 VALUE new_table;
925};
926
927static struct rb_cvar_class_tbl_entry *
928cvc_table_entry_alloc(void)
929{
930 return (struct rb_cvar_class_tbl_entry *)SHAREABLE_IMEMO_NEW(struct rb_cvar_class_tbl_entry, imemo_cvar_entry, 0);
931}
932
933static enum rb_id_table_iterator_result
934cvc_table_copy(ID id, VALUE val, void *data)
935{
936 struct cvc_table_copy_ctx *ctx = (struct cvc_table_copy_ctx *)data;
937 struct rb_cvar_class_tbl_entry * orig_entry;
938 orig_entry = (struct rb_cvar_class_tbl_entry *)val;
939
940 struct rb_cvar_class_tbl_entry *ent;
941
942 ent = cvc_table_entry_alloc();
943 RB_OBJ_WRITE((VALUE)ent, &ent->class_value, ctx->clone);
944 RB_OBJ_WRITE(ctx->clone, &ent->cref, orig_entry->cref);
945 ent->global_cvar_state = orig_entry->global_cvar_state;
946 rb_marked_id_table_insert(ctx->new_table, id, (VALUE)ent);
947
948 return ID_TABLE_CONTINUE;
949}
950
951static void
952copy_tables(VALUE clone, VALUE orig)
953{
954 if (RCLASS_CONST_TBL(clone)) {
955 rb_free_const_table(RCLASS_CONST_TBL(clone));
956 RCLASS_WRITE_CONST_TBL(clone, 0, false);
957 }
958 if (RCLASS_CVC_TBL(orig)) {
959 VALUE rb_cvc_tbl = RCLASS_CVC_TBL(orig);
960 VALUE rb_cvc_tbl_dup = rb_marked_id_table_new(rb_marked_id_table_size(rb_cvc_tbl));
961
962 struct cvc_table_copy_ctx ctx;
963 ctx.clone = clone;
964 ctx.new_table = rb_cvc_tbl_dup;
965 rb_marked_id_table_foreach(rb_cvc_tbl, cvc_table_copy, &ctx);
966 RCLASS_WRITE_CVC_TBL(clone, rb_cvc_tbl_dup);
967 }
968 rb_id_table_free(RCLASS_M_TBL(clone));
969 RCLASS_WRITE_M_TBL(clone, 0);
970 if (!RB_TYPE_P(clone, T_ICLASS)) {
971 rb_fields_tbl_copy(clone, orig);
972 }
973 if (RCLASS_CONST_TBL(orig)) {
974 struct clone_const_arg arg;
975 struct rb_id_table *const_tbl;
976 struct rb_id_table *orig_tbl = RCLASS_CONST_TBL(orig);
977 arg.tbl = const_tbl = rb_id_table_create(rb_id_table_size(orig_tbl));
978 arg.klass = clone;
979 rb_id_table_foreach(orig_tbl, clone_const_i, &arg);
980 RCLASS_WRITE_CONST_TBL(clone, const_tbl, false);
981 rb_gc_writebarrier_remember(clone);
982 }
983}
984
985static bool ensure_origin(VALUE klass);
986
987void
988rb_class_set_initialized(VALUE klass)
989{
990 RUBY_ASSERT(RB_TYPE_P(klass, T_CLASS) || RB_TYPE_P(klass, T_MODULE));
991 FL_SET_RAW(klass, RCLASS_IS_INITIALIZED);
992 /* no more re-initialization */
993}
994
995void
996rb_module_check_initializable(VALUE mod)
997{
998 if (RCLASS_INITIALIZED_P(mod)) {
999 rb_raise(rb_eTypeError, "already initialized module");
1000 }
1001}
1002
1003static enum rb_id_table_iterator_result
1004init_copy_check_const_i(ID id, VALUE v, void *data)
1005{
1006 const rb_const_entry_t *ce = (const rb_const_entry_t *)v;
1007 if (!UNDEF_P(ce->value) && !rb_ractor_shareable_p(ce->value)) {
1008 rb_raise(rb_eRactorIsolationError,
1009 "can not copy a class/module created by another Ractor because "
1010 "constant %"PRIsVALUE" refers to an unshareable object", rb_id2str(id));
1011 }
1012 return ID_TABLE_CONTINUE;
1013}
1014
1015static int
1016init_copy_check_field_i(ID id, VALUE val, st_data_t arg)
1017{
1018 if ((rb_is_instance_id(id) || rb_is_class_id(id)) && !rb_ractor_shareable_p(val)) {
1019 rb_raise(rb_eRactorIsolationError,
1020 "can not copy a class/module created by another Ractor because "
1021 "variable %"PRIsVALUE" refers to an unshareable object", rb_id2str(id));
1022 }
1023 return ST_CONTINUE;
1024}
1025
1026// The copy belongs to the copying Ractor, so it must not carry over unshareable
1027// objects owned by the source's Ractor.
1028static enum rb_id_table_iterator_result
1029move_check_const_i(ID id, VALUE v, void *data)
1030{
1031 const rb_const_entry_t *ce = (const rb_const_entry_t *)v;
1032 if (!UNDEF_P(ce->value) && !rb_ractor_shareable_p(ce->value)) {
1033 rb_raise(rb_eRactorIsolationError,
1034 "can not move an object whose singleton class has constant %"PRIsVALUE
1035 " referring to an unshareable object", rb_id2str(id));
1036 }
1037 return ID_TABLE_CONTINUE;
1038}
1039
1040static int
1041move_check_field_i(ID id, VALUE val, st_data_t arg)
1042{
1043 if ((rb_is_instance_id(id) || rb_is_class_id(id)) && !rb_ractor_shareable_p(val)) {
1044 rb_raise(rb_eRactorIsolationError,
1045 "can not move an object whose singleton class has variable %"PRIsVALUE
1046 " referring to an unshareable object", rb_id2str(id));
1047 }
1048 return ST_CONTINUE;
1049}
1050
1051/* The receiver of a moved object becomes the owner of its singleton class
1052 * (rb_class_take_ownership), so nothing the sender keeps may stay readable there. */
1053void
1054rb_class_check_singleton_movable(VALUE klass)
1055{
1056 do {
1057 if (RCLASS_CONST_TBL(klass)) {
1058 rb_id_table_foreach(RCLASS_CONST_TBL(klass), move_check_const_i, NULL);
1059 }
1060 rb_ivar_foreach_buffered(klass, move_check_field_i, 0);
1061 } while ((klass = class_own_metaclass(klass)) != 0);
1062}
1063
1064static void
1065init_copy_check_tables(VALUE klass)
1066{
1067 if (RCLASS_CONST_TBL(klass)) {
1068 rb_id_table_foreach(RCLASS_CONST_TBL(klass), init_copy_check_const_i, NULL);
1069 }
1070 rb_ivar_foreach_buffered(klass, init_copy_check_field_i, 0);
1071}
1072
1073static void
1074init_copy_owner_check(VALUE orig)
1075{
1076 if (!rb_class_owned_p(orig)) {
1077 init_copy_check_tables(orig);
1078
1079 // rb_singleton_class_clone_and_attach copies the metaclass's tables too
1080 VALUE meta = METACLASS_OF(orig);
1081 if (RCLASS_SINGLETON_P(meta)) {
1082 init_copy_check_tables(meta);
1083 }
1084 }
1085}
1086
1087/* :nodoc: */
1088VALUE
1090{
1091 /* Only class or module is valid here, but other classes may enter here and
1092 * only hit an exception on the OBJ_INIT_COPY checks
1093 */
1094 switch (BUILTIN_TYPE(clone)) {
1095 case T_CLASS:
1096 class_init_copy_check(clone, orig);
1097 break;
1098 case T_MODULE:
1099 rb_module_check_initializable(clone);
1100 break;
1101 default:
1102 break;
1103 }
1104 if (!OBJ_INIT_COPY(clone, orig)) return clone;
1105
1107 RUBY_ASSERT(BUILTIN_TYPE(clone) == BUILTIN_TYPE(orig));
1108
1109 init_copy_owner_check(orig);
1110
1111 rb_class_set_initialized(clone);
1112
1113 if (!RCLASS_SINGLETON_P(CLASS_OF(clone))) {
1114 RBASIC_SET_CLASS(clone, rb_singleton_class_clone(orig));
1115 rb_singleton_class_attached(METACLASS_OF(clone), (VALUE)clone);
1116 }
1117 if (BUILTIN_TYPE(clone) == T_CLASS) {
1118 RCLASS_SET_ALLOCATOR(clone, RCLASS_ALLOCATOR(orig));
1119 }
1120 copy_tables(clone, orig);
1121 if (RCLASS_M_TBL(orig)) {
1122 struct clone_method_arg arg;
1123 arg.new_klass = clone;
1124 class_initialize_method_table(clone);
1125 rb_id_table_foreach(RCLASS_M_TBL(orig), clone_method_i, &arg);
1126 }
1127
1128 if (RCLASS_ORIGIN(orig) == orig) {
1129 rb_class_set_super(clone, RCLASS_SUPER(orig));
1130 }
1131 else {
1132 VALUE p = RCLASS_SUPER(orig);
1133 VALUE orig_origin = RCLASS_ORIGIN(orig);
1134 VALUE prev_clone_p = clone;
1135 VALUE origin_stack = rb_ary_hidden_new(2);
1136 VALUE origin[2];
1137 VALUE clone_p = 0;
1138 long origin_len;
1139 int add_subclass;
1140 VALUE clone_origin;
1141
1142 ensure_origin(clone);
1143 clone_origin = RCLASS_ORIGIN(clone);
1144
1145 while (p && p != orig_origin) {
1146 if (BUILTIN_TYPE(p) != T_ICLASS) {
1147 rb_bug("non iclass between module/class and origin");
1148 }
1149 clone_p = class_alloc(T_ICLASS, METACLASS_OF(p));
1150 RCLASS_SET_M_TBL(clone_p, RCLASS_M_TBL(p));
1151 rb_class_set_super(prev_clone_p, clone_p);
1152 prev_clone_p = clone_p;
1153 RCLASS_SET_CONST_TBL(clone_p, RCLASS_CONST_TBL(p), false);
1154 RCLASS_SET_INCLUDER(clone_p, clone);
1155 add_subclass = TRUE;
1156 if (p != RCLASS_ORIGIN(p)) {
1157 origin[0] = clone_p;
1158 origin[1] = RCLASS_ORIGIN(p);
1159 rb_ary_cat(origin_stack, origin, 2);
1160 }
1161 else if ((origin_len = RARRAY_LEN(origin_stack)) > 1 &&
1162 RARRAY_AREF(origin_stack, origin_len - 1) == p) {
1163 RCLASS_WRITE_ORIGIN(RARRAY_AREF(origin_stack, (origin_len -= 2)), clone_p);
1164 RICLASS_WRITE_ORIGIN_SHARED_MTBL(clone_p);
1165 rb_ary_resize(origin_stack, origin_len);
1166 add_subclass = FALSE;
1167 }
1168 if (add_subclass) {
1169 rb_module_add_to_subclasses_list(METACLASS_OF(p), clone_p);
1170 }
1171 p = RCLASS_SUPER(p);
1172 }
1173
1174 if (p == orig_origin) {
1175 if (clone_p) {
1176 rb_class_set_super(clone_p, clone_origin);
1177 rb_class_set_super(clone_origin, RCLASS_SUPER(orig_origin));
1178 }
1179 copy_tables(clone_origin, orig_origin);
1180 if (RCLASS_M_TBL(orig_origin)) {
1181 struct clone_method_arg arg;
1182 arg.new_klass = clone;
1183 class_initialize_method_table(clone_origin);
1184 rb_id_table_foreach(RCLASS_M_TBL(orig_origin), clone_method_i, &arg);
1185 }
1186 }
1187 else {
1188 rb_bug("no origin for class that has origin");
1189 }
1190
1191 rb_class_update_superclasses(clone);
1192 }
1193
1194 if (RB_TYPE_P(clone, T_CLASS)) {
1195 VALUE super = RCLASS_SUPER(clone);
1196 if (super && RB_TYPE_P(super, T_ICLASS)) {
1197 class_switch_superclass(rb_class_superclass(clone), clone);
1198 }
1199 }
1200
1201 return clone;
1202}
1203
1204VALUE
1206{
1207 return rb_singleton_class_clone_and_attach(obj, Qundef);
1208}
1209
1210// Clone and return the singleton class of `obj` if it has been created and is attached to `obj`.
1211VALUE
1212rb_singleton_class_clone_and_attach(VALUE obj, VALUE attach)
1213{
1214 const VALUE klass = METACLASS_OF(obj);
1215
1216 // Note that `rb_singleton_class()` can create situations where `klass` is
1217 // attached to an object other than `obj`. In which case `obj` does not have
1218 // a material singleton class attached yet and there is no singleton class
1219 // to clone.
1220 if (!(RCLASS_SINGLETON_P(klass) && RCLASS_ATTACHED_OBJECT(klass) == obj)) {
1221 // nothing to clone
1222 return klass;
1223 }
1224 else {
1225 /* copy singleton(unnamed) class */
1226 bool klass_of_clone_is_new;
1227 RUBY_ASSERT(RB_TYPE_P(klass, T_CLASS));
1228 VALUE clone = class_alloc(T_CLASS, 0);
1229
1230 if (BUILTIN_TYPE(obj) == T_CLASS) {
1231 klass_of_clone_is_new = true;
1232 RBASIC_SET_CLASS(clone, clone);
1233 }
1234 else {
1235 VALUE klass_metaclass_clone = rb_singleton_class_clone(klass);
1236 // When `METACLASS_OF(klass) == klass_metaclass_clone`, it means the
1237 // recursive call did not clone `METACLASS_OF(klass)`.
1238 klass_of_clone_is_new = (METACLASS_OF(klass) != klass_metaclass_clone);
1239 RBASIC_SET_CLASS(clone, klass_metaclass_clone);
1240 }
1241
1242 // initialize method table before any GC chance
1243 class_initialize_method_table(clone);
1244
1245 rb_class_set_super(clone, RCLASS_SUPER(klass));
1246 rb_fields_tbl_copy(clone, klass);
1247 if (RCLASS_CONST_TBL(klass)) {
1248 struct clone_const_arg arg;
1249 struct rb_id_table *table;
1250 arg.tbl = table = rb_id_table_create(rb_id_table_size(RCLASS_CONST_TBL(klass)));
1251 arg.klass = clone;
1252 rb_id_table_foreach(RCLASS_CONST_TBL(klass), clone_const_i, &arg);
1253 RCLASS_SET_CONST_TBL(clone, table, false);
1254 }
1255 if (!UNDEF_P(attach)) {
1256 rb_singleton_class_attached(clone, attach);
1257 }
1258 {
1259 struct clone_method_arg arg;
1260 arg.new_klass = clone;
1261 rb_id_table_foreach(RCLASS_M_TBL(klass), clone_method_i, &arg);
1262 }
1263 if (klass_of_clone_is_new) {
1264 rb_singleton_class_attached(METACLASS_OF(clone), clone);
1265 }
1266 FL_SET(clone, FL_SINGLETON);
1267
1268 return clone;
1269 }
1270}
1271
1272void
1274{
1275 if (RCLASS_SINGLETON_P(klass)) {
1276 RCLASS_SET_ATTACHED_OBJECT(klass, obj);
1277 }
1278}
1279
1285#define META_CLASS_OF_CLASS_CLASS_P(k) (METACLASS_OF(k) == (k))
1286
1287static int
1288rb_singleton_class_has_metaclass_p(VALUE sklass)
1289{
1290 return RCLASS_ATTACHED_OBJECT(METACLASS_OF(sklass)) == sklass;
1291}
1292
1293int
1294rb_singleton_class_internal_p(VALUE sklass)
1295{
1296 return (RB_TYPE_P(RCLASS_ATTACHED_OBJECT(sklass), T_CLASS) &&
1297 !rb_singleton_class_has_metaclass_p(sklass));
1298}
1299
1305#define HAVE_METACLASS_P(k) \
1306 (FL_TEST(METACLASS_OF(k), FL_SINGLETON) && \
1307 rb_singleton_class_has_metaclass_p(k))
1308
1316#define ENSURE_EIGENCLASS(klass) \
1317 (HAVE_METACLASS_P(klass) ? METACLASS_OF(klass) : make_metaclass(klass))
1318
1319
1329static inline VALUE
1331{
1332 VALUE super;
1333 VALUE metaclass = class_boot_boxable(Qundef, FL_TEST_RAW(klass, RCLASS_BOXABLE));
1334
1335 FL_SET(metaclass, FL_SINGLETON);
1336 // owned by the attached class's owner, not by whoever triggered the lazy creation
1337 RCLASS_SET_OWNER_RACTOR_ID(metaclass, RCLASS_OWNER_RACTOR_ID(klass));
1338 rb_singleton_class_attached(metaclass, klass);
1339
1340 if (META_CLASS_OF_CLASS_CLASS_P(klass)) {
1341 SET_METACLASS_OF(klass, metaclass);
1342 SET_METACLASS_OF(metaclass, metaclass);
1343 }
1344 else {
1345 VALUE tmp = METACLASS_OF(klass); /* for a meta^(n)-class klass, tmp is meta^(n)-class of Class class */
1346 SET_METACLASS_OF(klass, metaclass);
1347 SET_METACLASS_OF(metaclass, ENSURE_EIGENCLASS(tmp));
1348 }
1349
1350 super = RCLASS_SUPER(klass);
1351 while (RB_TYPE_P(super, T_ICLASS)) super = RCLASS_SUPER(super);
1352 class_associate_super(metaclass, super ? ENSURE_EIGENCLASS(super) : rb_cClass, true);
1353 rb_class_set_initialized(klass);
1354
1355 // Full class ancestry may not have been filled until we reach here.
1356 rb_class_update_superclasses(METACLASS_OF(metaclass));
1357
1358 return metaclass;
1359}
1360
1367static inline VALUE
1369{
1370 VALUE orig_class = METACLASS_OF(obj);
1371 VALUE klass = class_alloc0(T_CLASS, rb_cClass, FL_TEST_RAW(orig_class, RCLASS_BOXABLE));
1372 FL_SET(klass, FL_SINGLETON);
1373 if (RB_TYPE_P(obj, T_MODULE)) {
1374 // as in make_metaclass: the module's owner, not the lazy creator
1375 RCLASS_SET_OWNER_RACTOR_ID(klass, RCLASS_OWNER_RACTOR_ID(obj));
1376 }
1377 else if (rb_ractor_shareable_p(obj)) {
1378 // A shareable object is no single Ractor's, so its singleton class stays the
1379 // main Ractor's rather than being claimed by whoever materialized it.
1380 RCLASS_SET_OWNER_RACTOR_ID(klass, 0);
1381 }
1382 class_initialize_method_table(klass);
1383 class_associate_super(klass, orig_class, true);
1384 if (orig_class && !UNDEF_P(orig_class)) {
1385 rb_class_set_initialized(klass);
1386 }
1387
1388 RBASIC_SET_CLASS(obj, klass);
1389 rb_singleton_class_attached(klass, obj);
1390 rb_yjit_invalidate_no_singleton_class(orig_class);
1391 rb_zjit_invalidate_no_singleton_class(orig_class);
1392
1393 SET_METACLASS_OF(klass, METACLASS_OF(rb_class_real(orig_class)));
1394 return klass;
1395}
1396
1397
1398static VALUE
1399boot_defclass(const char *name, VALUE super)
1400{
1401 VALUE obj = rb_class_boot(super);
1402 ID id = rb_intern(name);
1403
1404 rb_const_set((rb_cObject ? rb_cObject : obj), id, obj);
1405 rb_vm_register_global_object(obj);
1406 return obj;
1407}
1408
1409/***********************************************************************
1410 *
1411 * Document-class: Refinement
1412 *
1413 * Refinement is a class of the +self+ (current context) inside +refine+
1414 * statement. It allows to import methods from other modules, see #import_methods.
1415 */
1416
1417#if 0 /* for RDoc */
1418/*
1419 * Document-method: Refinement#import_methods
1420 *
1421 * call-seq:
1422 * import_methods(module, ...) -> self
1423 *
1424 * Imports methods from modules. Unlike Module#include,
1425 * Refinement#import_methods copies methods and adds them into the refinement,
1426 * so the refinement is activated in the imported methods.
1427 *
1428 * Note that due to method copying, only methods defined in Ruby code can be imported.
1429 *
1430 * module StrUtils
1431 * def indent(level)
1432 * ' ' * level + self
1433 * end
1434 * end
1435 *
1436 * module M
1437 * refine String do
1438 * import_methods StrUtils
1439 * end
1440 * end
1441 *
1442 * using M
1443 * "foo".indent(3)
1444 * #=> " foo"
1445 *
1446 * module M
1447 * refine String do
1448 * import_methods Enumerable
1449 * # Can't import method which is not defined with Ruby code: Enumerable#drop
1450 * end
1451 * end
1452 *
1453 */
1454
1455static VALUE
1456refinement_import_methods(int argc, VALUE *argv, VALUE refinement)
1457{
1458}
1459# endif
1460
1480void
1481Init_class_hierarchy(void)
1482{
1483 rb_cBasicObject = boot_defclass("BasicObject", 0);
1484 RCLASS_SET_ALLOCATOR(rb_cBasicObject, rb_class_allocate_instance);
1485 FL_SET_RAW(rb_cBasicObject, RCLASS_ALLOCATOR_DEFINED);
1486 RCLASS_SET_EXPECT_NO_IVAR(rb_cBasicObject);
1487
1488 rb_cObject = boot_defclass("Object", rb_cBasicObject);
1489 RCLASS_SET_EXPECT_NO_IVAR(rb_cObject);
1490
1491 /* resolve class name ASAP for order-independence */
1492 rb_set_class_path_string(rb_cObject, rb_cObject, rb_fstring_lit("Object"));
1493
1494 rb_cModule = boot_defclass("Module", rb_cObject);
1495 rb_cClass = boot_defclass("Class", rb_cModule);
1496 rb_cRefinement = boot_defclass("Refinement", rb_cModule);
1497
1498#if 0 /* for RDoc */
1499 // we pretend it to be public, otherwise RDoc will ignore it
1500 rb_define_method(rb_cRefinement, "import_methods", refinement_import_methods, -1);
1501#endif
1502
1504 RBASIC_SET_CLASS(rb_cClass, rb_cClass);
1505 RBASIC_SET_CLASS(rb_cModule, rb_cClass);
1506 RBASIC_SET_CLASS(rb_cObject, rb_cClass);
1507 RBASIC_SET_CLASS(rb_cRefinement, rb_cClass);
1508 RBASIC_SET_CLASS(rb_cBasicObject, rb_cClass);
1509
1511}
1512
1513
1524VALUE
1525rb_make_metaclass(VALUE obj, VALUE unused)
1526{
1527 if (BUILTIN_TYPE(obj) == T_CLASS) {
1528 return make_metaclass(obj);
1529 }
1530 else {
1531 return make_singleton_class(obj);
1532 }
1533}
1534
1535VALUE
1537{
1538 VALUE klass;
1539
1540 if (!super) super = rb_cObject;
1541 klass = rb_class_new(super);
1542 rb_make_metaclass(klass, METACLASS_OF(super));
1543
1544 return klass;
1545}
1546
1547
1556VALUE
1558{
1559 ID inherited;
1560 if (!super) super = rb_cObject;
1561 CONST_ID(inherited, "inherited");
1562 return rb_funcallv_uncached(super, inherited, 1, &klass);
1563}
1564
1565#ifdef rb_define_class
1566#undef rb_define_class
1567#endif
1568VALUE
1569rb_define_class(const char *name, VALUE super)
1570{
1571 return rb_define_class_under(rb_cObject, name, super);
1572}
1573
1574#ifdef rb_define_class_under
1575#undef rb_define_class_under
1576#endif
1577VALUE
1578rb_define_class_under(VALUE outer, const char *name, VALUE super)
1579{
1580 return rb_define_class_id_under(outer, rb_intern(name), super);
1581}
1582
1583VALUE
1584rb_define_class_id_under_no_pin(VALUE outer, ID id, VALUE super)
1585{
1586 VALUE klass;
1587
1588 if (rb_const_defined_at(outer, id)) {
1589 klass = rb_const_get_at(outer, id);
1590 if (!RB_TYPE_P(klass, T_CLASS)) {
1591 if (outer == rb_cObject) {
1592 rb_raise(rb_eTypeError, "%s is not a class (%"PRIsVALUE")",
1593 rb_id2name(id), rb_obj_class(klass));
1594 }
1595 else {
1596 rb_raise(rb_eTypeError, "%"PRIsVALUE"::%"PRIsVALUE" is not a class"
1597 " (%"PRIsVALUE")",
1598 outer, rb_id2str(id), rb_obj_class(klass));
1599 }
1600 }
1601 if (rb_class_real(RCLASS_SUPER(klass)) != super) {
1602 if (outer == rb_cObject) {
1603 rb_raise(rb_eTypeError, "superclass mismatch for class %s", rb_id2name(id));
1604 }
1605 else {
1606 rb_raise(rb_eTypeError, "superclass mismatch for class "
1607 "%"PRIsVALUE"::%"PRIsVALUE""
1608 " (%"PRIsVALUE" is given but was %"PRIsVALUE")",
1609 outer, rb_id2str(id), RCLASS_SUPER(klass), super);
1610 }
1611 }
1612
1613 return klass;
1614 }
1615 if (!super) {
1616 if (outer == rb_cObject) {
1617 rb_raise(rb_eArgError, "no super class for '%"PRIsVALUE"'", rb_id2str(id));
1618 }
1619 else {
1620 rb_raise(rb_eArgError, "no super class for '%"PRIsVALUE"::%"PRIsVALUE"'",
1621 rb_class_path(outer), rb_id2str(id));
1622 }
1623 }
1624 klass = rb_define_class_id(id, super);
1625 rb_set_class_path_string(klass, outer, rb_id2str(id));
1626 rb_const_set(outer, id, klass);
1627 rb_class_inherited(super, klass);
1628
1629 return klass;
1630}
1631
1632VALUE
1634{
1635 VALUE klass = rb_define_class_id_under_no_pin(outer, id, super);
1636 rb_vm_register_global_object(klass);
1637 return klass;
1638}
1639
1640VALUE
1641rb_module_s_alloc(VALUE klass)
1642{
1643 VALUE mod = class_alloc(T_MODULE, klass);
1644 class_initialize_method_table(mod);
1645 return mod;
1646}
1647
1648static inline VALUE
1649module_new(VALUE klass)
1650{
1651 VALUE mdl = class_alloc(T_MODULE, klass);
1652 class_initialize_method_table(mdl);
1653 return (VALUE)mdl;
1654}
1655
1656VALUE
1658{
1659 return module_new(rb_cModule);
1660}
1661
1662VALUE
1664{
1665 return module_new(rb_cRefinement);
1666}
1667
1668// Kept for compatibility. Use rb_module_new() instead.
1669VALUE
1671{
1672 return rb_module_new();
1673}
1674
1675#ifdef rb_define_module
1676#undef rb_define_module
1677#endif
1678VALUE
1679rb_define_module(const char *name)
1680{
1681 return rb_define_module_id_under(rb_cObject, rb_intern(name));
1682}
1683
1684#ifdef rb_define_module_under
1685#undef rb_define_module_under
1686#endif
1687VALUE
1688rb_define_module_under(VALUE outer, const char *name)
1689{
1690 return rb_define_module_id_under(outer, rb_intern(name));
1691}
1692
1693VALUE
1695{
1696 VALUE module;
1697
1698 if (rb_const_defined_at(outer, id)) {
1699 module = rb_const_get_at(outer, id);
1700 if (!RB_TYPE_P(module, T_MODULE)) {
1701 if (outer == rb_cObject) {
1702 rb_raise(rb_eTypeError, "%s is not a module (%"PRIsVALUE")",
1703 rb_id2name(id), rb_obj_class(module));
1704 }
1705 else {
1706 rb_raise(rb_eTypeError, "%"PRIsVALUE"::%"PRIsVALUE" is not a module"
1707 " (%"PRIsVALUE")",
1708 outer, rb_id2str(id), rb_obj_class(module));
1709 }
1710 }
1711 /* Module may have been defined in Ruby and not pin-rooted */
1712 rb_vm_register_global_object(module);
1713 return module;
1714 }
1715 module = rb_module_new();
1716 rb_const_set(outer, id, module);
1717 rb_set_class_path_string(module, outer, rb_id2str(id));
1718 rb_vm_register_global_object(module);
1719
1720 return module;
1721}
1722
1723VALUE
1724rb_include_class_new(VALUE module, VALUE super)
1725{
1726 VALUE klass = class_alloc(T_ICLASS, rb_cClass);
1727
1728 RCLASS_SET_M_TBL(klass, RCLASS_WRITABLE_M_TBL(module));
1729
1730 RCLASS_SET_ORIGIN(klass, klass);
1731 if (BUILTIN_TYPE(module) == T_ICLASS) {
1732 module = METACLASS_OF(module);
1733 }
1734 RUBY_ASSERT(!RB_TYPE_P(module, T_ICLASS));
1735 if (RCLASS_WRITABLE_CONST_TBL(module)) {
1736 RCLASS_SET_CONST_TBL(klass, RCLASS_WRITABLE_CONST_TBL(module), true);
1737 }
1738 else {
1739 RCLASS_WRITE_CONST_TBL(module, rb_id_table_create(0), false);
1740 RCLASS_SET_CONST_TBL(klass, RCLASS_WRITABLE_CONST_TBL(module), true);
1741 }
1742
1743 RCLASS_SET_CVC_TBL(klass, RCLASS_WRITABLE_CVC_TBL(module));
1744
1745 class_associate_super(klass, super, true);
1746 RBASIC_SET_CLASS(klass, module);
1747
1748 return (VALUE)klass;
1749}
1750
1751static int include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super);
1752
1753static void
1754ensure_includable(VALUE klass, VALUE module)
1755{
1756 rb_class_modify_check(klass);
1757 Check_Type(module, T_MODULE);
1758 rb_class_set_initialized(module);
1759 if (!NIL_P(rb_refinement_module_get_refined_class(module))) {
1760 rb_raise(rb_eArgError, "refinement module is not allowed");
1761 }
1762}
1763
1764void
1766{
1767 int changed = 0;
1768
1769 ensure_includable(klass, module);
1770
1771 changed = include_modules_at(klass, RCLASS_ORIGIN(klass), module, TRUE);
1772 if (changed < 0)
1773 rb_raise(rb_eArgError, "cyclic include detected");
1774
1775 if (RB_TYPE_P(klass, T_MODULE)) {
1776 VALUE subs_v = RCLASS_SUBCLASSES(klass);
1777 if (subs_v) {
1778 struct rb_subclasses *subs = (struct rb_subclasses *)subs_v;
1779 VALUE *entries = rb_imemo_subclasses_entries(subs_v);
1780 for (uint32_t i = 0; i < subs->count; i++) {
1781 VALUE check_class = entries[i];
1782 if (!check_class) continue;
1783
1784 int do_include = 1;
1785 /* During lazy sweeping, the entry could be a dead object that
1786 * has not yet been swept. */
1787 if (!rb_objspace_garbage_object_p(check_class)) {
1788 VALUE walk = check_class;
1789 while (walk) {
1790 RUBY_ASSERT(!rb_objspace_garbage_object_p(walk));
1791
1792 if (RB_TYPE_P(walk, T_ICLASS) &&
1793 (METACLASS_OF(walk) == module)) {
1794 do_include = 0;
1795 }
1796 walk = RCLASS_SUPER(walk);
1797 }
1798
1799 if (do_include) {
1800 include_modules_at(check_class, RCLASS_ORIGIN(check_class), module, TRUE);
1801 }
1802 }
1803 }
1804 }
1805 }
1806}
1807
1808static enum rb_id_table_iterator_result
1809add_refined_method_entry_i(ID key, VALUE value, void *data)
1810{
1811 rb_add_refined_method_entry((VALUE)data, key);
1812 return ID_TABLE_CONTINUE;
1813}
1814
1815static enum rb_id_table_iterator_result
1816clear_module_cache_i(ID id, VALUE val, void *data)
1817{
1818 VALUE klass = (VALUE)data;
1819 rb_clear_method_cache(klass, id);
1820 return ID_TABLE_CONTINUE;
1821}
1822
1823static bool
1824module_in_super_chain(const VALUE klass, VALUE module)
1825{
1826 struct rb_id_table *const klass_m_tbl = RCLASS_M_TBL(RCLASS_ORIGIN(klass));
1827 if (klass_m_tbl) {
1828 while (module) {
1829 if (klass_m_tbl == RCLASS_M_TBL(module))
1830 return true;
1831 module = RCLASS_SUPER(module);
1832 }
1833 }
1834 return false;
1835}
1836
1837// For each ID key in the class constant table, we're going to clear the VM's
1838// inline constant caches associated with it.
1839static enum rb_id_table_iterator_result
1840clear_constant_cache_i(ID id, VALUE value, void *data)
1841{
1843 return ID_TABLE_CONTINUE;
1844}
1845
1846static int
1847do_include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super, bool check_cyclic)
1848{
1849 VALUE p, iclass, origin_stack = 0;
1850 int method_changed = 0;
1851 long origin_len;
1852 VALUE klass_origin = RCLASS_ORIGIN(klass);
1853 VALUE original_klass = klass;
1854
1855 if (check_cyclic && module_in_super_chain(klass, module))
1856 return -1;
1857
1858 while (module) {
1859 int c_seen = FALSE;
1860 int superclass_seen = FALSE;
1861 struct rb_id_table *tbl;
1862
1863 if (klass == c) {
1864 c_seen = TRUE;
1865 }
1866 if (klass_origin != c || search_super) {
1867 /* ignore if the module included already in superclasses for include,
1868 * ignore if the module included before origin class for prepend
1869 */
1870 for (p = RCLASS_SUPER(klass); p; p = RCLASS_SUPER(p)) {
1871 int type = BUILTIN_TYPE(p);
1872 if (klass_origin == p && !search_super)
1873 break;
1874 if (c == p)
1875 c_seen = TRUE;
1876 if (type == T_ICLASS) {
1877 if (RCLASS_M_TBL(p) == RCLASS_M_TBL(module)) {
1878 if (!superclass_seen && c_seen) {
1879 c = p; /* move insertion point */
1880 }
1881 goto skip;
1882 }
1883 }
1884 else if (type == T_CLASS) {
1885 superclass_seen = TRUE;
1886 }
1887 }
1888 }
1889
1890 VALUE super_class = RCLASS_SUPER(c);
1891
1892 // invalidate inline method cache
1893 RB_DEBUG_COUNTER_INC(cvar_include_invalidate);
1894 ruby_vm_global_cvar_state++;
1895 tbl = RCLASS_M_TBL(module);
1896 if (tbl && rb_id_table_size(tbl)) {
1897 if (search_super) { // include
1898 if (super_class && !RB_TYPE_P(super_class, T_MODULE)) {
1899 rb_id_table_foreach(tbl, clear_module_cache_i, (void *)super_class);
1900 }
1901 }
1902 else { // prepend
1903 if (!RB_TYPE_P(original_klass, T_MODULE)) {
1904 rb_id_table_foreach(tbl, clear_module_cache_i, (void *)original_klass);
1905 }
1906 }
1907 method_changed = 1;
1908 }
1909
1910 // setup T_ICLASS for the include/prepend module
1911 iclass = rb_include_class_new(module, super_class);
1912 c = rb_class_set_super(c, iclass);
1913 RCLASS_SET_INCLUDER(iclass, klass);
1914 if (module != RCLASS_ORIGIN(module)) {
1915 if (!origin_stack) origin_stack = rb_ary_hidden_new(2);
1916 VALUE origin[2] = {iclass, RCLASS_ORIGIN(module)};
1917 rb_ary_cat(origin_stack, origin, 2);
1918 }
1919 else if (origin_stack && (origin_len = RARRAY_LEN(origin_stack)) > 1 &&
1920 RARRAY_AREF(origin_stack, origin_len - 1) == module) {
1921 RCLASS_WRITE_ORIGIN(RARRAY_AREF(origin_stack, (origin_len -= 2)), iclass);
1922 RICLASS_WRITE_ORIGIN_SHARED_MTBL(iclass);
1923 rb_ary_resize(origin_stack, origin_len);
1924 }
1925
1926 VALUE m = module;
1927 if (BUILTIN_TYPE(m) == T_ICLASS) m = METACLASS_OF(m);
1928 rb_module_add_to_subclasses_list(m, iclass);
1929
1930 if (BUILTIN_TYPE(klass) == T_MODULE && FL_TEST(klass, RMODULE_IS_REFINEMENT)) {
1931 VALUE refined_class =
1932 rb_refinement_module_get_refined_class(klass);
1933
1934 rb_id_table_foreach(RCLASS_M_TBL(module), add_refined_method_entry_i, (void *)refined_class);
1936 }
1937
1938 tbl = RCLASS_CONST_TBL(module);
1939 if (tbl && rb_id_table_size(tbl))
1940 rb_id_table_foreach(tbl, clear_constant_cache_i, NULL);
1941 skip:
1942 module = RCLASS_SUPER(module);
1943 }
1944
1945 return method_changed;
1946}
1947
1948static int
1949include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super)
1950{
1951 return do_include_modules_at(klass, c, module, search_super, true);
1952}
1953
1954static enum rb_id_table_iterator_result
1955move_refined_method(ID key, VALUE value, void *data)
1956{
1957 rb_method_entry_t *me = (rb_method_entry_t *)value;
1958
1959 if (me->def->type == VM_METHOD_TYPE_REFINED) {
1960 VALUE klass = (VALUE)data;
1961 struct rb_id_table *tbl = RCLASS_WRITABLE_M_TBL(klass);
1962
1963 if (me->def->body.refined.orig_me) {
1964 const rb_method_entry_t *orig_me = me->def->body.refined.orig_me, *new_me;
1965 RB_OBJ_WRITE(me, &me->def->body.refined.orig_me, NULL);
1966 new_me = rb_method_entry_clone(me);
1967 rb_method_table_insert(klass, tbl, key, new_me);
1968 rb_method_entry_copy(me, orig_me);
1969 return ID_TABLE_CONTINUE;
1970 }
1971 else {
1972 rb_method_table_insert(klass, tbl, key, me);
1973 return ID_TABLE_DELETE;
1974 }
1975 }
1976 else {
1977 return ID_TABLE_CONTINUE;
1978 }
1979}
1980
1981static enum rb_id_table_iterator_result
1982cache_clear_refined_method(ID key, VALUE value, void *data)
1983{
1984 rb_method_entry_t *me = (rb_method_entry_t *) value;
1985
1986 if (me->def->type == VM_METHOD_TYPE_REFINED && me->def->body.refined.orig_me) {
1987 VALUE klass = (VALUE)data;
1988 rb_clear_method_cache(klass, me->called_id);
1989 }
1990 // Refined method entries without an orig_me is going to stay in the method
1991 // table of klass, like before the move, so no need to clear the cache.
1992
1993 return ID_TABLE_CONTINUE;
1994}
1995
1996static bool
1997ensure_origin(VALUE klass)
1998{
1999 VALUE origin = RCLASS_ORIGIN(klass);
2000 if (origin == klass) {
2001 /* Create the box-local classext before reading m_tbl, so that the
2002 * origin shares the m_tbl with the box-local iclasses of klass,
2003 * as rb_prepend_module relies on that identity. */
2004 rb_class_ensure_writable(klass);
2005 origin = class_alloc(T_ICLASS, klass);
2006 RCLASS_SET_M_TBL(origin, RCLASS_M_TBL(klass));
2007 rb_class_set_super(origin, RCLASS_SUPER(klass));
2008 rb_class_set_super(klass, origin); // writes origin into RCLASS_SUPER(klass)
2009 RCLASS_WRITE_ORIGIN(klass, origin);
2010
2011 // RCLASS_WRITE_ORIGIN marks origin as an origin, so this is the first
2012 // point that it sees M_TBL and may mark it
2013 rb_gc_writebarrier_remember(origin);
2014
2015 class_clear_method_table(klass);
2016 rb_id_table_foreach(RCLASS_M_TBL(origin), cache_clear_refined_method, (void *)klass);
2017 rb_id_table_foreach(RCLASS_M_TBL(origin), move_refined_method, (void *)klass);
2018 return true;
2019 }
2020 return false;
2021}
2022
2023void
2025{
2026 int changed;
2027 bool klass_had_no_origin;
2028
2029 ensure_includable(klass, module);
2030 if (module_in_super_chain(klass, module))
2031 rb_raise(rb_eArgError, "cyclic prepend detected");
2032
2033 klass_had_no_origin = ensure_origin(klass);
2034 changed = do_include_modules_at(klass, klass, module, FALSE, false);
2035 RUBY_ASSERT(changed >= 0); // already checked for cyclic prepend above
2036 if (changed) {
2037 rb_vm_check_redefinition_by_prepend(klass);
2038 }
2039 if (RB_TYPE_P(klass, T_MODULE)) {
2040 VALUE subs_v = RCLASS_SUBCLASSES(klass);
2041 VALUE klass_origin = RCLASS_ORIGIN(klass);
2042 struct rb_id_table *klass_m_tbl = RCLASS_M_TBL(klass);
2043 struct rb_id_table *klass_origin_m_tbl = RCLASS_M_TBL(klass_origin);
2044 if (subs_v) {
2045 struct rb_subclasses *subs = (struct rb_subclasses *)subs_v;
2046 VALUE *entries = rb_imemo_subclasses_entries(subs_v);
2047 VALUE new_origins = 0;
2048 for (uint32_t i = 0; i < subs->count; i++) {
2049 const VALUE subclass = entries[i];
2050 if (!subclass) continue;
2051 /* During lazy sweeping, the entry could be a dead object that
2052 * has not yet been swept. */
2053 if (!rb_objspace_garbage_object_p(subclass)) {
2054 if (klass_had_no_origin && klass_origin_m_tbl == RCLASS_M_TBL(subclass)) {
2055 // backfill an origin iclass to handle refinements and future prepends
2056 rb_id_table_foreach(RCLASS_M_TBL(subclass), clear_module_cache_i, (void *)subclass);
2057 RCLASS_WRITE_M_TBL(subclass, klass_m_tbl);
2058 VALUE origin = rb_include_class_new(klass_origin, RCLASS_SUPER(subclass));
2059 rb_class_set_super(subclass, origin);
2060 RCLASS_SET_INCLUDER(origin, RCLASS_INCLUDER(subclass));
2061 RCLASS_WRITE_ORIGIN(subclass, origin);
2062 RICLASS_SET_ORIGIN_SHARED_MTBL(origin);
2063 if (!new_origins) new_origins = rb_ary_hidden_new(1);
2064 rb_ary_push(new_origins, origin);
2065 }
2066 include_modules_at(subclass, subclass, module, FALSE);
2067 }
2068 }
2069 /* Register after the loop. Registering during it would visit the
2070 * new iclass and prepend module into it a second time. */
2071 if (new_origins) {
2072 for (long i = 0; i < RARRAY_LEN(new_origins); i++) {
2073 rb_module_add_to_subclasses_list(klass, RARRAY_AREF(new_origins, i));
2074 }
2075 }
2076 RB_GC_GUARD(new_origins);
2077 }
2078 }
2079}
2080
2081/*
2082 * call-seq:
2083 * mod.included_modules -> array
2084 *
2085 * Returns the list of modules included or prepended in <i>mod</i>
2086 * or one of <i>mod</i>'s ancestors.
2087 *
2088 * module Sub
2089 * end
2090 *
2091 * module Mixin
2092 * prepend Sub
2093 * end
2094 *
2095 * module Outer
2096 * include Mixin
2097 * end
2098 *
2099 * Mixin.included_modules #=> [Sub]
2100 * Outer.included_modules #=> [Sub, Mixin]
2101 */
2102
2103VALUE
2105{
2106 VALUE ary = rb_ary_new();
2107 VALUE p;
2108 VALUE origin = RCLASS_ORIGIN(mod);
2109
2110 for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
2111 if (p != origin && RCLASS_ORIGIN(p) == p && BUILTIN_TYPE(p) == T_ICLASS) {
2112 VALUE m = METACLASS_OF(p);
2113 if (RB_TYPE_P(m, T_MODULE))
2114 rb_ary_push(ary, m);
2115 }
2116 }
2117 return ary;
2118}
2119
2120/*
2121 * call-seq:
2122 * mod.include?(module) -> true or false
2123 *
2124 * Returns <code>true</code> if <i>module</i> is included
2125 * or prepended in <i>mod</i> or one of <i>mod</i>'s ancestors.
2126 *
2127 * module A
2128 * end
2129 * class B
2130 * include A
2131 * end
2132 * class C < B
2133 * end
2134 * B.include?(A) #=> true
2135 * C.include?(A) #=> true
2136 * A.include?(A) #=> false
2137 */
2138
2139VALUE
2141{
2142 VALUE p;
2143
2144 Check_Type(mod2, T_MODULE);
2145 for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
2146 if (BUILTIN_TYPE(p) == T_ICLASS && !RICLASS_IS_ORIGIN_P(p)) {
2147 if (METACLASS_OF(p) == mod2) return Qtrue;
2148 }
2149 }
2150 return Qfalse;
2151}
2152
2153/*
2154 * call-seq:
2155 * mod.ancestors -> array
2156 *
2157 * Returns a list of modules included/prepended in <i>mod</i>
2158 * (including <i>mod</i> itself).
2159 *
2160 * module Mod
2161 * include Math
2162 * include Comparable
2163 * prepend Enumerable
2164 * end
2165 *
2166 * Mod.ancestors #=> [Enumerable, Mod, Comparable, Math]
2167 * Math.ancestors #=> [Math]
2168 * Enumerable.ancestors #=> [Enumerable]
2169 */
2170
2171VALUE
2173{
2174 VALUE p, ary = rb_ary_new();
2175 VALUE refined_class = Qnil;
2176 if (BUILTIN_TYPE(mod) == T_MODULE && FL_TEST(mod, RMODULE_IS_REFINEMENT)) {
2177 refined_class = rb_refinement_module_get_refined_class(mod);
2178 }
2179
2180 for (p = mod; p; p = RCLASS_SUPER(p)) {
2181 if (p == refined_class) break;
2182 if (p != RCLASS_ORIGIN(p)) continue;
2183 if (BUILTIN_TYPE(p) == T_ICLASS) {
2184 rb_ary_push(ary, METACLASS_OF(p));
2185 }
2186 else {
2187 rb_ary_push(ary, p);
2188 }
2189 }
2190 return ary;
2191}
2192
2194{
2195 VALUE buffer;
2196 long count;
2197 long maxcount;
2198 bool immediate_only;
2199};
2200
2201static void
2202class_descendants_recursive(VALUE klass, VALUE v)
2203{
2204 struct subclass_traverse_data *data = (struct subclass_traverse_data *) v;
2205
2206 if (RB_TYPE_P(klass, T_ICLASS)) return; // skip refinement ICLASSes
2207
2208 if (!RCLASS_SINGLETON_P(klass)) {
2209 if (data->buffer && data->count < data->maxcount && !rb_objspace_garbage_object_p(klass)) {
2210 // assumes that this does not cause GC as long as the length does not exceed the capacity
2211 rb_ary_push(data->buffer, klass);
2212 }
2213 data->count++;
2214 if (data->immediate_only) return;
2215 }
2216 rb_class_foreach_subclass(klass, class_descendants_recursive, v);
2217}
2218
2219static VALUE
2220class_descendants(VALUE klass, bool immediate_only)
2221{
2222 struct subclass_traverse_data data = { Qfalse, 0, -1, immediate_only };
2223
2224 // estimate the count of subclasses
2225 rb_class_foreach_subclass(klass, class_descendants_recursive, (VALUE) &data);
2226
2227 // the following allocation may cause GC which may change the number of subclasses
2228 data.buffer = rb_ary_new_capa(data.count);
2229 data.maxcount = data.count;
2230 data.count = 0;
2231
2232 size_t gc_count = rb_gc_count();
2233
2234 // enumerate subclasses
2235 rb_class_foreach_subclass(klass, class_descendants_recursive, (VALUE) &data);
2236
2237 if (gc_count != rb_gc_count()) {
2238 rb_bug("GC must not occur during the subclass iteration of Class#descendants");
2239 }
2240
2241 return data.buffer;
2242}
2243
2244/*
2245 * call-seq:
2246 * subclasses -> array
2247 *
2248 * Returns an array of classes where the receiver is the
2249 * direct superclass of the class, excluding singleton classes.
2250 * The order of the returned array is not defined.
2251 *
2252 * class A; end
2253 * class B < A; end
2254 * class C < B; end
2255 * class D < A; end
2256 *
2257 * A.subclasses #=> [D, B]
2258 * B.subclasses #=> [C]
2259 * C.subclasses #=> []
2260 *
2261 * Anonymous subclasses (not associated with a constant) are
2262 * returned, too:
2263 *
2264 * c = Class.new(A)
2265 * A.subclasses # => [#<Class:0x00007f003c77bd78>, D, B]
2266 *
2267 * Note that the parent does not hold references to subclasses
2268 * and doesn't prevent them from being garbage collected. This
2269 * means that the subclass might disappear when all references
2270 * to it are dropped:
2271 *
2272 * # drop the reference to subclass, it can be garbage-collected now
2273 * c = nil
2274 *
2275 * A.subclasses
2276 * # It can be
2277 * # => [#<Class:0x00007f003c77bd78>, D, B]
2278 * # ...or just
2279 * # => [D, B]
2280 * # ...depending on whether garbage collector was run
2281 */
2282
2283VALUE
2285{
2286 return class_descendants(klass, true);
2287}
2288
2290{
2291 VALUE buffer;
2292 long count;
2293 long maxcount;
2294 st_table *visited;
2295};
2296
2297static void module_descendants_recursive(VALUE entry, VALUE v);
2298
2299static void
2300module_descendants_add(VALUE klass, struct descendants_traverse_data *data)
2301{
2302 // skip entries beyond the estimation to keep the enumeration pass allocation-free
2303 if (data->buffer && data->count >= data->maxcount) return;
2304
2305 if (st_insert(data->visited, (st_data_t)klass, 1)) return; // already visited
2306
2307 if (data->buffer) {
2308 // assumes that this does not cause GC as long as the length does not exceed the capacity
2309 rb_ary_push(data->buffer, klass);
2310 }
2311 data->count++;
2312 rb_class_foreach_subclass(klass, module_descendants_recursive, (VALUE)data);
2313}
2314
2315// an include done in another box is not in the ancestors here if the includer
2316// has a classext per box, e.g. a module included into a builtin class
2317static bool
2318iclass_in_ancestors_p(VALUE iclass, VALUE includer)
2319{
2320 for (VALUE p = includer; p; p = RCLASS_SUPER(p)) {
2321 if (p == iclass) return true;
2322 }
2323 return false;
2324}
2325
2326static void
2327module_descendants_recursive(VALUE entry, VALUE v)
2328{
2329 struct descendants_traverse_data *data = (struct descendants_traverse_data *)v;
2330
2331 if (rb_objspace_garbage_object_p(entry)) return;
2332
2333 if (RB_TYPE_P(entry, T_ICLASS)) {
2334 // resolve the ICLASS to the including class or module;
2335 // refinement ICLASSes have no includer
2336 VALUE includer = RCLASS_INCLUDER(entry);
2337 while (includer && RB_TYPE_P(includer, T_ICLASS)) {
2338 includer = RCLASS_INCLUDER(includer);
2339 }
2340 if (!includer || UNDEF_P(includer)) return;
2341 if (rb_objspace_garbage_object_p(includer)) return;
2342 if (RCLASS_SINGLETON_P(includer)) return; // e.g. Object#extend
2343 if (!iclass_in_ancestors_p(entry, includer)) return;
2344 module_descendants_add(includer, data);
2345 }
2346 else {
2347 if (RCLASS_SINGLETON_P(entry)) return;
2348 module_descendants_add(entry, data);
2349 }
2350}
2351
2352/*
2353 * call-seq:
2354 * descendants -> array
2355 *
2356 * Returns an array of classes and modules that have the receiver in
2357 * their ancestors. This is the inverse of Module#ancestors:
2358 * +x.descendants.include?(y)+ holds if and only if
2359 * +y.ancestors.include?(x)+ holds, except that the receiver itself,
2360 * singleton classes, and refinements are never included.
2361 * The order of the returned array is not defined.
2362 *
2363 * module A; end
2364 * module B; include A; end
2365 * class C; include B; end
2366 * class D < C; end
2367 *
2368 * A.descendants #=> [B, C, D]
2369 * B.descendants #=> [C, D]
2370 * C.descendants #=> [D]
2371 *
2372 * Note that the receiver does not hold references to its descendants
2373 * and doesn't prevent them from being garbage collected. This means
2374 * that a descendant might disappear from the result when all
2375 * references to it are dropped, depending on whether garbage
2376 * collector was run.
2377 */
2378
2379VALUE
2381{
2382 struct descendants_traverse_data data = { Qfalse, 0, -1, NULL };
2383
2384 // estimate the count of descendants
2385 data.visited = st_init_numtable();
2386 st_insert(data.visited, (st_data_t)mod, 1); // exclude the receiver
2387 rb_class_foreach_subclass(mod, module_descendants_recursive, (VALUE)&data);
2388 st_free_table(data.visited);
2389
2390 // the following allocation may cause GC which may change the number of descendants
2391 data.buffer = rb_ary_new_capa(data.count);
2392 data.maxcount = data.count;
2393 data.count = 0;
2394 // pre-sized so that st_insert() does not cause GC during the enumeration
2395 data.visited = st_init_numtable_with_size(data.maxcount + 1);
2396 st_insert(data.visited, (st_data_t)mod, 1); // exclude the receiver
2397
2398 size_t gc_count = rb_gc_count();
2399
2400 rb_class_foreach_subclass(mod, module_descendants_recursive, (VALUE)&data);
2401
2402 if (gc_count != rb_gc_count()) {
2403 rb_bug("GC must not occur during the subclass iteration of Module#descendants");
2404 }
2405 st_free_table(data.visited);
2406
2407 return data.buffer;
2408}
2409
2410/*
2411 * call-seq:
2412 * attached_object -> object
2413 *
2414 * Returns the object for which the receiver is the singleton class.
2415 *
2416 * Raises an TypeError if the class is not a singleton class.
2417 *
2418 * Raises a Ractor::IsolationError if the attached object is not shareable and
2419 * belongs to another Ractor.
2420 *
2421 * class Foo; end
2422 *
2423 * Foo.singleton_class.attached_object #=> Foo
2424 * Foo.attached_object #=> TypeError: `Foo' is not a singleton class
2425 * Foo.new.singleton_class.attached_object #=> #<Foo:0x000000010491a370>
2426 * TrueClass.attached_object #=> TypeError: `TrueClass' is not a singleton class
2427 * NilClass.attached_object #=> TypeError: `NilClass' is not a singleton class
2428 */
2429
2430VALUE
2432{
2433 if (!RCLASS_SINGLETON_P(klass)) {
2434 rb_raise(rb_eTypeError, "'%"PRIsVALUE"' is not a singleton class", klass);
2435 }
2436
2437 const VALUE obj = RCLASS_ATTACHED_OBJECT(klass);
2438
2439 /* A singleton class is shareable whatever it is attached to, so another Ractor can
2440 * hold one attached to an unshareable object. Returning it would share it. */
2441 if (rb_objspace_foreign_object_p(obj) && !RB_OBJ_SHAREABLE_P(obj)) {
2442 /* No klass in the message: naming a singleton class inspects the very object we
2443 * must not touch from here. */
2444 rb_raise(rb_eRactorIsolationError,
2445 "can not get an unshareable attached object from another Ractor");
2446 }
2447
2448 return obj;
2449}
2450
2451static void
2452ins_methods_push(st_data_t name, st_data_t ary)
2453{
2454 rb_ary_push((VALUE)ary, ID2SYM((ID)name));
2455}
2456
2457static int
2458ins_methods_i(st_data_t name, st_data_t type, st_data_t ary)
2459{
2460 switch ((rb_method_visibility_t)type) {
2461 case METHOD_VISI_UNDEF:
2462 case METHOD_VISI_PRIVATE:
2463 break;
2464 default: /* everything but private */
2465 ins_methods_push(name, ary);
2466 break;
2467 }
2468 return ST_CONTINUE;
2469}
2470
2471static int
2472ins_methods_type_i(st_data_t name, st_data_t type, st_data_t ary, rb_method_visibility_t visi)
2473{
2474 if ((rb_method_visibility_t)type == visi) {
2475 ins_methods_push(name, ary);
2476 }
2477 return ST_CONTINUE;
2478}
2479
2480static int
2481ins_methods_prot_i(st_data_t name, st_data_t type, st_data_t ary)
2482{
2483 return ins_methods_type_i(name, type, ary, METHOD_VISI_PROTECTED);
2484}
2485
2486static int
2487ins_methods_priv_i(st_data_t name, st_data_t type, st_data_t ary)
2488{
2489 return ins_methods_type_i(name, type, ary, METHOD_VISI_PRIVATE);
2490}
2491
2492static int
2493ins_methods_pub_i(st_data_t name, st_data_t type, st_data_t ary)
2494{
2495 return ins_methods_type_i(name, type, ary, METHOD_VISI_PUBLIC);
2496}
2497
2498static int
2499ins_methods_undef_i(st_data_t name, st_data_t type, st_data_t ary)
2500{
2501 return ins_methods_type_i(name, type, ary, METHOD_VISI_UNDEF);
2502}
2503
2505 st_table *list;
2506 int recur;
2507};
2508
2509static enum rb_id_table_iterator_result
2510method_entry_i(ID key, VALUE value, void *data)
2511{
2512 const rb_method_entry_t *me = (const rb_method_entry_t *)value;
2513 struct method_entry_arg *arg = (struct method_entry_arg *)data;
2514 rb_method_visibility_t type;
2515
2516 if (me->def->type == VM_METHOD_TYPE_REFINED) {
2517 VALUE owner = me->owner;
2518 me = rb_resolve_refined_method(Qnil, me);
2519 if (!me) return ID_TABLE_CONTINUE;
2520 if (!arg->recur && me->owner != owner) return ID_TABLE_CONTINUE;
2521 }
2522 if (!st_is_member(arg->list, key)) {
2523 if (UNDEFINED_METHOD_ENTRY_P(me)) {
2524 type = METHOD_VISI_UNDEF; /* none */
2525 }
2526 else {
2527 type = METHOD_ENTRY_VISI(me);
2528 RUBY_ASSERT(type != METHOD_VISI_UNDEF);
2529 }
2530 st_add_direct(arg->list, key, (st_data_t)type);
2531 }
2532 return ID_TABLE_CONTINUE;
2533}
2534
2535static void
2536add_instance_method_list(VALUE mod, struct method_entry_arg *me_arg)
2537{
2538 struct rb_id_table *m_tbl = RCLASS_M_TBL(mod);
2539 if (!m_tbl) return;
2540 rb_id_table_foreach(m_tbl, method_entry_i, me_arg);
2541}
2542
2543static bool
2544particular_class_p(VALUE mod)
2545{
2546 if (!mod) return false;
2547 if (RCLASS_SINGLETON_P(mod)) return true;
2548 if (BUILTIN_TYPE(mod) == T_ICLASS) return true;
2549 return false;
2550}
2551
2552static VALUE
2553class_instance_method_list(int argc, const VALUE *argv, VALUE mod, int obj, int (*func) (st_data_t, st_data_t, st_data_t))
2554{
2555 VALUE ary;
2556 int recur = TRUE, prepended = 0;
2557 struct method_entry_arg me_arg;
2558
2559 if (rb_check_arity(argc, 0, 1)) recur = RTEST(argv[0]);
2560
2561 me_arg.list = st_init_numtable();
2562 me_arg.recur = recur;
2563
2564 if (obj) {
2565 for (; particular_class_p(mod); mod = RCLASS_SUPER(mod)) {
2566 add_instance_method_list(mod, &me_arg);
2567 }
2568 }
2569
2570 if (!recur && RCLASS_ORIGIN(mod) != mod) {
2571 mod = RCLASS_ORIGIN(mod);
2572 prepended = 1;
2573 }
2574
2575 for (; mod; mod = RCLASS_SUPER(mod)) {
2576 add_instance_method_list(mod, &me_arg);
2577 if (BUILTIN_TYPE(mod) == T_ICLASS && !prepended) continue;
2578 if (!recur) break;
2579 }
2580 ary = rb_ary_new2(me_arg.list->num_entries);
2581 st_foreach(me_arg.list, func, ary);
2582 st_free_table(me_arg.list);
2583
2584 return ary;
2585}
2586
2587/*
2588 * call-seq:
2589 * mod.instance_methods(include_super=true) -> array
2590 *
2591 * Returns an array containing the names of the public and protected instance
2592 * methods in the receiver. For a module, these are the public and protected methods;
2593 * for a class, they are the instance (not singleton) methods. If the optional
2594 * parameter is <code>false</code>, the methods of any ancestors are not included.
2595 *
2596 * module A
2597 * def method1() end
2598 * end
2599 * class B
2600 * include A
2601 * def method2() end
2602 * end
2603 * class C < B
2604 * def method3() end
2605 * end
2606 *
2607 * A.instance_methods(false) #=> [:method1]
2608 * B.instance_methods(false) #=> [:method2]
2609 * B.instance_methods(true).include?(:method1) #=> true
2610 * C.instance_methods(false) #=> [:method3]
2611 * C.instance_methods.include?(:method2) #=> true
2612 *
2613 * Note that method visibility changes in the current class, as well as aliases,
2614 * are considered as methods of the current class by this method:
2615 *
2616 * class C < B
2617 * alias method4 method2
2618 * protected :method2
2619 * end
2620 * C.instance_methods(false).sort #=> [:method2, :method3, :method4]
2621 */
2622
2623VALUE
2624rb_class_instance_methods(int argc, const VALUE *argv, VALUE mod)
2625{
2626 return class_instance_method_list(argc, argv, mod, 0, ins_methods_i);
2627}
2628
2629/*
2630 * call-seq:
2631 * mod.protected_instance_methods(include_super=true) -> array
2632 *
2633 * Returns a list of the protected instance methods defined in
2634 * <i>mod</i>. If the optional parameter is <code>false</code>, the
2635 * methods of any ancestors are not included.
2636 */
2637
2638VALUE
2640{
2641 return class_instance_method_list(argc, argv, mod, 0, ins_methods_prot_i);
2642}
2643
2644/*
2645 * call-seq:
2646 * mod.private_instance_methods(include_super=true) -> array
2647 *
2648 * Returns a list of the private instance methods defined in
2649 * <i>mod</i>. If the optional parameter is <code>false</code>, the
2650 * methods of any ancestors are not included.
2651 *
2652 * module Mod
2653 * def method1() end
2654 * private :method1
2655 * def method2() end
2656 * end
2657 * Mod.instance_methods #=> [:method2]
2658 * Mod.private_instance_methods #=> [:method1]
2659 */
2660
2661VALUE
2663{
2664 return class_instance_method_list(argc, argv, mod, 0, ins_methods_priv_i);
2665}
2666
2667/*
2668 * call-seq:
2669 * mod.public_instance_methods(include_super=true) -> array
2670 *
2671 * Returns a list of the public instance methods defined in <i>mod</i>.
2672 * If the optional parameter is <code>false</code>, the methods of
2673 * any ancestors are not included.
2674 */
2675
2676VALUE
2678{
2679 return class_instance_method_list(argc, argv, mod, 0, ins_methods_pub_i);
2680}
2681
2682/*
2683 * call-seq:
2684 * mod.undefined_instance_methods -> array
2685 *
2686 * Returns a list of the undefined instance methods defined in <i>mod</i>.
2687 * The undefined methods of any ancestors are not included.
2688 */
2689
2690VALUE
2691rb_class_undefined_instance_methods(VALUE mod)
2692{
2693 VALUE include_super = Qfalse;
2694 return class_instance_method_list(1, &include_super, mod, 0, ins_methods_undef_i);
2695}
2696
2697/*
2698 * call-seq:
2699 * obj.methods(regular=true) -> array
2700 *
2701 * Returns a list of the names of public and protected methods of
2702 * <i>obj</i>. This will include all the methods accessible in
2703 * <i>obj</i>'s ancestors.
2704 * If the optional parameter is <code>false</code>, it
2705 * returns an array of <i>obj</i>'s public and protected singleton methods,
2706 * the array will not include methods in modules included in <i>obj</i>.
2707 *
2708 * class Klass
2709 * def klass_method()
2710 * end
2711 * end
2712 * k = Klass.new
2713 * k.methods[0..9] #=> [:klass_method, :nil?, :===,
2714 * # :==~, :!, :eql?
2715 * # :hash, :<=>, :class, :singleton_class]
2716 * k.methods.length #=> 56
2717 *
2718 * k.methods(false) #=> []
2719 * def k.singleton_method; end
2720 * k.methods(false) #=> [:singleton_method]
2721 *
2722 * module M123; def m123; end end
2723 * k.extend M123
2724 * k.methods(false) #=> [:singleton_method]
2725 */
2726
2727VALUE
2728rb_obj_methods(int argc, const VALUE *argv, VALUE obj)
2729{
2730 rb_check_arity(argc, 0, 1);
2731 if (argc > 0 && !RTEST(argv[0])) {
2732 return rb_obj_singleton_methods(argc, argv, obj);
2733 }
2734 return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_i);
2735}
2736
2737/*
2738 * call-seq:
2739 * obj.protected_methods(all=true) -> array
2740 *
2741 * Returns the list of protected methods accessible to <i>obj</i>. If
2742 * the <i>all</i> parameter is set to <code>false</code>, only those methods
2743 * in the receiver will be listed.
2744 */
2745
2746VALUE
2747rb_obj_protected_methods(int argc, const VALUE *argv, VALUE obj)
2748{
2749 return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_prot_i);
2750}
2751
2752/*
2753 * call-seq:
2754 * obj.private_methods(all=true) -> array
2755 *
2756 * Returns the list of private methods accessible to <i>obj</i>. If
2757 * the <i>all</i> parameter is set to <code>false</code>, only those methods
2758 * in the receiver will be listed.
2759 */
2760
2761VALUE
2762rb_obj_private_methods(int argc, const VALUE *argv, VALUE obj)
2763{
2764 return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_priv_i);
2765}
2766
2767/*
2768 * call-seq:
2769 * obj.public_methods(all=true) -> array
2770 *
2771 * Returns the list of public methods accessible to <i>obj</i>. If
2772 * the <i>all</i> parameter is set to <code>false</code>, only those methods
2773 * in the receiver will be listed.
2774 */
2775
2776VALUE
2777rb_obj_public_methods(int argc, const VALUE *argv, VALUE obj)
2778{
2779 return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_pub_i);
2780}
2781
2782/*
2783 * call-seq:
2784 * obj.singleton_methods(all=true) -> array
2785 *
2786 * Returns an array of the names of singleton methods for <i>obj</i>.
2787 * If the optional <i>all</i> parameter is true, the list will include
2788 * methods in modules included in <i>obj</i>.
2789 * Only public and protected singleton methods are returned.
2790 *
2791 * module Other
2792 * def three() end
2793 * end
2794 *
2795 * class Single
2796 * def Single.four() end
2797 * end
2798 *
2799 * a = Single.new
2800 *
2801 * def a.one()
2802 * end
2803 *
2804 * class << a
2805 * include Other
2806 * def two()
2807 * end
2808 * end
2809 *
2810 * Single.singleton_methods #=> [:four]
2811 * a.singleton_methods(false) #=> [:two, :one]
2812 * a.singleton_methods #=> [:two, :one, :three]
2813 */
2814
2815VALUE
2816rb_obj_singleton_methods(int argc, const VALUE *argv, VALUE obj)
2817{
2818 VALUE ary, klass, origin;
2819 struct method_entry_arg me_arg;
2820 struct rb_id_table *mtbl;
2821 int recur = TRUE;
2822
2823 if (rb_check_arity(argc, 0, 1)) recur = RTEST(argv[0]);
2824 if (RB_TYPE_P(obj, T_CLASS) && RCLASS_SINGLETON_P(obj)) {
2825 rb_singleton_class(obj);
2826 }
2827 klass = CLASS_OF(obj);
2828 origin = RCLASS_ORIGIN(klass);
2829 me_arg.list = st_init_numtable();
2830 me_arg.recur = recur;
2831 if (klass && RCLASS_SINGLETON_P(klass)) {
2832 if ((mtbl = RCLASS_M_TBL(origin)) != 0) rb_id_table_foreach(mtbl, method_entry_i, &me_arg);
2833 klass = RCLASS_SUPER(klass);
2834 }
2835 if (recur) {
2836 while (klass && (RCLASS_SINGLETON_P(klass) || RB_TYPE_P(klass, T_ICLASS))) {
2837 if (klass != origin && (mtbl = RCLASS_M_TBL(klass)) != 0) rb_id_table_foreach(mtbl, method_entry_i, &me_arg);
2838 klass = RCLASS_SUPER(klass);
2839 }
2840 }
2841 ary = rb_ary_new2(me_arg.list->num_entries);
2842 st_foreach(me_arg.list, ins_methods_i, ary);
2843 st_free_table(me_arg.list);
2844
2845 return ary;
2846}
2847
2856#ifdef rb_define_method_id
2857#undef rb_define_method_id
2858#endif
2859void
2860rb_define_method_id(VALUE klass, ID mid, VALUE (*func)(ANYARGS), int argc)
2861{
2862 rb_add_method_cfunc(klass, mid, func, argc, METHOD_VISI_PUBLIC);
2863}
2864
2865#ifdef rb_define_method
2866#undef rb_define_method
2867#endif
2868void
2869rb_define_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc)
2870{
2871 rb_add_method_cfunc(klass, rb_intern(name), func, argc, METHOD_VISI_PUBLIC);
2872}
2873
2874#ifdef rb_define_protected_method
2875#undef rb_define_protected_method
2876#endif
2877void
2878rb_define_protected_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc)
2879{
2880 rb_add_method_cfunc(klass, rb_intern(name), func, argc, METHOD_VISI_PROTECTED);
2881}
2882
2883#ifdef rb_define_private_method
2884#undef rb_define_private_method
2885#endif
2886void
2887rb_define_private_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc)
2888{
2889 rb_add_method_cfunc(klass, rb_intern(name), func, argc, METHOD_VISI_PRIVATE);
2890}
2891
2892void
2893rb_undef_method(VALUE klass, const char *name)
2894{
2895 rb_add_method(klass, rb_intern(name), VM_METHOD_TYPE_UNDEF, 0, METHOD_VISI_UNDEF);
2896}
2897
2898static enum rb_id_table_iterator_result
2899undef_method_i(ID name, VALUE value, void *data)
2900{
2901 VALUE klass = (VALUE)data;
2902 rb_add_method(klass, name, VM_METHOD_TYPE_UNDEF, 0, METHOD_VISI_UNDEF);
2903 return ID_TABLE_CONTINUE;
2904}
2905
2906void
2907rb_undef_methods_from(VALUE klass, VALUE super)
2908{
2909 struct rb_id_table *mtbl = RCLASS_M_TBL(super);
2910 if (mtbl) {
2911 rb_id_table_foreach(mtbl, undef_method_i, (void *)klass);
2912 }
2913}
2914
2923static inline VALUE
2924special_singleton_class_of(VALUE obj)
2925{
2926 switch (obj) {
2927 case Qnil: return rb_cNilClass;
2928 case Qfalse: return rb_cFalseClass;
2929 case Qtrue: return rb_cTrueClass;
2930 default: return Qnil;
2931 }
2932}
2933
2934VALUE
2935rb_special_singleton_class(VALUE obj)
2936{
2937 return special_singleton_class_of(obj);
2938}
2939
2949static VALUE
2950singleton_class_of(VALUE obj, bool ensure_eigenclass)
2951{
2952 VALUE klass;
2953
2954 switch (TYPE(obj)) {
2955 case T_FIXNUM:
2956 case T_BIGNUM:
2957 case T_FLOAT:
2958 case T_SYMBOL:
2959 rb_raise(rb_eTypeError, "can't define singleton");
2960
2961 case T_FALSE:
2962 case T_TRUE:
2963 case T_NIL:
2964 klass = special_singleton_class_of(obj);
2965 if (NIL_P(klass))
2966 rb_bug("unknown immediate %p", (void *)obj);
2967 return klass;
2968
2969 case T_STRING:
2970 if (CHILLED_STRING_P(obj)) {
2971 CHILLED_STRING_MUTATED(obj);
2972 }
2973 else if (FL_TEST_RAW(obj, RSTRING_FSTR)) {
2974 rb_raise(rb_eTypeError, "can't define singleton");
2975 }
2976 }
2977
2978 bool needs_lock = rb_multi_ractor_p() && rb_ractor_shareable_p(obj);
2979 unsigned int lev;
2980 if (needs_lock) {
2981 RB_VM_LOCK_ENTER_LEV(&lev);
2982 }
2983 {
2984 klass = METACLASS_OF(obj);
2985 if (!(RCLASS_SINGLETON_P(klass) &&
2986 RCLASS_ATTACHED_OBJECT(klass) == obj)) {
2987 klass = rb_make_metaclass(obj, klass);
2988 }
2989 RB_FL_SET_RAW(klass, RB_OBJ_FROZEN_RAW(obj));
2990 if (ensure_eigenclass && RB_TYPE_P(obj, T_CLASS)) {
2991 /* ensures an exposed class belongs to its own eigenclass */
2992 (void)ENSURE_EIGENCLASS(klass);
2993 }
2994 }
2995 if (needs_lock) {
2996 RB_VM_LOCK_LEAVE_LEV(&lev);
2997 }
2998
2999 return klass;
3000}
3001
3002#if RUBY_VERSION_SINCE(4, 2)
3003RBIMPL_TODO("make rb_freeze_singleton_class internal; remove from fl_type.h")
3004#endif
3005void
3007{
3008 VALUE klass;
3009
3010 /* Freeze singleton classes of singleton class, as singleton class is frozen, and so on */
3011 /* In each iteration, check the current object's class pointer is the singleton class of the object. */
3012 while ((klass = RBASIC_CLASS(attached_object)) &&
3013 FL_TEST_RAW(klass, FL_SINGLETON) &&
3014 !OBJ_FROZEN_RAW(klass) &&
3015 (RCLASS_ATTACHED_OBJECT(klass) == attached_object)) {
3016 attached_object = klass;
3017 OBJ_FREEZE(attached_object);
3018 }
3019}
3020
3028VALUE
3030{
3031 VALUE klass;
3032
3033 if (SPECIAL_CONST_P(obj)) {
3034 return rb_special_singleton_class(obj);
3035 }
3036 klass = METACLASS_OF(obj);
3037 if (!RCLASS_SINGLETON_P(klass)) return Qnil;
3038 if (RCLASS_ATTACHED_OBJECT(klass) != obj) return Qnil;
3039 return klass;
3040}
3041
3042VALUE
3044{
3045 return singleton_class_of(obj, true);
3046}
3047
3057#ifdef rb_define_singleton_method
3058#undef rb_define_singleton_method
3059#endif
3060void
3061rb_define_singleton_method(VALUE obj, const char *name, VALUE (*func)(ANYARGS), int argc)
3062{
3063 rb_define_method(singleton_class_of(obj, false), name, func, argc);
3064}
3065
3066#ifdef rb_define_module_function
3067#undef rb_define_module_function
3068#endif
3069void
3070rb_define_module_function(VALUE module, const char *name, VALUE (*func)(ANYARGS), int argc)
3071{
3072 rb_define_private_method(module, name, func, argc);
3073 rb_define_singleton_method(module, name, func, argc);
3074}
3075
3076#ifdef rb_define_global_function
3077#undef rb_define_global_function
3078#endif
3079void
3080rb_define_global_function(const char *name, VALUE (*func)(ANYARGS), int argc)
3081{
3082 rb_define_module_function(rb_mKernel, name, func, argc);
3083}
3084
3085void
3086rb_define_alias(VALUE klass, const char *name1, const char *name2)
3087{
3088 rb_alias(klass, rb_intern(name1), rb_intern(name2));
3089}
3090
3091void
3092rb_define_attr(VALUE klass, const char *name, int read, int write)
3093{
3094 rb_attr(klass, rb_intern(name), read, write, FALSE);
3095}
3096
3097VALUE
3098rb_keyword_error_new(const char *error, VALUE keys)
3099{
3100 long i = 0, len = RARRAY_LEN(keys);
3101 VALUE error_message = rb_sprintf("%s keyword%.*s", error, len > 1, "s");
3102
3103 if (len > 0) {
3104 rb_str_cat_cstr(error_message, ": ");
3105 while (1) {
3106 const VALUE k = RARRAY_AREF(keys, i);
3107 rb_str_append(error_message, rb_inspect(k));
3108 if (++i >= len) break;
3109 rb_str_cat_cstr(error_message, ", ");
3110 }
3111 }
3112
3113 return rb_exc_new_str(rb_eArgError, error_message);
3114}
3115
3116NORETURN(static void rb_keyword_error(const char *error, VALUE keys));
3117static void
3118rb_keyword_error(const char *error, VALUE keys)
3119{
3120 rb_exc_raise(rb_keyword_error_new(error, keys));
3121}
3122
3123NORETURN(static void unknown_keyword_error(VALUE hash, const ID *table, int keywords));
3124static void
3125unknown_keyword_error(VALUE hash, const ID *table, int keywords)
3126{
3127 int i;
3128 for (i = 0; i < keywords; i++) {
3129 st_data_t key = ID2SYM(table[i]);
3130 rb_hash_stlike_delete(hash, &key, NULL);
3131 }
3132 rb_keyword_error("unknown", rb_hash_keys(hash));
3133}
3134
3135
3136static int
3137separate_symbol(st_data_t key, st_data_t value, st_data_t arg)
3138{
3139 VALUE *kwdhash = (VALUE *)arg;
3140 if (!SYMBOL_P(key)) kwdhash++;
3141 if (!*kwdhash) *kwdhash = rb_hash_new();
3142 rb_hash_aset(*kwdhash, (VALUE)key, (VALUE)value);
3143 return ST_CONTINUE;
3144}
3145
3146VALUE
3148{
3149 VALUE parthash[2] = {0, 0};
3150 VALUE hash = *orighash;
3151
3152 if (RHASH_EMPTY_P(hash)) {
3153 *orighash = 0;
3154 return hash;
3155 }
3156 rb_hash_foreach(hash, separate_symbol, (st_data_t)&parthash);
3157 *orighash = parthash[1];
3158 if (parthash[1] && RBASIC_CLASS(hash) != rb_cHash) {
3159 RBASIC_SET_CLASS(parthash[1], RBASIC_CLASS(hash));
3160 }
3161 return parthash[0];
3162}
3163
3164int
3165rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
3166{
3167 int i = 0, j;
3168 int rest = 0;
3169 VALUE missing = Qnil;
3170 st_data_t key;
3171
3172#define extract_kwarg(keyword, val) \
3173 (key = (st_data_t)(keyword), values ? \
3174 (rb_hash_stlike_delete(keyword_hash, &key, &(val)) || ((val) = Qundef, 0)) : \
3175 rb_hash_stlike_lookup(keyword_hash, key, NULL))
3176
3177 if (NIL_P(keyword_hash)) keyword_hash = 0;
3178
3179 if (optional < 0) {
3180 rest = 1;
3181 optional = -1-optional;
3182 }
3183 if (required) {
3184 for (; i < required; i++) {
3185 VALUE keyword = ID2SYM(table[i]);
3186 if (keyword_hash) {
3187 if (extract_kwarg(keyword, values[i])) {
3188 continue;
3189 }
3190 }
3191 if (NIL_P(missing)) missing = rb_ary_hidden_new(1);
3192 rb_ary_push(missing, keyword);
3193 }
3194 if (!NIL_P(missing)) {
3195 rb_keyword_error("missing", missing);
3196 }
3197 }
3198 j = i;
3199 if (optional && keyword_hash) {
3200 for (i = 0; i < optional; i++) {
3201 if (extract_kwarg(ID2SYM(table[required+i]), values[required+i])) {
3202 j++;
3203 }
3204 }
3205 }
3206 if (!rest && keyword_hash) {
3207 if (RHASH_SIZE(keyword_hash) > (unsigned int)(values ? 0 : j)) {
3208 unknown_keyword_error(keyword_hash, table, required+optional);
3209 }
3210 }
3211 if (values && !keyword_hash) {
3212 for (i = 0; i < required + optional; i++) {
3213 values[i] = Qundef;
3214 }
3215 }
3216 return j;
3217#undef extract_kwarg
3218}
3219
3221 int kw_flag;
3222 int n_lead;
3223 int n_opt;
3224 int n_trail;
3225 bool f_var;
3226 bool f_hash;
3227 bool f_block;
3228};
3229
3230static void
3231rb_scan_args_parse(int kw_flag, const char *fmt, struct rb_scan_args_t *arg)
3232{
3233 const char *p = fmt;
3234
3235 memset(arg, 0, sizeof(*arg));
3236 arg->kw_flag = kw_flag;
3237
3238 if (ISDIGIT(*p)) {
3239 arg->n_lead = *p - '0';
3240 p++;
3241 if (ISDIGIT(*p)) {
3242 arg->n_opt = *p - '0';
3243 p++;
3244 }
3245 }
3246 if (*p == '*') {
3247 arg->f_var = 1;
3248 p++;
3249 }
3250 if (ISDIGIT(*p)) {
3251 arg->n_trail = *p - '0';
3252 p++;
3253 }
3254 if (*p == ':') {
3255 arg->f_hash = 1;
3256 p++;
3257 }
3258 if (*p == '&') {
3259 arg->f_block = 1;
3260 p++;
3261 }
3262 if (*p != '\0') {
3263 rb_fatal("bad scan arg format: %s", fmt);
3264 }
3265}
3266
3267static int
3268rb_scan_args_assign(const struct rb_scan_args_t *arg, int argc, const VALUE *const argv, va_list vargs)
3269{
3270 int i, argi = 0;
3271 VALUE *var, hash = Qnil;
3272#define rb_scan_args_next_param() va_arg(vargs, VALUE *)
3273 const int kw_flag = arg->kw_flag;
3274 const int n_lead = arg->n_lead;
3275 const int n_opt = arg->n_opt;
3276 const int n_trail = arg->n_trail;
3277 const int n_mand = n_lead + n_trail;
3278 const bool f_var = arg->f_var;
3279 const bool f_hash = arg->f_hash;
3280 const bool f_block = arg->f_block;
3281
3282 /* capture an option hash - phase 1: pop from the argv */
3283 if (f_hash && argc > 0) {
3284 VALUE last = argv[argc - 1];
3285 if (rb_scan_args_keyword_p(kw_flag, last)) {
3286 hash = rb_hash_dup(last);
3287 argc--;
3288 }
3289 }
3290
3291 if (argc < n_mand) {
3292 goto argc_error;
3293 }
3294
3295 /* capture leading mandatory arguments */
3296 for (i = 0; i < n_lead; i++) {
3297 var = rb_scan_args_next_param();
3298 if (var) *var = argv[argi];
3299 argi++;
3300 }
3301 /* capture optional arguments */
3302 for (i = 0; i < n_opt; i++) {
3303 var = rb_scan_args_next_param();
3304 if (argi < argc - n_trail) {
3305 if (var) *var = argv[argi];
3306 argi++;
3307 }
3308 else {
3309 if (var) *var = Qnil;
3310 }
3311 }
3312 /* capture variable length arguments */
3313 if (f_var) {
3314 int n_var = argc - argi - n_trail;
3315
3316 var = rb_scan_args_next_param();
3317 if (0 < n_var) {
3318 if (var) *var = rb_ary_new_from_values(n_var, &argv[argi]);
3319 argi += n_var;
3320 }
3321 else {
3322 if (var) *var = rb_ary_new();
3323 }
3324 }
3325 /* capture trailing mandatory arguments */
3326 for (i = 0; i < n_trail; i++) {
3327 var = rb_scan_args_next_param();
3328 if (var) *var = argv[argi];
3329 argi++;
3330 }
3331 /* capture an option hash - phase 2: assignment */
3332 if (f_hash) {
3333 var = rb_scan_args_next_param();
3334 if (var) *var = hash;
3335 }
3336 /* capture iterator block */
3337 if (f_block) {
3338 var = rb_scan_args_next_param();
3339 if (rb_block_given_p()) {
3340 *var = rb_block_proc();
3341 }
3342 else {
3343 *var = Qnil;
3344 }
3345 }
3346
3347 if (argi == argc) {
3348 return argc;
3349 }
3350
3351 argc_error:
3352 return -(argc + 1);
3353#undef rb_scan_args_next_param
3354}
3355
3356static int
3357rb_scan_args_result(const struct rb_scan_args_t *const arg, int argc)
3358{
3359 const int n_lead = arg->n_lead;
3360 const int n_opt = arg->n_opt;
3361 const int n_trail = arg->n_trail;
3362 const int n_mand = n_lead + n_trail;
3363 const bool f_var = arg->f_var;
3364
3365 if (argc >= 0) {
3366 return argc;
3367 }
3368
3369 argc = -argc - 1;
3370 rb_error_arity(argc, n_mand, f_var ? UNLIMITED_ARGUMENTS : n_mand + n_opt);
3372}
3373
3374#undef rb_scan_args
3375int
3376rb_scan_args(int argc, const VALUE *argv, const char *fmt, ...)
3377{
3378 va_list vargs;
3379 struct rb_scan_args_t arg;
3380 rb_scan_args_parse(RB_SCAN_ARGS_PASS_CALLED_KEYWORDS, fmt, &arg);
3381 va_start(vargs,fmt);
3382 argc = rb_scan_args_assign(&arg, argc, argv, vargs);
3383 va_end(vargs);
3384 return rb_scan_args_result(&arg, argc);
3385}
3386
3387#undef rb_scan_args_kw
3388int
3389rb_scan_args_kw(int kw_flag, int argc, const VALUE *argv, const char *fmt, ...)
3390{
3391 va_list vargs;
3392 struct rb_scan_args_t arg;
3393 rb_scan_args_parse(kw_flag, fmt, &arg);
3394 va_start(vargs,fmt);
3395 argc = rb_scan_args_assign(&arg, argc, argv, vargs);
3396 va_end(vargs);
3397 return rb_scan_args_result(&arg, argc);
3398}
3399
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_method_id(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_protected_method(klass, mid, func, arity)
Defines klass#mid and makes it protected.
#define rb_define_module_function(klass, mid, func, arity)
Defines klass#mid and makes it a module function.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
#define RUBY_EXTERN
Declaration of externally visible global variables.
Definition dllexport.h:45
static VALUE RB_OBJ_FROZEN_RAW(VALUE obj)
This is an implementation detail of RB_OBJ_FROZEN().
Definition fl_type.h:699
static void RB_FL_SET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_SET().
Definition fl_type.h:544
VALUE rb_class_protected_instance_methods(int argc, const VALUE *argv, VALUE mod)
Identical to rb_class_instance_methods(), except it returns names of methods that are protected only.
Definition class.c:2639
static VALUE class_alloc0(enum ruby_value_type type, VALUE klass, bool boxable)
Allocates a struct RClass for a new class, iclass, or module.
Definition class.c:574
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1765
VALUE rb_refinement_new(void)
Creates a new, anonymous refinement.
Definition class.c:1663
VALUE rb_class_new(VALUE super)
Creates a new, anonymous class.
Definition class.c:849
static VALUE make_singleton_class(VALUE obj)
Creates a singleton class for obj.
Definition class.c:1368
VALUE rb_singleton_class_clone(VALUE obj)
Clones a singleton class.
Definition class.c:1205
void rb_prepend_module(VALUE klass, VALUE module)
Identical to rb_include_module(), except it "prepends" the passed module to the klass,...
Definition class.c:2024
VALUE rb_class_subclasses(VALUE klass)
Queries the class's direct descendants.
Definition class.c:2284
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3043
VALUE rb_class_attached_object(VALUE klass)
Returns the attached object for a singleton class.
Definition class.c:2431
VALUE rb_obj_singleton_methods(int argc, const VALUE *argv, VALUE obj)
Identical to rb_class_instance_methods(), except it returns names of singleton methods instead of ins...
Definition class.c:2816
VALUE rb_module_new(void)
Creates a new, anonymous module.
Definition class.c:1657
#define META_CLASS_OF_CLASS_CLASS_P(k)
whether k is a meta^(n)-class of Class class
Definition class.c:1285
VALUE rb_class_instance_methods(int argc, const VALUE *argv, VALUE mod)
Generates an array of symbols, which are the list of method names defined in the passed class.
Definition class.c:2624
void rb_check_inheritable(VALUE super)
Asserts that the given class can derive a child class.
Definition class.c:834
VALUE rb_class_public_instance_methods(int argc, const VALUE *argv, VALUE mod)
Identical to rb_class_instance_methods(), except it returns names of methods that are public only.
Definition class.c:2677
VALUE rb_class_super_of(VALUE klass)
Internal header for Objspace.
Definition class.c:459
VALUE rb_class_boot(VALUE super)
A utility function that wraps class_alloc.
Definition class.c:767
void rb_class_modify_check(VALUE klass)
Asserts that klass is not a frozen class.
Definition eval.c:445
VALUE rb_define_module_id_under(VALUE outer, ID id)
Identical to rb_define_module_under(), except it takes the name in ID instead of C's string.
Definition class.c:1694
void rb_singleton_class_attached(VALUE klass, VALUE obj)
Attaches a singleton class to its corresponding object.
Definition class.c:1273
VALUE rb_mod_included_modules(VALUE mod)
Queries the list of included modules.
Definition class.c:2104
VALUE rb_define_class_id_under(VALUE outer, ID id, VALUE super)
Identical to rb_define_class_under(), except it takes the name in ID instead of C's string.
Definition class.c:1633
VALUE rb_mod_ancestors(VALUE mod)
Queries the module's ancestors.
Definition class.c:2172
static VALUE make_metaclass(VALUE klass)
Creates a metaclass of klass
Definition class.c:1330
VALUE rb_class_inherited(VALUE super, VALUE klass)
Calls Class::inherited.
Definition class.c:1557
VALUE rb_mod_include_p(VALUE mod, VALUE mod2)
Queries if the passed module is included by the module.
Definition class.c:2140
void rb_freeze_singleton_class(VALUE attached_object)
This is an implementation detail of RB_OBJ_FREEZE().
Definition class.c:3006
VALUE rb_class_private_instance_methods(int argc, const VALUE *argv, VALUE mod)
Identical to rb_class_instance_methods(), except it returns names of methods that are private only.
Definition class.c:2662
#define ENSURE_EIGENCLASS(klass)
ensures klass belongs to its own eigenclass.
Definition class.c:1316
VALUE rb_mod_init_copy(VALUE clone, VALUE orig)
The comment that comes with this function says :nodoc:.
Definition class.c:1089
VALUE rb_mod_descendants(VALUE mod)
Queries the module's descendants.
Definition class.c:2380
VALUE rb_singleton_class_get(VALUE obj)
Returns the singleton class of obj, or nil if obj is not a singleton object.
Definition class.c:3029
VALUE rb_define_module_id(ID id)
This is a very badly designed API that creates an anonymous module.
Definition class.c:1670
VALUE rb_define_class_id(ID id, VALUE super)
This is a very badly designed API that creates an anonymous class.
Definition class.c:1536
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3086
VALUE rb_extract_keywords(VALUE *orighash)
Splits a hash into two.
Definition class.c:3147
void rb_define_attr(VALUE klass, const char *name, int read, int write)
Defines public accessor method(s) for an attribute.
Definition class.c:3092
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2893
int rb_scan_args_kw(int kw_flag, int argc, const VALUE *argv, const char *fmt,...)
Identical to rb_scan_args(), except it also accepts kw_splat.
Definition class.c:3389
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:3376
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1035
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3165
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define FL_SINGLETON
Old name of RUBY_FL_SINGLETON.
Definition fl_type.h:58
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define ALLOC
Old name of RB_ALLOC.
Definition memory.h:400
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define T_NIL
Old name of RUBY_T_NIL.
Definition value_type.h:72
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#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 FL_SHAREABLE
Old name of RUBY_FL_SHAREABLE.
Definition fl_type.h:62
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define xmalloc
Old name of ruby_xmalloc.
Definition xmalloc.h:53
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
#define ISDIGIT
Old name of rb_isdigit.
Definition ctype.h:93
#define T_TRUE
Old name of RUBY_T_TRUE.
Definition value_type.h:81
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:128
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:125
#define T_FALSE
Old name of RUBY_T_FALSE.
Definition value_type.h:61
#define Qtrue
Old name of RUBY_Qtrue.
#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_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#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:127
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:126
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
#define OBJ_FROZEN_RAW
Old name of RB_OBJ_FROZEN_RAW.
Definition fl_type.h:134
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:678
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1463
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1514
VALUE rb_cClass
Class class.
Definition object.c:62
VALUE rb_class_superclass(VALUE klass)
Queries the parent of the given class.
Definition object.c:2307
VALUE rb_mKernel
Kernel module.
Definition object.c:59
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:657
VALUE rb_cRefinement
Refinement class.
Definition object.c:63
VALUE rb_cNilClass
NilClass class.
Definition object.c:65
VALUE rb_cHash
Hash class.
Definition hash.c:123
VALUE rb_cFalseClass
FalseClass class.
Definition object.c:67
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:234
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:668
VALUE rb_cBasicObject
BasicObject class.
Definition object.c:58
VALUE rb_cModule
Module class.
Definition object.c:61
VALUE rb_class_real(VALUE klass)
Finds a "real" class.
Definition object.c:225
VALUE rb_cTrueClass
TrueClass class.
Definition object.c:66
#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:481
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:469
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_ary_cat(VALUE ary, const VALUE *train, long len)
Destructively appends multiple elements at the end of the array.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_resize(VALUE ary, long len)
Expands or shrinks the passed array to the passed length.
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
#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
int rb_is_instance_id(ID id)
Classifies the given ID, then sees if it is an instance variable.
Definition symbol.c:1253
int rb_is_class_id(ID id)
Classifies the given ID, then sees if it is a class variable.
Definition symbol.c:1241
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:1575
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3898
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1657
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:3974
VALUE rb_const_get_at(VALUE space, ID name)
Identical to rb_const_defined_at(), except it returns the actual defined value.
Definition variable.c:3501
void rb_set_class_path_string(VALUE klass, VALUE space, VALUE name)
Identical to rb_set_class_path(), except it accepts the name as Ruby's string instead of C's.
Definition variable.c:441
int rb_const_defined_at(VALUE space, ID name)
Identical to rb_const_defined(), except it doesn't look for parent classes.
Definition variable.c:3834
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:398
void rb_alias(VALUE klass, ID dst, ID src)
Resembles alias.
Definition vm_method.c:2936
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:2501
void rb_clear_constant_cache_for_id(ID id)
Clears the inline constant caches associated with a particular ID.
Definition vm_method.c:333
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
int len
Length of the buffer.
Definition io.h:8
static bool rb_ractor_shareable_p(VALUE obj)
Queries if multiple Ractors can share the passed object or not.
Definition ractor.h:269
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:255
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
VALUE type(ANYARGS)
ANYARGS-ed function type.
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define RARRAY_AREF(a, i)
Definition rarray.h:402
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition rbasic.h:166
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
Definition rclass.h:44
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition rhash.h:69
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition rhash.h:79
#define RB_SCAN_ARGS_PASS_CALLED_KEYWORDS
Same behaviour as rb_scan_args().
Definition scan_args.h:50
#define RTEST
This is an old name of RB_TEST.
#define ANYARGS
Functions declared using this macro take arbitrary arguments, including void.
Definition stdarg.h:64
Definition class.h:88
Definition class.c:2504
Internal header for Ruby Box.
Definition box.h:14
Definition constant.h:33
Internal header for Class.
Definition class.h:31
Definition method.h:55
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:425
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
ruby_value_type
C-level type of an object.
Definition value_type.h:113