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