Ruby 4.1.0dev (2026-11-10 revision c65a8e03f14ed911e519028419ba3b2b9fbad6d3)
class.c (c65a8e03f14ed911e519028419ba3b2b9fbad6d3)
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
214/* Fills ext's m_tbl with a copy of orig. The table is stored on ext before it is filled
215 * so the GC, which can run at any allocation here, always sees the entries through klass.
216 * For an ICLASS it only marks the m_tbl when ICLASS_IS_ORIGIN is set, so set that first. */
217static void
218duplicate_classext_m_tbl(rb_classext_t *ext, struct rb_id_table *orig, VALUE klass, bool init_missing)
219{
220 if (!orig) {
221 RCLASSEXT_M_TBL(ext) = init_missing ? rb_id_table_create(0) : NULL;
222 return;
223 }
224 struct rb_id_table *tbl = rb_id_table_create(rb_id_table_size(orig));
225 RCLASSEXT_M_TBL(ext) = tbl;
226 struct duplicate_id_tbl_data data = {
227 .tbl = tbl,
228 .klass = klass,
229 };
230 rb_id_table_foreach(orig, duplicate_classext_m_tbl_i, &data);
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->u.file, src->u.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 RCLASSEXT_ICLASS_IS_ORIGIN(ext) = RCLASSEXT_ICLASS_IS_ORIGIN(src);
301 RCLASSEXT_ICLASS_ORIGIN_SHARED_MTBL(ext) = RCLASSEXT_ICLASS_ORIGIN_SHARED_MTBL(src);
302
303 // See also: rb_include_class_new()
304 if (RCLASSEXT_ICLASS_IS_ORIGIN(src) && !RCLASSEXT_ICLASS_ORIGIN_SHARED_MTBL(src)) {
305 duplicate_classext_m_tbl(ext, RCLASSEXT_M_TBL(src), iclass, true);
306 }
307 else {
308 RCLASSEXT_M_TBL(ext) = RCLASSEXT_M_TBL(mod_ext);
309 }
310
311 RCLASSEXT_CONST_TBL(ext) = RCLASSEXT_CONST_TBL(mod_ext);
312 RCLASSEXT_CVC_TBL(ext) = RCLASSEXT_CVC_TBL(mod_ext);
313
314 // Those are cache and should be recreated when methods are called
315 // RCLASSEXT_CALLABLE_M_TBL(ext) = NULL;
316 // RCLASSEXT_CC_TBL(ext) = NULL;
317
318 // Subclasses/back-pointers are only in the prime classext.
319
320 RCLASSEXT_SET_ORIGIN(ext, iclass, RCLASSEXT_ORIGIN(src));
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_ICLASS_IS_ORIGIN(ext) = true;
345 duplicate_classext_m_tbl(ext, RCLASSEXT_M_TBL(orig), klass, dup_iclass);
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->u.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 RUBY_ASSERT(!RCLASS_INITIALIZED_P(clone));
919 if (RCLASS_SINGLETON_P(orig)) {
920 rb_raise(rb_eTypeError, "can't copy singleton class");
921 }
922}
923
925 VALUE clone;
926 VALUE new_table;
927};
928
929static struct rb_cvar_class_tbl_entry *
930cvc_table_entry_alloc(void)
931{
932 return (struct rb_cvar_class_tbl_entry *)SHAREABLE_IMEMO_NEW(struct rb_cvar_class_tbl_entry, imemo_cvar_entry, 0);
933}
934
935static enum rb_id_table_iterator_result
936cvc_table_copy(ID id, VALUE val, void *data)
937{
938 struct cvc_table_copy_ctx *ctx = (struct cvc_table_copy_ctx *)data;
939 struct rb_cvar_class_tbl_entry * orig_entry;
940 orig_entry = (struct rb_cvar_class_tbl_entry *)val;
941
942 struct rb_cvar_class_tbl_entry *ent;
943
944 ent = cvc_table_entry_alloc();
945 RB_OBJ_WRITE((VALUE)ent, &ent->class_value, ctx->clone);
946 RB_OBJ_WRITE(ctx->clone, &ent->cref, orig_entry->cref);
947 ent->global_cvar_state = orig_entry->global_cvar_state;
948 rb_marked_id_table_insert(ctx->new_table, id, (VALUE)ent);
949
950 return ID_TABLE_CONTINUE;
951}
952
953static void
954copy_tables(VALUE clone, VALUE orig)
955{
956 if (RCLASS_CONST_TBL(clone)) {
957 rb_free_const_table(RCLASS_CONST_TBL(clone));
958 RCLASS_WRITE_CONST_TBL(clone, 0, false);
959 }
960 if (RCLASS_CVC_TBL(orig)) {
961 VALUE rb_cvc_tbl = RCLASS_CVC_TBL(orig);
962 VALUE rb_cvc_tbl_dup = rb_marked_id_table_new(rb_marked_id_table_size(rb_cvc_tbl));
963
964 struct cvc_table_copy_ctx ctx;
965 ctx.clone = clone;
966 ctx.new_table = rb_cvc_tbl_dup;
967 rb_marked_id_table_foreach(rb_cvc_tbl, cvc_table_copy, &ctx);
968 RCLASS_WRITE_CVC_TBL(clone, rb_cvc_tbl_dup);
969 }
970 rb_id_table_free(RCLASS_M_TBL(clone));
971 RCLASS_WRITE_M_TBL(clone, 0);
972 if (!RB_TYPE_P(clone, T_ICLASS)) {
973 rb_fields_tbl_copy(clone, orig);
974 }
975 if (RCLASS_CONST_TBL(orig)) {
976 struct clone_const_arg arg;
977 struct rb_id_table *const_tbl;
978 struct rb_id_table *orig_tbl = RCLASS_CONST_TBL(orig);
979 arg.klass = clone;
980 RB_VM_LOCKING() { // orig's owner may be removing constants (rb_const_remove)
981 arg.tbl = const_tbl = rb_id_table_create(rb_id_table_size(orig_tbl));
982 rb_id_table_foreach(orig_tbl, clone_const_i, &arg);
983 }
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
1008move_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 move an object whose singleton class has constant %"PRIsVALUE
1014 " referring to an unshareable object", rb_id2str(id));
1015 }
1016 return ID_TABLE_CONTINUE;
1017}
1018
1019static int
1020move_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 move an object whose singleton class has variable %"PRIsVALUE
1025 " referring to an unshareable object", rb_id2str(id));
1026 }
1027 return ST_CONTINUE;
1028}
1029
1030/* The receiver of a moved object becomes the owner of its singleton class
1031 * (rb_class_take_ownership), so nothing the sender keeps may stay readable there. */
1032void
1033rb_class_check_singleton_movable(VALUE klass)
1034{
1035 do {
1036 if (RCLASS_CONST_TBL(klass)) {
1037 rb_id_table_foreach(RCLASS_CONST_TBL(klass), move_check_const_i, NULL);
1038 }
1039 rb_ivar_foreach_buffered(klass, move_check_field_i, 0);
1040 } while ((klass = class_own_metaclass(klass)) != 0);
1041}
1042
1043// the copy would carry the owner's field values, which only the owner may read
1044static void
1045init_copy_owner_check(VALUE orig)
1046{
1047 VALUE meta = METACLASS_OF(orig);
1048 if (!rb_class_owned_p(orig) || (RCLASS_SINGLETON_P(meta) && !rb_class_owned_p(meta))) {
1049 rb_raise(rb_eRactorIsolationError, "can not copy a class/module created by another Ractor");
1050 }
1051}
1052
1053/* :nodoc: */
1054VALUE
1056{
1057 /* Only class or module is valid here, but other classes may enter here and
1058 * only hit an exception on the OBJ_INIT_COPY checks
1059 */
1060 switch (BUILTIN_TYPE(clone)) {
1061 case T_CLASS:
1062 class_init_copy_check(clone, orig);
1063 break;
1064 case T_MODULE:
1065 rb_module_check_initializable(clone);
1066 break;
1067 default:
1068 break;
1069 }
1070 if (!OBJ_INIT_COPY(clone, orig)) return clone;
1071
1073 RUBY_ASSERT(BUILTIN_TYPE(clone) == BUILTIN_TYPE(orig));
1074
1075 init_copy_owner_check(orig);
1076
1077 if (RCLASS_INITIALIZED_P(orig)) {
1078 rb_class_set_initialized(clone);
1079 }
1080
1081 if (!RCLASS_SINGLETON_P(CLASS_OF(clone))) {
1082 RBASIC_SET_CLASS(clone, rb_singleton_class_clone(orig));
1083 rb_singleton_class_attached(METACLASS_OF(clone), (VALUE)clone);
1084 }
1085 if (BUILTIN_TYPE(clone) == T_CLASS) {
1086 RCLASS_SET_ALLOCATOR(clone, RCLASS_ALLOCATOR(orig));
1087 }
1088 copy_tables(clone, orig);
1089 if (RCLASS_M_TBL(orig)) {
1090 struct clone_method_arg arg;
1091 arg.new_klass = clone;
1092 class_initialize_method_table(clone);
1093 rb_id_table_foreach(RCLASS_M_TBL(orig), clone_method_i, &arg);
1094 }
1095
1096 if (RCLASS_ORIGIN(orig) == orig) {
1097 rb_class_set_super(clone, RCLASS_SUPER(orig));
1098 }
1099 else {
1100 VALUE p = RCLASS_SUPER(orig);
1101 VALUE orig_origin = RCLASS_ORIGIN(orig);
1102 VALUE prev_clone_p = clone;
1103 VALUE origin_stack = rb_ary_hidden_new(2);
1104 VALUE origin[2];
1105 VALUE clone_p = 0;
1106 rb_len_t origin_len;
1107 int add_subclass;
1108 VALUE clone_origin;
1109
1110 ensure_origin(clone);
1111 clone_origin = RCLASS_ORIGIN(clone);
1112
1113 while (p && p != orig_origin) {
1114 if (BUILTIN_TYPE(p) != T_ICLASS) {
1115 rb_bug("non iclass between module/class and origin");
1116 }
1117 clone_p = class_alloc(T_ICLASS, METACLASS_OF(p));
1118 RCLASS_SET_M_TBL(clone_p, RCLASS_M_TBL(p));
1119 rb_class_set_super(prev_clone_p, clone_p);
1120 prev_clone_p = clone_p;
1121 RCLASS_SET_CONST_TBL(clone_p, RCLASS_CONST_TBL(p), false);
1122 RCLASS_SET_INCLUDER(clone_p, clone);
1123 add_subclass = TRUE;
1124 if (p != RCLASS_ORIGIN(p)) {
1125 origin[0] = clone_p;
1126 origin[1] = RCLASS_ORIGIN(p);
1127 rb_ary_cat(origin_stack, origin, 2);
1128 }
1129 else if ((origin_len = RARRAY_LEN(origin_stack)) > 1 &&
1130 RARRAY_AREF(origin_stack, origin_len - 1) == p) {
1131 RCLASS_WRITE_ORIGIN(RARRAY_AREF(origin_stack, (origin_len -= 2)), clone_p);
1132 RICLASS_WRITE_ORIGIN_SHARED_MTBL(clone_p);
1133 rb_ary_resize(origin_stack, origin_len);
1134 add_subclass = FALSE;
1135 }
1136 if (add_subclass) {
1137 rb_module_add_to_subclasses_list(METACLASS_OF(p), clone_p);
1138 }
1139 p = RCLASS_SUPER(p);
1140 }
1141
1142 if (p == orig_origin) {
1143 if (clone_p) {
1144 rb_class_set_super(clone_p, clone_origin);
1145 rb_class_set_super(clone_origin, RCLASS_SUPER(orig_origin));
1146 }
1147 copy_tables(clone_origin, orig_origin);
1148 if (RCLASS_M_TBL(orig_origin)) {
1149 struct clone_method_arg arg;
1150 arg.new_klass = clone;
1151 class_initialize_method_table(clone_origin);
1152 rb_id_table_foreach(RCLASS_M_TBL(orig_origin), clone_method_i, &arg);
1153 }
1154 }
1155 else {
1156 rb_bug("no origin for class that has origin");
1157 }
1158
1159 rb_class_update_superclasses(clone);
1160 }
1161
1162 if (RB_TYPE_P(clone, T_CLASS)) {
1163 VALUE super = RCLASS_SUPER(clone);
1164 if (super && RB_TYPE_P(super, T_ICLASS)) {
1165 class_switch_superclass(rb_class_superclass(clone), clone);
1166 }
1167 }
1168
1169 return clone;
1170}
1171
1172VALUE
1174{
1175 return rb_singleton_class_clone_and_attach(obj, Qundef);
1176}
1177
1178// Clone and return the singleton class of `obj` if it has been created and is attached to `obj`.
1179VALUE
1180rb_singleton_class_clone_and_attach(VALUE obj, VALUE attach)
1181{
1182 const VALUE klass = METACLASS_OF(obj);
1183
1184 // Note that `rb_singleton_class()` can create situations where `klass` is
1185 // attached to an object other than `obj`. In which case `obj` does not have
1186 // a material singleton class attached yet and there is no singleton class
1187 // to clone.
1188 if (!(RCLASS_SINGLETON_P(klass) && RCLASS_ATTACHED_OBJECT(klass) == obj)) {
1189 // nothing to clone
1190 return klass;
1191 }
1192 else {
1193 /* copy singleton(unnamed) class */
1194 bool klass_of_clone_is_new;
1195 RUBY_ASSERT(RB_TYPE_P(klass, T_CLASS));
1196 VALUE clone = class_alloc(T_CLASS, 0);
1197
1198 if (BUILTIN_TYPE(obj) == T_CLASS) {
1199 klass_of_clone_is_new = true;
1200 RBASIC_SET_CLASS(clone, clone);
1201 }
1202 else {
1203 VALUE klass_metaclass_clone = rb_singleton_class_clone(klass);
1204 // When `METACLASS_OF(klass) == klass_metaclass_clone`, it means the
1205 // recursive call did not clone `METACLASS_OF(klass)`.
1206 klass_of_clone_is_new = (METACLASS_OF(klass) != klass_metaclass_clone);
1207 RBASIC_SET_CLASS(clone, klass_metaclass_clone);
1208 }
1209
1210 // initialize method table before any GC chance
1211 class_initialize_method_table(clone);
1212
1213 rb_class_set_super(clone, RCLASS_SUPER(klass));
1214 rb_fields_tbl_copy(clone, klass);
1215 if (RCLASS_CONST_TBL(klass)) {
1216 struct clone_const_arg arg;
1217 struct rb_id_table *table;
1218 arg.klass = clone;
1219 RB_VM_LOCKING() { // see copy_tables
1220 arg.tbl = table = rb_id_table_create(rb_id_table_size(RCLASS_CONST_TBL(klass)));
1221 rb_id_table_foreach(RCLASS_CONST_TBL(klass), clone_const_i, &arg);
1222 }
1223 RCLASS_SET_CONST_TBL(clone, table, false);
1224 }
1225 if (!UNDEF_P(attach)) {
1226 rb_singleton_class_attached(clone, attach);
1227 }
1228 {
1229 struct clone_method_arg arg;
1230 arg.new_klass = clone;
1231 rb_id_table_foreach(RCLASS_M_TBL(klass), clone_method_i, &arg);
1232 }
1233 if (klass_of_clone_is_new) {
1234 rb_singleton_class_attached(METACLASS_OF(clone), clone);
1235 }
1236 FL_SET(clone, FL_SINGLETON);
1237
1238 return clone;
1239 }
1240}
1241
1242void
1244{
1245 if (RCLASS_SINGLETON_P(klass)) {
1246 RCLASS_SET_ATTACHED_OBJECT(klass, obj);
1247 }
1248}
1249
1255#define META_CLASS_OF_CLASS_CLASS_P(k) (METACLASS_OF(k) == (k))
1256
1257static int
1258rb_singleton_class_has_metaclass_p(VALUE sklass)
1259{
1260 return RCLASS_ATTACHED_OBJECT(METACLASS_OF(sklass)) == sklass;
1261}
1262
1263int
1264rb_singleton_class_internal_p(VALUE sklass)
1265{
1266 return (RB_TYPE_P(RCLASS_ATTACHED_OBJECT(sklass), T_CLASS) &&
1267 !rb_singleton_class_has_metaclass_p(sklass));
1268}
1269
1275#define HAVE_METACLASS_P(k) \
1276 (FL_TEST(METACLASS_OF(k), FL_SINGLETON) && \
1277 rb_singleton_class_has_metaclass_p(k))
1278
1286#define ENSURE_EIGENCLASS(klass) \
1287 (HAVE_METACLASS_P(klass) ? METACLASS_OF(klass) : make_metaclass(klass))
1288
1289
1299static inline VALUE
1301{
1302 VALUE super;
1303 VALUE metaclass = class_boot_boxable(Qundef, FL_TEST_RAW(klass, RCLASS_BOXABLE));
1304
1305 FL_SET(metaclass, FL_SINGLETON);
1306 // owned by the attached class's owner, not by whoever triggered the lazy creation
1307 RCLASS_SET_OWNER_RACTOR_ID(metaclass, RCLASS_OWNER_RACTOR_ID(klass));
1308 rb_singleton_class_attached(metaclass, klass);
1309
1310 if (META_CLASS_OF_CLASS_CLASS_P(klass)) {
1311 SET_METACLASS_OF(klass, metaclass);
1312 SET_METACLASS_OF(metaclass, metaclass);
1313 }
1314 else {
1315 VALUE tmp = METACLASS_OF(klass); /* for a meta^(n)-class klass, tmp is meta^(n)-class of Class class */
1316 SET_METACLASS_OF(klass, metaclass);
1317 SET_METACLASS_OF(metaclass, ENSURE_EIGENCLASS(tmp));
1318 }
1319
1320 super = RCLASS_SUPER(klass);
1321 while (RB_TYPE_P(super, T_ICLASS)) super = RCLASS_SUPER(super);
1322 class_associate_super(metaclass, super ? ENSURE_EIGENCLASS(super) : rb_cClass, true);
1323 rb_class_set_initialized(metaclass);
1324
1325 // Full class ancestry may not have been filled until we reach here.
1326 rb_class_update_superclasses(METACLASS_OF(metaclass));
1327
1328 return metaclass;
1329}
1330
1337static inline VALUE
1339{
1340 VALUE orig_class = METACLASS_OF(obj);
1341 VALUE klass = class_alloc0(T_CLASS, rb_cClass, FL_TEST_RAW(orig_class, RCLASS_BOXABLE));
1342 FL_SET(klass, FL_SINGLETON);
1343 if (RB_TYPE_P(obj, T_MODULE)) {
1344 // as in make_metaclass: the module's owner, not the lazy creator
1345 RCLASS_SET_OWNER_RACTOR_ID(klass, RCLASS_OWNER_RACTOR_ID(obj));
1346 }
1347 else if (rb_ractor_shareable_p(obj)) {
1348 // A shareable object is no single Ractor's, so its singleton class stays the
1349 // main Ractor's rather than being claimed by whoever materialized it.
1350 RCLASS_SET_OWNER_RACTOR_ID(klass, 0);
1351 }
1352 class_initialize_method_table(klass);
1353 class_associate_super(klass, orig_class, true);
1354 if (orig_class && !UNDEF_P(orig_class)) {
1355 rb_class_set_initialized(klass);
1356 }
1357
1358 RBASIC_SET_CLASS(obj, klass);
1359 rb_singleton_class_attached(klass, obj);
1360 rb_yjit_invalidate_no_singleton_class(orig_class);
1361 rb_zjit_invalidate_no_singleton_class(orig_class);
1362
1363 SET_METACLASS_OF(klass, METACLASS_OF(rb_class_real(orig_class)));
1364 return klass;
1365}
1366
1367
1368static VALUE
1369boot_defclass(const char *name, VALUE super)
1370{
1371 VALUE obj = rb_class_boot(super);
1372 ID id = rb_intern(name);
1373
1374 rb_const_set((rb_cObject ? rb_cObject : obj), id, obj);
1375 rb_vm_register_global_object(obj);
1376 return obj;
1377}
1378
1379/***********************************************************************
1380 *
1381 * Document-class: Refinement
1382 *
1383 * Refinement is a class of the +self+ (current context) inside +refine+
1384 * statement. It allows to import methods from other modules, see #import_methods.
1385 */
1386
1387#if 0 /* for RDoc */
1388/*
1389 * Document-method: Refinement#import_methods
1390 *
1391 * call-seq:
1392 * import_methods(module, ...) -> self
1393 *
1394 * Imports methods from modules. Unlike Module#include,
1395 * Refinement#import_methods copies methods and adds them into the refinement,
1396 * so the refinement is activated in the imported methods.
1397 *
1398 * Note that due to method copying, only methods defined in Ruby code can be imported.
1399 *
1400 * module StrUtils
1401 * def indent(level)
1402 * ' ' * level + self
1403 * end
1404 * end
1405 *
1406 * module M
1407 * refine String do
1408 * import_methods StrUtils
1409 * end
1410 * end
1411 *
1412 * using M
1413 * "foo".indent(3)
1414 * #=> " foo"
1415 *
1416 * module M
1417 * refine String do
1418 * import_methods Enumerable
1419 * # Can't import method which is not defined with Ruby code: Enumerable#drop
1420 * end
1421 * end
1422 *
1423 */
1424
1425static VALUE
1426refinement_import_methods(int argc, VALUE *argv, VALUE refinement)
1427{
1428}
1429# endif
1430
1450void
1451Init_class_hierarchy(void)
1452{
1453 rb_cBasicObject = boot_defclass("BasicObject", 0);
1454 RCLASS_SET_ALLOCATOR(rb_cBasicObject, rb_class_allocate_instance);
1455 FL_SET_RAW(rb_cBasicObject, RCLASS_ALLOCATOR_DEFINED);
1456 rb_class_set_initialized(rb_cBasicObject);
1457 RCLASS_SET_EXPECT_NO_IVAR(rb_cBasicObject);
1458
1459 rb_cObject = boot_defclass("Object", rb_cBasicObject);
1460 RCLASS_SET_EXPECT_NO_IVAR(rb_cObject);
1461
1462 /* resolve class name ASAP for order-independence */
1463 rb_set_class_path_string(rb_cObject, rb_cObject, rb_fstring_lit("Object"));
1464
1465 rb_cModule = boot_defclass("Module", rb_cObject);
1466 rb_cClass = boot_defclass("Class", rb_cModule);
1467 rb_cRefinement = boot_defclass("Refinement", rb_cModule);
1468
1469#if 0 /* for RDoc */
1470 // we pretend it to be public, otherwise RDoc will ignore it
1471 rb_define_method(rb_cRefinement, "import_methods", refinement_import_methods, -1);
1472#endif
1473
1475 RBASIC_SET_CLASS(rb_cClass, rb_cClass);
1476 RBASIC_SET_CLASS(rb_cModule, rb_cClass);
1477 RBASIC_SET_CLASS(rb_cObject, rb_cClass);
1478 RBASIC_SET_CLASS(rb_cRefinement, rb_cClass);
1479 RBASIC_SET_CLASS(rb_cBasicObject, rb_cClass);
1480
1482}
1483
1484
1495VALUE
1496rb_make_metaclass(VALUE obj, VALUE unused)
1497{
1498 if (BUILTIN_TYPE(obj) == T_CLASS) {
1499 return make_metaclass(obj);
1500 }
1501 else {
1502 return make_singleton_class(obj);
1503 }
1504}
1505
1506VALUE
1508{
1509 VALUE klass;
1510
1511 if (!super) super = rb_cObject;
1512 klass = rb_class_new(super);
1513 rb_make_metaclass(klass, METACLASS_OF(super));
1514
1515 return klass;
1516}
1517
1518
1527VALUE
1529{
1530 ID inherited;
1531 if (!super) super = rb_cObject;
1532 CONST_ID(inherited, "inherited");
1533 return rb_funcallv_uncached(super, inherited, 1, &klass);
1534}
1535
1536#ifdef rb_define_class
1537#undef rb_define_class
1538#endif
1539VALUE
1540rb_define_class(const char *name, VALUE super)
1541{
1542 return rb_define_class_under(rb_cObject, name, super);
1543}
1544
1545#ifdef rb_define_class_under
1546#undef rb_define_class_under
1547#endif
1548VALUE
1549rb_define_class_under(VALUE outer, const char *name, VALUE super)
1550{
1551 return rb_define_class_id_under(outer, rb_intern(name), super);
1552}
1553
1554VALUE
1555rb_define_class_id_under_no_pin(VALUE outer, ID id, VALUE super)
1556{
1557 VALUE klass;
1558
1559 if (rb_const_defined_at(outer, id)) {
1560 klass = rb_const_get_at(outer, id);
1561 if (!RB_TYPE_P(klass, T_CLASS)) {
1562 if (outer == rb_cObject) {
1563 rb_raise(rb_eTypeError, "%s is not a class (%"PRIsVALUE")",
1564 rb_id2name(id), rb_obj_class(klass));
1565 }
1566 else {
1567 rb_raise(rb_eTypeError, "%"PRIsVALUE"::%"PRIsVALUE" is not a class"
1568 " (%"PRIsVALUE")",
1569 outer, rb_id2str(id), rb_obj_class(klass));
1570 }
1571 }
1572 if (rb_class_real(RCLASS_SUPER(klass)) != super) {
1573 if (outer == rb_cObject) {
1574 rb_raise(rb_eTypeError, "superclass mismatch for class %s", rb_id2name(id));
1575 }
1576 else {
1577 rb_raise(rb_eTypeError, "superclass mismatch for class "
1578 "%"PRIsVALUE"::%"PRIsVALUE""
1579 " (%"PRIsVALUE" is given but was %"PRIsVALUE")",
1580 outer, rb_id2str(id), RCLASS_SUPER(klass), super);
1581 }
1582 }
1583
1584 return klass;
1585 }
1586 if (!super) {
1587 if (outer == rb_cObject) {
1588 rb_raise(rb_eArgError, "no super class for '%"PRIsVALUE"'", rb_id2str(id));
1589 }
1590 else {
1591 rb_raise(rb_eArgError, "no super class for '%"PRIsVALUE"::%"PRIsVALUE"'",
1592 rb_class_path(outer), rb_id2str(id));
1593 }
1594 }
1595 klass = rb_define_class_id(id, super);
1596 rb_set_class_path_string(klass, outer, rb_id2str(id));
1597 rb_const_set(outer, id, klass);
1598 rb_class_inherited(super, klass);
1599
1600 return klass;
1601}
1602
1603VALUE
1605{
1606 VALUE klass = rb_define_class_id_under_no_pin(outer, id, super);
1607 rb_vm_register_global_object(klass);
1608 return klass;
1609}
1610
1611VALUE
1612rb_module_s_alloc(VALUE klass)
1613{
1614 VALUE mod = class_alloc(T_MODULE, klass);
1615 class_initialize_method_table(mod);
1616 return mod;
1617}
1618
1619static inline VALUE
1620module_new(VALUE klass)
1621{
1622 VALUE mdl = class_alloc(T_MODULE, klass);
1623 class_initialize_method_table(mdl);
1624 return (VALUE)mdl;
1625}
1626
1627VALUE
1629{
1630 return module_new(rb_cModule);
1631}
1632
1633VALUE
1635{
1636 return module_new(rb_cRefinement);
1637}
1638
1639// Kept for compatibility. Use rb_module_new() instead.
1640VALUE
1642{
1643 return rb_module_new();
1644}
1645
1646#ifdef rb_define_module
1647#undef rb_define_module
1648#endif
1649VALUE
1650rb_define_module(const char *name)
1651{
1652 return rb_define_module_id_under(rb_cObject, rb_intern(name));
1653}
1654
1655#ifdef rb_define_module_under
1656#undef rb_define_module_under
1657#endif
1658VALUE
1659rb_define_module_under(VALUE outer, const char *name)
1660{
1661 return rb_define_module_id_under(outer, rb_intern(name));
1662}
1663
1664VALUE
1666{
1667 VALUE module;
1668
1669 if (rb_const_defined_at(outer, id)) {
1670 module = rb_const_get_at(outer, id);
1671 if (!RB_TYPE_P(module, T_MODULE)) {
1672 if (outer == rb_cObject) {
1673 rb_raise(rb_eTypeError, "%s is not a module (%"PRIsVALUE")",
1674 rb_id2name(id), rb_obj_class(module));
1675 }
1676 else {
1677 rb_raise(rb_eTypeError, "%"PRIsVALUE"::%"PRIsVALUE" is not a module"
1678 " (%"PRIsVALUE")",
1679 outer, rb_id2str(id), rb_obj_class(module));
1680 }
1681 }
1682 /* Module may have been defined in Ruby and not pin-rooted */
1683 rb_vm_register_global_object(module);
1684 return module;
1685 }
1686 module = rb_module_new();
1687 rb_const_set(outer, id, module);
1688 rb_set_class_path_string(module, outer, rb_id2str(id));
1689 rb_vm_register_global_object(module);
1690
1691 return module;
1692}
1693
1694VALUE
1695rb_include_class_new(VALUE module, VALUE super)
1696{
1697 VALUE klass = class_alloc(T_ICLASS, rb_cClass);
1698
1699 RCLASS_SET_M_TBL(klass, RCLASS_WRITABLE_M_TBL(module));
1700
1701 RCLASS_SET_ORIGIN(klass, klass);
1702 if (BUILTIN_TYPE(module) == T_ICLASS) {
1703 module = METACLASS_OF(module);
1704 }
1705 RUBY_ASSERT(!RB_TYPE_P(module, T_ICLASS));
1706 if (RCLASS_WRITABLE_CONST_TBL(module)) {
1707 RCLASS_SET_CONST_TBL(klass, RCLASS_WRITABLE_CONST_TBL(module), true);
1708 }
1709 else {
1710 RCLASS_WRITE_CONST_TBL(module, rb_id_table_create(0), false);
1711 RCLASS_SET_CONST_TBL(klass, RCLASS_WRITABLE_CONST_TBL(module), true);
1712 }
1713
1714 RCLASS_SET_CVC_TBL(klass, RCLASS_WRITABLE_CVC_TBL(module));
1715
1716 class_associate_super(klass, super, true);
1717 RBASIC_SET_CLASS(klass, module);
1718
1719 return (VALUE)klass;
1720}
1721
1722static int include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super);
1723
1724static void
1725ensure_includable(VALUE klass, VALUE module)
1726{
1727 rb_class_modify_check(klass);
1728 Check_Type(module, T_MODULE);
1729 rb_class_set_initialized(module);
1730 if (!NIL_P(rb_refinement_module_get_refined_class(module))) {
1731 rb_raise(rb_eArgError, "refinement module is not allowed");
1732 }
1733}
1734
1735void
1737{
1738 int changed = 0;
1739
1740 ensure_includable(klass, module);
1741
1742 changed = include_modules_at(klass, RCLASS_ORIGIN(klass), module, TRUE);
1743 if (changed < 0)
1744 rb_raise(rb_eArgError, "cyclic include detected");
1745
1746 if (RB_TYPE_P(klass, T_MODULE)) {
1747 VALUE subs_v = RCLASS_SUBCLASSES(klass);
1748 if (subs_v) {
1749 struct rb_subclasses *subs = (struct rb_subclasses *)subs_v;
1750 VALUE *entries = rb_imemo_subclasses_entries(subs_v);
1751 for (uint32_t i = 0; i < subs->count; i++) {
1752 VALUE check_class = entries[i];
1753 if (!check_class) continue;
1754
1755 int do_include = 1;
1756 /* During lazy sweeping, the entry could be a dead object that
1757 * has not yet been swept. */
1758 if (!rb_objspace_garbage_object_p(check_class)) {
1759 VALUE walk = check_class;
1760 while (walk) {
1761 RUBY_ASSERT(!rb_objspace_garbage_object_p(walk));
1762
1763 if (RB_TYPE_P(walk, T_ICLASS) &&
1764 (METACLASS_OF(walk) == module)) {
1765 do_include = 0;
1766 }
1767 walk = RCLASS_SUPER(walk);
1768 }
1769
1770 if (do_include) {
1771 include_modules_at(check_class, RCLASS_ORIGIN(check_class), module, TRUE);
1772 }
1773 }
1774 }
1775 }
1776 }
1777}
1778
1779static enum rb_id_table_iterator_result
1780add_refined_method_entry_i(ID key, VALUE value, void *data)
1781{
1782 rb_add_refined_method_entry((VALUE)data, key);
1783 return ID_TABLE_CONTINUE;
1784}
1785
1786static enum rb_id_table_iterator_result
1787clear_module_cache_i(ID id, VALUE val, void *data)
1788{
1789 VALUE klass = (VALUE)data;
1790 rb_clear_method_cache(klass, id);
1791 return ID_TABLE_CONTINUE;
1792}
1793
1794static bool
1795module_in_super_chain(const VALUE klass, VALUE module)
1796{
1797 struct rb_id_table *const klass_m_tbl = RCLASS_M_TBL(RCLASS_ORIGIN(klass));
1798 if (klass_m_tbl) {
1799 while (module) {
1800 if (klass_m_tbl == RCLASS_M_TBL(module))
1801 return true;
1802 module = RCLASS_SUPER(module);
1803 }
1804 }
1805 return false;
1806}
1807
1808// For each ID key in the class constant table, we're going to clear the VM's
1809// inline constant caches associated with it.
1810static enum rb_id_table_iterator_result
1811clear_constant_cache_i(ID id, VALUE value, void *data)
1812{
1814 return ID_TABLE_CONTINUE;
1815}
1816
1817static int
1818do_include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super, bool check_cyclic)
1819{
1820 VALUE p, iclass, origin_stack = 0;
1821 int method_changed = 0;
1822 rb_len_t origin_len;
1823 VALUE klass_origin = RCLASS_ORIGIN(klass);
1824 VALUE original_klass = klass;
1825
1826 if (check_cyclic && module_in_super_chain(klass, module))
1827 return -1;
1828
1829 while (module) {
1830 int c_seen = FALSE;
1831 int superclass_seen = FALSE;
1832 struct rb_id_table *tbl;
1833
1834 if (klass == c) {
1835 c_seen = TRUE;
1836 }
1837 if (klass_origin != c || search_super) {
1838 /* ignore if the module included already in superclasses for include,
1839 * ignore if the module included before origin class for prepend
1840 */
1841 for (p = RCLASS_SUPER(klass); p; p = RCLASS_SUPER(p)) {
1842 int type = BUILTIN_TYPE(p);
1843 if (klass_origin == p && !search_super)
1844 break;
1845 if (c == p)
1846 c_seen = TRUE;
1847 if (type == T_ICLASS) {
1848 if (RCLASS_M_TBL(p) == RCLASS_M_TBL(module)) {
1849 if (!superclass_seen && c_seen) {
1850 c = p; /* move insertion point */
1851 }
1852 goto skip;
1853 }
1854 }
1855 else if (type == T_CLASS) {
1856 superclass_seen = TRUE;
1857 }
1858 }
1859 }
1860
1861 VALUE super_class = RCLASS_SUPER(c);
1862
1863 // invalidate inline method cache
1864 RB_DEBUG_COUNTER_INC(cvar_include_invalidate);
1865 ruby_vm_global_cvar_state++;
1866 tbl = RCLASS_M_TBL(module);
1867 if (tbl && rb_id_table_size(tbl)) {
1868 if (search_super) { // include
1869 if (super_class && !RB_TYPE_P(super_class, T_MODULE)) {
1870 rb_id_table_foreach(tbl, clear_module_cache_i, (void *)super_class);
1871 }
1872 }
1873 else { // prepend
1874 if (!RB_TYPE_P(original_klass, T_MODULE)) {
1875 rb_id_table_foreach(tbl, clear_module_cache_i, (void *)original_klass);
1876 }
1877 }
1878 method_changed = 1;
1879 }
1880
1881 // setup T_ICLASS for the include/prepend module
1882 iclass = rb_include_class_new(module, super_class);
1883 c = rb_class_set_super(c, iclass);
1884 RCLASS_SET_INCLUDER(iclass, klass);
1885 if (module != RCLASS_ORIGIN(module)) {
1886 if (!origin_stack) origin_stack = rb_ary_hidden_new(2);
1887 VALUE origin[2] = {iclass, RCLASS_ORIGIN(module)};
1888 rb_ary_cat(origin_stack, origin, 2);
1889 }
1890 else if (origin_stack && (origin_len = RARRAY_LEN(origin_stack)) > 1 &&
1891 RARRAY_AREF(origin_stack, origin_len - 1) == module) {
1892 RCLASS_WRITE_ORIGIN(RARRAY_AREF(origin_stack, (origin_len -= 2)), iclass);
1893 RICLASS_WRITE_ORIGIN_SHARED_MTBL(iclass);
1894 rb_ary_resize(origin_stack, origin_len);
1895 }
1896
1897 VALUE m = module;
1898 if (BUILTIN_TYPE(m) == T_ICLASS) m = METACLASS_OF(m);
1899 rb_module_add_to_subclasses_list(m, iclass);
1900
1901 if (BUILTIN_TYPE(klass) == T_MODULE && FL_TEST(klass, RMODULE_IS_REFINEMENT)) {
1902 VALUE refined_class =
1903 rb_refinement_module_get_refined_class(klass);
1904
1905 rb_id_table_foreach(RCLASS_M_TBL(module), add_refined_method_entry_i, (void *)refined_class);
1907 }
1908
1909 tbl = RCLASS_CONST_TBL(module);
1910 if (tbl && rb_id_table_size(tbl))
1911 rb_id_table_foreach(tbl, clear_constant_cache_i, NULL);
1912 skip:
1913 module = RCLASS_SUPER(module);
1914 }
1915
1916 return method_changed;
1917}
1918
1919static int
1920include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super)
1921{
1922 return do_include_modules_at(klass, c, module, search_super, true);
1923}
1924
1925static enum rb_id_table_iterator_result
1926move_refined_method(ID key, VALUE value, void *data)
1927{
1928 rb_method_entry_t *me = (rb_method_entry_t *)value;
1929
1930 if (me->def->type == VM_METHOD_TYPE_REFINED) {
1931 VALUE klass = (VALUE)data;
1932 struct rb_id_table *tbl = RCLASS_WRITABLE_M_TBL(klass);
1933
1934 if (me->def->body.refined.orig_me) {
1935 const rb_method_entry_t *orig_me = me->def->body.refined.orig_me, *new_me;
1936 RB_OBJ_WRITE(me, &me->def->body.refined.orig_me, NULL);
1937 new_me = rb_method_entry_clone(me);
1938 rb_method_table_insert(klass, tbl, key, new_me);
1939 rb_method_entry_copy(me, orig_me);
1940 return ID_TABLE_CONTINUE;
1941 }
1942 else {
1943 rb_method_table_insert(klass, tbl, key, me);
1944 return ID_TABLE_DELETE;
1945 }
1946 }
1947 else {
1948 return ID_TABLE_CONTINUE;
1949 }
1950}
1951
1952static enum rb_id_table_iterator_result
1953cache_clear_refined_method(ID key, VALUE value, void *data)
1954{
1955 rb_method_entry_t *me = (rb_method_entry_t *) value;
1956
1957 if (me->def->type == VM_METHOD_TYPE_REFINED && me->def->body.refined.orig_me) {
1958 VALUE klass = (VALUE)data;
1959 rb_clear_method_cache(klass, me->called_id);
1960 }
1961 // Refined method entries without an orig_me is going to stay in the method
1962 // table of klass, like before the move, so no need to clear the cache.
1963
1964 return ID_TABLE_CONTINUE;
1965}
1966
1967static bool
1968ensure_origin(VALUE klass)
1969{
1970 VALUE origin = RCLASS_ORIGIN(klass);
1971 if (origin == klass) {
1972 /* Create the box-local classext before reading m_tbl, so that the
1973 * origin shares the m_tbl with the box-local iclasses of klass,
1974 * as rb_prepend_module relies on that identity. */
1975 rb_class_ensure_writable(klass);
1976 origin = class_alloc(T_ICLASS, klass);
1977 RCLASS_SET_M_TBL(origin, RCLASS_M_TBL(klass));
1978 rb_class_set_super(origin, RCLASS_SUPER(klass));
1979 rb_class_set_super(klass, origin); // writes origin into RCLASS_SUPER(klass)
1980 RCLASS_WRITE_ORIGIN(klass, origin);
1981
1982 // RCLASS_WRITE_ORIGIN marks origin as an origin, so this is the first
1983 // point that it sees M_TBL and may mark it
1984 rb_gc_writebarrier_remember(origin);
1985
1986 class_clear_method_table(klass);
1987 rb_id_table_foreach(RCLASS_M_TBL(origin), cache_clear_refined_method, (void *)klass);
1988 rb_id_table_foreach(RCLASS_M_TBL(origin), move_refined_method, (void *)klass);
1989 return true;
1990 }
1991 return false;
1992}
1993
1994void
1996{
1997 int changed;
1998 bool klass_had_no_origin;
1999
2000 ensure_includable(klass, module);
2001 if (module_in_super_chain(klass, module))
2002 rb_raise(rb_eArgError, "cyclic prepend detected");
2003
2004 klass_had_no_origin = ensure_origin(klass);
2005 changed = do_include_modules_at(klass, klass, module, FALSE, false);
2006 RUBY_ASSERT(changed >= 0); // already checked for cyclic prepend above
2007 if (changed) {
2008 rb_vm_check_redefinition_by_prepend(klass);
2009 }
2010 if (RB_TYPE_P(klass, T_MODULE)) {
2011 VALUE subs_v = RCLASS_SUBCLASSES(klass);
2012 VALUE klass_origin = RCLASS_ORIGIN(klass);
2013 struct rb_id_table *klass_m_tbl = RCLASS_M_TBL(klass);
2014 struct rb_id_table *klass_origin_m_tbl = RCLASS_M_TBL(klass_origin);
2015 if (subs_v) {
2016 struct rb_subclasses *subs = (struct rb_subclasses *)subs_v;
2017 VALUE *entries = rb_imemo_subclasses_entries(subs_v);
2018 VALUE new_origins = 0;
2019 for (uint32_t i = 0; i < subs->count; i++) {
2020 const VALUE subclass = entries[i];
2021 if (!subclass) continue;
2022 /* During lazy sweeping, the entry could be a dead object that
2023 * has not yet been swept. */
2024 if (!rb_objspace_garbage_object_p(subclass)) {
2025 if (klass_had_no_origin && klass_origin_m_tbl == RCLASS_M_TBL(subclass)) {
2026 // backfill an origin iclass to handle refinements and future prepends
2027 rb_id_table_foreach(RCLASS_M_TBL(subclass), clear_module_cache_i, (void *)subclass);
2028 RCLASS_WRITE_M_TBL(subclass, klass_m_tbl);
2029 VALUE origin = rb_include_class_new(klass_origin, RCLASS_SUPER(subclass));
2030 rb_class_set_super(subclass, origin);
2031 RCLASS_SET_INCLUDER(origin, RCLASS_INCLUDER(subclass));
2032 RCLASS_WRITE_ORIGIN(subclass, origin);
2033 RICLASS_SET_ORIGIN_SHARED_MTBL(origin);
2034 if (!new_origins) new_origins = rb_ary_hidden_new(1);
2035 rb_ary_push(new_origins, origin);
2036 }
2037 include_modules_at(subclass, subclass, module, FALSE);
2038 }
2039 }
2040 /* Register after the loop. Registering during it would visit the
2041 * new iclass and prepend module into it a second time. */
2042 if (new_origins) {
2043 for (rb_len_t i = 0; i < RARRAY_LEN(new_origins); i++) {
2044 rb_module_add_to_subclasses_list(klass, RARRAY_AREF(new_origins, i));
2045 }
2046 }
2047 RB_GC_GUARD(new_origins);
2048 }
2049 }
2050}
2051
2052/*
2053 * call-seq:
2054 * mod.included_modules -> array
2055 *
2056 * Returns the list of modules included or prepended in <i>mod</i>
2057 * or one of <i>mod</i>'s ancestors.
2058 *
2059 * module Sub
2060 * end
2061 *
2062 * module Mixin
2063 * prepend Sub
2064 * end
2065 *
2066 * module Outer
2067 * include Mixin
2068 * end
2069 *
2070 * Mixin.included_modules #=> [Sub]
2071 * Outer.included_modules #=> [Sub, Mixin]
2072 */
2073
2074VALUE
2076{
2077 VALUE ary = rb_ary_new();
2078 VALUE p;
2079 VALUE origin = RCLASS_ORIGIN(mod);
2080
2081 for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
2082 if (p != origin && RCLASS_ORIGIN(p) == p && BUILTIN_TYPE(p) == T_ICLASS) {
2083 VALUE m = METACLASS_OF(p);
2084 if (RB_TYPE_P(m, T_MODULE))
2085 rb_ary_push(ary, m);
2086 }
2087 }
2088 return ary;
2089}
2090
2091/*
2092 * call-seq:
2093 * mod.include?(module) -> true or false
2094 *
2095 * Returns <code>true</code> if <i>module</i> is included
2096 * or prepended in <i>mod</i> or one of <i>mod</i>'s ancestors.
2097 *
2098 * module A
2099 * end
2100 * class B
2101 * include A
2102 * end
2103 * class C < B
2104 * end
2105 * B.include?(A) #=> true
2106 * C.include?(A) #=> true
2107 * A.include?(A) #=> false
2108 */
2109
2110VALUE
2112{
2113 VALUE p;
2114
2115 Check_Type(mod2, T_MODULE);
2116 for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
2117 if (BUILTIN_TYPE(p) == T_ICLASS && !RICLASS_IS_ORIGIN_P(p)) {
2118 if (METACLASS_OF(p) == mod2) return Qtrue;
2119 }
2120 }
2121 return Qfalse;
2122}
2123
2124/*
2125 * call-seq:
2126 * ancestors -> array
2127 *
2128 * Returns an array of the modules that are ancestors of +self+
2129 * and that +self+ includes or prepends, including +self+:
2130 *
2131 * module MyModule
2132 * include Math
2133 * include Comparable
2134 * prepend Enumerable
2135 * end
2136 * MyModule.ancestors # => [Enumerable, MyModule, Comparable, Math]
2137 *
2138 * class MyClass; end
2139 * MyClass.ancestors # => [MyClass, Object, JSON::GeneratorMethods, PP::ObjectMixin, Kernel, BasicObject]
2140 *
2141 * Object.ancestors # => [Object, JSON::GeneratorMethods, PP::ObjectMixin, Kernel, BasicObject]
2142 * BasicObject.ancestors # => [BasicObject]
2143 *
2144 */
2145
2146VALUE
2148{
2149 VALUE p, ary = rb_ary_new();
2150 VALUE refined_class = Qnil;
2151 if (BUILTIN_TYPE(mod) == T_MODULE && FL_TEST(mod, RMODULE_IS_REFINEMENT)) {
2152 refined_class = rb_refinement_module_get_refined_class(mod);
2153 }
2154
2155 for (p = mod; p; p = RCLASS_SUPER(p)) {
2156 if (p == refined_class) break;
2157 if (p != RCLASS_ORIGIN(p)) continue;
2158 if (BUILTIN_TYPE(p) == T_ICLASS) {
2159 rb_ary_push(ary, METACLASS_OF(p));
2160 }
2161 else {
2162 rb_ary_push(ary, p);
2163 }
2164 }
2165 return ary;
2166}
2167
2169{
2170 VALUE buffer;
2171 long count;
2172 long maxcount;
2173 bool immediate_only;
2174};
2175
2176static void
2177class_descendants_recursive(VALUE klass, VALUE v)
2178{
2179 struct subclass_traverse_data *data = (struct subclass_traverse_data *) v;
2180
2181 if (RB_TYPE_P(klass, T_ICLASS)) return; // skip refinement ICLASSes
2182
2183 if (!RCLASS_SINGLETON_P(klass)) {
2184 if (data->buffer && data->count < data->maxcount && !rb_objspace_garbage_object_p(klass)) {
2185 // assumes that this does not cause GC as long as the length does not exceed the capacity
2186 rb_ary_push(data->buffer, klass);
2187 }
2188 data->count++;
2189 if (data->immediate_only) return;
2190 }
2191 rb_class_foreach_subclass(klass, class_descendants_recursive, v);
2192}
2193
2194static VALUE
2195class_descendants(VALUE klass, bool immediate_only)
2196{
2197 struct subclass_traverse_data data = { Qfalse, 0, -1, immediate_only };
2198
2199 // estimate the count of subclasses
2200 rb_class_foreach_subclass(klass, class_descendants_recursive, (VALUE) &data);
2201
2202 // the following allocation may cause GC which may change the number of subclasses
2203 data.buffer = rb_ary_new_capa(data.count);
2204 data.maxcount = data.count;
2205 data.count = 0;
2206
2207 size_t gc_count = rb_gc_count();
2208
2209 // enumerate subclasses
2210 rb_class_foreach_subclass(klass, class_descendants_recursive, (VALUE) &data);
2211
2212 if (gc_count != rb_gc_count()) {
2213 rb_bug("GC must not occur during the subclass iteration of Class#descendants");
2214 }
2215
2216 return data.buffer;
2217}
2218
2219/*
2220 * call-seq:
2221 * subclasses -> array
2222 *
2223 * Returns an array of classes where the receiver is the
2224 * direct superclass of the class, excluding singleton classes.
2225 * The order of the returned array is not defined.
2226 *
2227 * class A; end
2228 * class B < A; end
2229 * class C < B; end
2230 * class D < A; end
2231 *
2232 * A.subclasses #=> [D, B]
2233 * B.subclasses #=> [C]
2234 * C.subclasses #=> []
2235 *
2236 * Anonymous subclasses (not associated with a constant) are
2237 * returned, too:
2238 *
2239 * c = Class.new(A)
2240 * A.subclasses # => [#<Class:0x00007f003c77bd78>, D, B]
2241 *
2242 * Note that the parent does not hold references to subclasses
2243 * and doesn't prevent them from being garbage collected. This
2244 * means that the subclass might disappear when all references
2245 * to it are dropped:
2246 *
2247 * # drop the reference to subclass, it can be garbage-collected now
2248 * c = nil
2249 *
2250 * A.subclasses
2251 * # It can be
2252 * # => [#<Class:0x00007f003c77bd78>, D, B]
2253 * # ...or just
2254 * # => [D, B]
2255 * # ...depending on whether garbage collector was run
2256 */
2257
2258VALUE
2260{
2261 return class_descendants(klass, true);
2262}
2263
2265{
2266 VALUE buffer;
2267 long count;
2268 long maxcount;
2269 st_table *visited;
2270};
2271
2272static void module_descendants_recursive(VALUE entry, VALUE v);
2273
2274static void
2275module_descendants_add(VALUE klass, struct descendants_traverse_data *data)
2276{
2277 // skip entries beyond the estimation to keep the enumeration pass allocation-free
2278 if (data->buffer && data->count >= data->maxcount) return;
2279
2280 if (st_insert(data->visited, (st_data_t)klass, 1)) return; // already visited
2281
2282 if (data->buffer) {
2283 // assumes that this does not cause GC as long as the length does not exceed the capacity
2284 rb_ary_push(data->buffer, klass);
2285 }
2286 data->count++;
2287 rb_class_foreach_subclass(klass, module_descendants_recursive, (VALUE)data);
2288}
2289
2290// an include done in another box is not in the ancestors here if the includer
2291// has a classext per box, e.g. a module included into a builtin class
2292static bool
2293iclass_in_ancestors_p(VALUE iclass, VALUE includer)
2294{
2295 for (VALUE p = includer; p; p = RCLASS_SUPER(p)) {
2296 if (p == iclass) return true;
2297 }
2298 return false;
2299}
2300
2301static void
2302module_descendants_recursive(VALUE entry, VALUE v)
2303{
2304 struct descendants_traverse_data *data = (struct descendants_traverse_data *)v;
2305
2306 if (rb_objspace_garbage_object_p(entry)) return;
2307
2308 if (RB_TYPE_P(entry, T_ICLASS)) {
2309 // resolve the ICLASS to the including class or module;
2310 // refinement ICLASSes have no includer
2311 VALUE includer = RCLASS_INCLUDER(entry);
2312 while (includer && RB_TYPE_P(includer, T_ICLASS)) {
2313 includer = RCLASS_INCLUDER(includer);
2314 }
2315 if (!includer || UNDEF_P(includer)) return;
2316 if (rb_objspace_garbage_object_p(includer)) return;
2317 if (RCLASS_SINGLETON_P(includer)) return; // e.g. Object#extend
2318 if (!iclass_in_ancestors_p(entry, includer)) return;
2319 module_descendants_add(includer, data);
2320 }
2321 else {
2322 if (RCLASS_SINGLETON_P(entry)) return;
2323 module_descendants_add(entry, data);
2324 }
2325}
2326
2327/*
2328 * call-seq:
2329 * descendants -> array
2330 *
2331 * Returns an array of classes and modules that have +self+ as an ancestor.
2332 * Singleton classes and refinements are not included.
2333 * The order of the returned array is not defined.
2334 *
2335 * module A; end
2336 * module B; include A; end
2337 * class C; include B; end
2338 * class D < C; end
2339 *
2340 * A.descendants #=> [B, C, D]
2341 * B.descendants #=> [C, D]
2342 * C.descendants #=> [D]
2343 *
2344 * Note that +self+ does not hold references to its descendants;
2345 * Thus even though all references to a module are dropped,
2346 * the module may be reported as a descendant, depending on garbage collection.
2347 */
2348
2349VALUE
2351{
2352 struct descendants_traverse_data data = { Qfalse, 0, -1, NULL };
2353
2354 // estimate the count of descendants
2355 data.visited = st_init_numtable();
2356 st_insert(data.visited, (st_data_t)mod, 1); // exclude the receiver
2357 rb_class_foreach_subclass(mod, module_descendants_recursive, (VALUE)&data);
2358 st_free_table(data.visited);
2359
2360 // the following allocation may cause GC which may change the number of descendants
2361 data.buffer = rb_ary_new_capa(data.count);
2362 data.maxcount = data.count;
2363 data.count = 0;
2364 // pre-sized so that st_insert() does not cause GC during the enumeration
2365 data.visited = st_init_numtable_with_size(data.maxcount + 1);
2366 st_insert(data.visited, (st_data_t)mod, 1); // exclude the receiver
2367
2368 size_t gc_count = rb_gc_count();
2369
2370 rb_class_foreach_subclass(mod, module_descendants_recursive, (VALUE)&data);
2371
2372 if (gc_count != rb_gc_count()) {
2373 rb_bug("GC must not occur during the subclass iteration of Module#descendants");
2374 }
2375 st_free_table(data.visited);
2376
2377 return data.buffer;
2378}
2379
2380/*
2381 * call-seq:
2382 * attached_object -> object
2383 *
2384 * Returns the object for which the receiver is the singleton class.
2385 *
2386 * Raises an TypeError if the class is not a singleton class.
2387 *
2388 * Raises a Ractor::IsolationError if the attached object is not shareable and
2389 * belongs to another Ractor.
2390 *
2391 * class Foo; end
2392 *
2393 * Foo.singleton_class.attached_object #=> Foo
2394 * Foo.attached_object #=> TypeError: `Foo' is not a singleton class
2395 * Foo.new.singleton_class.attached_object #=> #<Foo:0x000000010491a370>
2396 * TrueClass.attached_object #=> TypeError: `TrueClass' is not a singleton class
2397 * NilClass.attached_object #=> TypeError: `NilClass' is not a singleton class
2398 */
2399
2400VALUE
2402{
2403 if (!RCLASS_SINGLETON_P(klass)) {
2404 rb_raise(rb_eTypeError, "'%"PRIsVALUE"' is not a singleton class", klass);
2405 }
2406
2407 const VALUE obj = RCLASS_ATTACHED_OBJECT(klass);
2408
2409 /* A singleton class is shareable whatever it is attached to, so another Ractor can
2410 * hold one attached to an unshareable object. Returning it would share it. */
2411 if (rb_objspace_foreign_object_p(obj) && !RB_OBJ_SHAREABLE_P(obj)) {
2412 /* No klass in the message: naming a singleton class inspects the very object we
2413 * must not touch from here. */
2414 rb_raise(rb_eRactorIsolationError,
2415 "can not get an unshareable attached object from another Ractor");
2416 }
2417
2418 return obj;
2419}
2420
2421static void
2422ins_methods_push(st_data_t name, st_data_t ary)
2423{
2424 rb_ary_push((VALUE)ary, ID2SYM((ID)name));
2425}
2426
2427static int
2428ins_methods_i(st_data_t name, st_data_t type, st_data_t ary)
2429{
2430 switch ((rb_method_visibility_t)type) {
2431 case METHOD_VISI_UNDEF:
2432 case METHOD_VISI_PRIVATE:
2433 break;
2434 default: /* everything but private */
2435 ins_methods_push(name, ary);
2436 break;
2437 }
2438 return ST_CONTINUE;
2439}
2440
2441static int
2442ins_methods_type_i(st_data_t name, st_data_t type, st_data_t ary, rb_method_visibility_t visi)
2443{
2444 if ((rb_method_visibility_t)type == visi) {
2445 ins_methods_push(name, ary);
2446 }
2447 return ST_CONTINUE;
2448}
2449
2450static int
2451ins_methods_prot_i(st_data_t name, st_data_t type, st_data_t ary)
2452{
2453 return ins_methods_type_i(name, type, ary, METHOD_VISI_PROTECTED);
2454}
2455
2456static int
2457ins_methods_priv_i(st_data_t name, st_data_t type, st_data_t ary)
2458{
2459 return ins_methods_type_i(name, type, ary, METHOD_VISI_PRIVATE);
2460}
2461
2462static int
2463ins_methods_pub_i(st_data_t name, st_data_t type, st_data_t ary)
2464{
2465 return ins_methods_type_i(name, type, ary, METHOD_VISI_PUBLIC);
2466}
2467
2468static int
2469ins_methods_undef_i(st_data_t name, st_data_t type, st_data_t ary)
2470{
2471 return ins_methods_type_i(name, type, ary, METHOD_VISI_UNDEF);
2472}
2473
2475 st_table *list;
2476 int recur;
2477};
2478
2479static enum rb_id_table_iterator_result
2480method_entry_i(ID key, VALUE value, void *data)
2481{
2482 const rb_method_entry_t *me = (const rb_method_entry_t *)value;
2483 struct method_entry_arg *arg = (struct method_entry_arg *)data;
2484 rb_method_visibility_t type;
2485
2486 if (me->def->type == VM_METHOD_TYPE_REFINED) {
2487 VALUE owner = me->owner;
2488 me = rb_resolve_refined_method(Qnil, me);
2489 if (!me) return ID_TABLE_CONTINUE;
2490 if (!arg->recur && me->owner != owner) return ID_TABLE_CONTINUE;
2491 }
2492 if (!st_is_member(arg->list, key)) {
2493 if (UNDEFINED_METHOD_ENTRY_P(me)) {
2494 type = METHOD_VISI_UNDEF; /* none */
2495 }
2496 else {
2497 type = METHOD_ENTRY_VISI(me);
2498 RUBY_ASSERT(type != METHOD_VISI_UNDEF);
2499 }
2500 st_add_direct(arg->list, key, (st_data_t)type);
2501 }
2502 return ID_TABLE_CONTINUE;
2503}
2504
2505static void
2506add_instance_method_list(VALUE mod, struct method_entry_arg *me_arg)
2507{
2508 struct rb_id_table *m_tbl = RCLASS_M_TBL(mod);
2509 if (!m_tbl) return;
2510 rb_id_table_foreach(m_tbl, method_entry_i, me_arg);
2511}
2512
2513static bool
2514particular_class_p(VALUE mod)
2515{
2516 if (!mod) return false;
2517 if (RCLASS_SINGLETON_P(mod)) return true;
2518 if (BUILTIN_TYPE(mod) == T_ICLASS) return true;
2519 return false;
2520}
2521
2522static VALUE
2523class_instance_method_list(int argc, const VALUE *argv, VALUE mod, int obj, int (*func) (st_data_t, st_data_t, st_data_t))
2524{
2525 VALUE ary;
2526 int recur = TRUE, prepended = 0;
2527 struct method_entry_arg me_arg;
2528
2529 if (rb_check_arity(argc, 0, 1)) recur = RTEST(argv[0]);
2530
2531 me_arg.list = st_init_numtable();
2532 me_arg.recur = recur;
2533
2534 if (obj) {
2535 for (; particular_class_p(mod); mod = RCLASS_SUPER(mod)) {
2536 add_instance_method_list(mod, &me_arg);
2537 }
2538 }
2539
2540 if (!recur && RCLASS_ORIGIN(mod) != mod) {
2541 mod = RCLASS_ORIGIN(mod);
2542 prepended = 1;
2543 }
2544
2545 for (; mod; mod = RCLASS_SUPER(mod)) {
2546 add_instance_method_list(mod, &me_arg);
2547 if (BUILTIN_TYPE(mod) == T_ICLASS && !prepended) continue;
2548 if (!recur) break;
2549 }
2550 ary = rb_ary_new2(me_arg.list->num_entries);
2551 st_foreach(me_arg.list, func, ary);
2552 st_free_table(me_arg.list);
2553
2554 return ary;
2555}
2556
2557/*
2558 * call-seq:
2559 * mod.instance_methods(include_super=true) -> array
2560 *
2561 * Returns an array containing the names of the public and protected instance
2562 * methods in the receiver. For a module, these are the public and protected methods;
2563 * for a class, they are the instance (not singleton) methods. If the optional
2564 * parameter is <code>false</code>, the methods of any ancestors are not included.
2565 *
2566 * module A
2567 * def method1() end
2568 * end
2569 * class B
2570 * include A
2571 * def method2() end
2572 * end
2573 * class C < B
2574 * def method3() end
2575 * end
2576 *
2577 * A.instance_methods(false) #=> [:method1]
2578 * B.instance_methods(false) #=> [:method2]
2579 * B.instance_methods(true).include?(:method1) #=> true
2580 * C.instance_methods(false) #=> [:method3]
2581 * C.instance_methods.include?(:method2) #=> true
2582 *
2583 * Note that method visibility changes in the current class, as well as aliases,
2584 * are considered as methods of the current class by this method:
2585 *
2586 * class C < B
2587 * alias method4 method2
2588 * protected :method2
2589 * end
2590 * C.instance_methods(false).sort #=> [:method2, :method3, :method4]
2591 */
2592
2593VALUE
2594rb_class_instance_methods(int argc, const VALUE *argv, VALUE mod)
2595{
2596 return class_instance_method_list(argc, argv, mod, 0, ins_methods_i);
2597}
2598
2599/*
2600 * call-seq:
2601 * mod.protected_instance_methods(include_super=true) -> array
2602 *
2603 * Returns a list of the protected instance methods defined in
2604 * <i>mod</i>. If the optional parameter is <code>false</code>, the
2605 * methods of any ancestors are not included.
2606 */
2607
2608VALUE
2610{
2611 return class_instance_method_list(argc, argv, mod, 0, ins_methods_prot_i);
2612}
2613
2614/*
2615 * call-seq:
2616 * mod.private_instance_methods(include_super=true) -> array
2617 *
2618 * Returns a list of the private instance methods defined in
2619 * <i>mod</i>. If the optional parameter is <code>false</code>, the
2620 * methods of any ancestors are not included.
2621 *
2622 * module Mod
2623 * def method1() end
2624 * private :method1
2625 * def method2() end
2626 * end
2627 * Mod.instance_methods #=> [:method2]
2628 * Mod.private_instance_methods #=> [:method1]
2629 */
2630
2631VALUE
2633{
2634 return class_instance_method_list(argc, argv, mod, 0, ins_methods_priv_i);
2635}
2636
2637/*
2638 * call-seq:
2639 * mod.public_instance_methods(include_super=true) -> array
2640 *
2641 * Returns a list of the public instance methods defined in <i>mod</i>.
2642 * If the optional parameter is <code>false</code>, the methods of
2643 * any ancestors are not included.
2644 */
2645
2646VALUE
2648{
2649 return class_instance_method_list(argc, argv, mod, 0, ins_methods_pub_i);
2650}
2651
2652/*
2653 * call-seq:
2654 * mod.undefined_instance_methods -> array
2655 *
2656 * Returns a list of the undefined instance methods defined in <i>mod</i>.
2657 * The undefined methods of any ancestors are not included.
2658 */
2659
2660VALUE
2661rb_class_undefined_instance_methods(VALUE mod)
2662{
2663 VALUE include_super = Qfalse;
2664 return class_instance_method_list(1, &include_super, mod, 0, ins_methods_undef_i);
2665}
2666
2667/*
2668 * call-seq:
2669 * obj.methods(regular=true) -> array
2670 *
2671 * Returns a list of the names of public and protected methods of
2672 * <i>obj</i>. This will include all the methods accessible in
2673 * <i>obj</i>'s ancestors.
2674 * If the optional parameter is <code>false</code>, it
2675 * returns an array of <i>obj</i>'s public and protected singleton methods,
2676 * the array will not include methods in modules included in <i>obj</i>.
2677 *
2678 * class Klass
2679 * def klass_method()
2680 * end
2681 * end
2682 * k = Klass.new
2683 * k.methods[0..9] #=> [:klass_method, :nil?, :===,
2684 * # :==~, :!, :eql?
2685 * # :hash, :<=>, :class, :singleton_class]
2686 * k.methods.length #=> 56
2687 *
2688 * k.methods(false) #=> []
2689 * def k.singleton_method; end
2690 * k.methods(false) #=> [:singleton_method]
2691 *
2692 * module M123; def m123; end end
2693 * k.extend M123
2694 * k.methods(false) #=> [:singleton_method]
2695 */
2696
2697VALUE
2698rb_obj_methods(int argc, const VALUE *argv, VALUE obj)
2699{
2700 rb_check_arity(argc, 0, 1);
2701 if (argc > 0 && !RTEST(argv[0])) {
2702 return rb_obj_singleton_methods(argc, argv, obj);
2703 }
2704 return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_i);
2705}
2706
2707/*
2708 * call-seq:
2709 * obj.protected_methods(all=true) -> array
2710 *
2711 * Returns the list of protected methods accessible to <i>obj</i>. If
2712 * the <i>all</i> parameter is set to <code>false</code>, only those methods
2713 * in the receiver will be listed.
2714 */
2715
2716VALUE
2717rb_obj_protected_methods(int argc, const VALUE *argv, VALUE obj)
2718{
2719 return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_prot_i);
2720}
2721
2722/*
2723 * call-seq:
2724 * obj.private_methods(all=true) -> array
2725 *
2726 * Returns the list of private methods accessible to <i>obj</i>. If
2727 * the <i>all</i> parameter is set to <code>false</code>, only those methods
2728 * in the receiver will be listed.
2729 */
2730
2731VALUE
2732rb_obj_private_methods(int argc, const VALUE *argv, VALUE obj)
2733{
2734 return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_priv_i);
2735}
2736
2737/*
2738 * call-seq:
2739 * obj.public_methods(all=true) -> array
2740 *
2741 * Returns the list of public methods accessible to <i>obj</i>. If
2742 * the <i>all</i> parameter is set to <code>false</code>, only those methods
2743 * in the receiver will be listed.
2744 */
2745
2746VALUE
2747rb_obj_public_methods(int argc, const VALUE *argv, VALUE obj)
2748{
2749 return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_pub_i);
2750}
2751
2752/*
2753 * call-seq:
2754 * obj.singleton_methods(all=true) -> array
2755 *
2756 * Returns an array of the names of singleton methods for <i>obj</i>.
2757 * If the optional <i>all</i> parameter is true, the list will include
2758 * methods in modules included in <i>obj</i>.
2759 * Only public and protected singleton methods are returned.
2760 *
2761 * module Other
2762 * def three() end
2763 * end
2764 *
2765 * class Single
2766 * def Single.four() end
2767 * end
2768 *
2769 * a = Single.new
2770 *
2771 * def a.one()
2772 * end
2773 *
2774 * class << a
2775 * include Other
2776 * def two()
2777 * end
2778 * end
2779 *
2780 * Single.singleton_methods #=> [:four]
2781 * a.singleton_methods(false) #=> [:two, :one]
2782 * a.singleton_methods #=> [:two, :one, :three]
2783 */
2784
2785VALUE
2786rb_obj_singleton_methods(int argc, const VALUE *argv, VALUE obj)
2787{
2788 VALUE ary, klass, origin;
2789 struct method_entry_arg me_arg;
2790 struct rb_id_table *mtbl;
2791 int recur = TRUE;
2792
2793 if (rb_check_arity(argc, 0, 1)) recur = RTEST(argv[0]);
2794 if (RB_TYPE_P(obj, T_CLASS) && RCLASS_SINGLETON_P(obj)) {
2795 rb_singleton_class(obj);
2796 }
2797 klass = CLASS_OF(obj);
2798 origin = RCLASS_ORIGIN(klass);
2799 me_arg.list = st_init_numtable();
2800 me_arg.recur = recur;
2801 if (klass && RCLASS_SINGLETON_P(klass)) {
2802 if ((mtbl = RCLASS_M_TBL(origin)) != 0) rb_id_table_foreach(mtbl, method_entry_i, &me_arg);
2803 klass = RCLASS_SUPER(klass);
2804 }
2805 if (recur) {
2806 while (klass && (RCLASS_SINGLETON_P(klass) || RB_TYPE_P(klass, T_ICLASS))) {
2807 if (klass != origin && (mtbl = RCLASS_M_TBL(klass)) != 0) rb_id_table_foreach(mtbl, method_entry_i, &me_arg);
2808 klass = RCLASS_SUPER(klass);
2809 }
2810 }
2811 ary = rb_ary_new2(me_arg.list->num_entries);
2812 st_foreach(me_arg.list, ins_methods_i, ary);
2813 st_free_table(me_arg.list);
2814
2815 return ary;
2816}
2817
2826#ifdef rb_define_method_id
2827#undef rb_define_method_id
2828#endif
2829void
2830rb_define_method_id(VALUE klass, ID mid, VALUE (*func)(ANYARGS), int argc)
2831{
2832 rb_add_method_cfunc(klass, mid, func, argc, METHOD_VISI_PUBLIC);
2833}
2834
2835#ifdef rb_define_method
2836#undef rb_define_method
2837#endif
2838void
2839rb_define_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc)
2840{
2841 rb_add_method_cfunc(klass, rb_intern(name), func, argc, METHOD_VISI_PUBLIC);
2842}
2843
2844#ifdef rb_define_protected_method
2845#undef rb_define_protected_method
2846#endif
2847void
2848rb_define_protected_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc)
2849{
2850 rb_add_method_cfunc(klass, rb_intern(name), func, argc, METHOD_VISI_PROTECTED);
2851}
2852
2853#ifdef rb_define_private_method
2854#undef rb_define_private_method
2855#endif
2856void
2857rb_define_private_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc)
2858{
2859 rb_add_method_cfunc(klass, rb_intern(name), func, argc, METHOD_VISI_PRIVATE);
2860}
2861
2862void
2863rb_undef_method(VALUE klass, const char *name)
2864{
2865 rb_add_method(klass, rb_intern(name), VM_METHOD_TYPE_UNDEF, 0, METHOD_VISI_UNDEF);
2866}
2867
2868static enum rb_id_table_iterator_result
2869undef_method_i(ID name, VALUE value, void *data)
2870{
2871 VALUE klass = (VALUE)data;
2872 rb_add_method(klass, name, VM_METHOD_TYPE_UNDEF, 0, METHOD_VISI_UNDEF);
2873 return ID_TABLE_CONTINUE;
2874}
2875
2876void
2877rb_undef_methods_from(VALUE klass, VALUE super)
2878{
2879 struct rb_id_table *mtbl = RCLASS_M_TBL(super);
2880 if (mtbl) {
2881 rb_id_table_foreach(mtbl, undef_method_i, (void *)klass);
2882 }
2883}
2884
2893static inline VALUE
2894special_singleton_class_of(VALUE obj)
2895{
2896 switch (obj) {
2897 case Qnil: return rb_cNilClass;
2898 case Qfalse: return rb_cFalseClass;
2899 case Qtrue: return rb_cTrueClass;
2900 default: return Qnil;
2901 }
2902}
2903
2904VALUE
2905rb_special_singleton_class(VALUE obj)
2906{
2907 return special_singleton_class_of(obj);
2908}
2909
2919static VALUE
2920singleton_class_of(VALUE obj, bool ensure_eigenclass)
2921{
2922 VALUE klass;
2923
2924 switch (TYPE(obj)) {
2925 case T_FIXNUM:
2926 case T_BIGNUM:
2927 case T_FLOAT:
2928 case T_SYMBOL:
2929 rb_raise(rb_eTypeError, "can't define singleton");
2930
2931 case T_FALSE:
2932 case T_TRUE:
2933 case T_NIL:
2934 klass = special_singleton_class_of(obj);
2935 if (NIL_P(klass))
2936 rb_bug("unknown immediate %p", (void *)obj);
2937 return klass;
2938
2939 case T_STRING:
2940 if (CHILLED_STRING_P(obj)) {
2941 CHILLED_STRING_MUTATED(obj);
2942 }
2943 else if (FL_TEST_RAW(obj, RSTRING_FSTR)) {
2944 rb_raise(rb_eTypeError, "can't define singleton");
2945 }
2946 }
2947
2948 bool needs_lock = rb_multi_ractor_p() && rb_ractor_shareable_p(obj);
2949 unsigned int lev;
2950 if (needs_lock) {
2951 RB_VM_LOCK_ENTER_LEV(&lev);
2952 }
2953 {
2954 klass = METACLASS_OF(obj);
2955 if (!(RCLASS_SINGLETON_P(klass) &&
2956 RCLASS_ATTACHED_OBJECT(klass) == obj)) {
2957 klass = rb_make_metaclass(obj, klass);
2958 }
2959 if (RB_OBJ_FROZEN_RAW(obj)) {
2960 // Freeze through rb_obj_freeze_inline so the singleton class also
2961 // gets a frozen shape_id, not just the FL_FREEZE flag.
2962 rb_obj_freeze_inline(klass);
2963 }
2964 if (ensure_eigenclass && RB_TYPE_P(obj, T_CLASS)) {
2965 /* ensures an exposed class belongs to its own eigenclass */
2966 (void)ENSURE_EIGENCLASS(klass);
2967 }
2968 }
2969 if (needs_lock) {
2970 RB_VM_LOCK_LEAVE_LEV(&lev);
2971 }
2972
2973 return klass;
2974}
2975
2976#if RUBY_VERSION_SINCE(4, 2)
2977RBIMPL_TODO("make rb_freeze_singleton_class internal; remove from fl_type.h")
2978#endif
2979void
2981{
2982 VALUE klass;
2983
2984 /* Freeze singleton classes of singleton class, as singleton class is frozen, and so on */
2985 /* In each iteration, check the current object's class pointer is the singleton class of the object. */
2986 while ((klass = RBASIC_CLASS(attached_object)) &&
2987 FL_TEST_RAW(klass, FL_SINGLETON) &&
2988 !OBJ_FROZEN_RAW(klass) &&
2989 (RCLASS_ATTACHED_OBJECT(klass) == attached_object)) {
2990 attached_object = klass;
2991 OBJ_FREEZE(attached_object);
2992 }
2993}
2994
3002VALUE
3004{
3005 VALUE klass;
3006
3007 if (SPECIAL_CONST_P(obj)) {
3008 return rb_special_singleton_class(obj);
3009 }
3010 klass = METACLASS_OF(obj);
3011 if (!RCLASS_SINGLETON_P(klass)) return Qnil;
3012 if (RCLASS_ATTACHED_OBJECT(klass) != obj) return Qnil;
3013 return klass;
3014}
3015
3016VALUE
3018{
3019 return singleton_class_of(obj, true);
3020}
3021
3031#ifdef rb_define_singleton_method
3032#undef rb_define_singleton_method
3033#endif
3034void
3035rb_define_singleton_method(VALUE obj, const char *name, VALUE (*func)(ANYARGS), int argc)
3036{
3037 rb_define_method(singleton_class_of(obj, false), name, func, argc);
3038}
3039
3040#ifdef rb_define_module_function
3041#undef rb_define_module_function
3042#endif
3043void
3044rb_define_module_function(VALUE module, const char *name, VALUE (*func)(ANYARGS), int argc)
3045{
3046 rb_define_private_method(module, name, func, argc);
3047 rb_define_singleton_method(module, name, func, argc);
3048}
3049
3050#ifdef rb_define_global_function
3051#undef rb_define_global_function
3052#endif
3053void
3054rb_define_global_function(const char *name, VALUE (*func)(ANYARGS), int argc)
3055{
3056 rb_define_module_function(rb_mKernel, name, func, argc);
3057}
3058
3059void
3060rb_define_alias(VALUE klass, const char *name1, const char *name2)
3061{
3062 rb_alias(klass, rb_intern(name1), rb_intern(name2));
3063}
3064
3065void
3066rb_define_attr(VALUE klass, const char *name, int read, int write)
3067{
3068 rb_attr(klass, rb_intern(name), read, write, FALSE);
3069}
3070
3071VALUE
3072rb_keyword_error_new(const char *error, VALUE keys)
3073{
3074 rb_len_t i = 0, len = RARRAY_LEN(keys);
3075 VALUE error_message = rb_sprintf("%s keyword%.*s", error, len > 1, "s");
3076
3077 if (len > 0) {
3078 rb_str_cat_cstr(error_message, ": ");
3079 while (1) {
3080 const VALUE k = RARRAY_AREF(keys, i);
3081 rb_str_append(error_message, rb_inspect(k));
3082 if (++i >= len) break;
3083 rb_str_cat_cstr(error_message, ", ");
3084 }
3085 }
3086
3087 return rb_exc_new_str(rb_eArgError, error_message);
3088}
3089
3090NORETURN(static void rb_keyword_error(const char *error, VALUE keys));
3091static void
3092rb_keyword_error(const char *error, VALUE keys)
3093{
3094 rb_exc_raise(rb_keyword_error_new(error, keys));
3095}
3096
3097NORETURN(static void unknown_keyword_error(VALUE hash, const ID *table, int keywords));
3098static void
3099unknown_keyword_error(VALUE hash, const ID *table, int keywords)
3100{
3101 int i;
3102 for (i = 0; i < keywords; i++) {
3103 st_data_t key = ID2SYM(table[i]);
3104 rb_hash_stlike_delete(hash, &key, NULL);
3105 }
3106 rb_keyword_error("unknown", rb_hash_keys(hash));
3107}
3108
3109
3110static int
3111separate_symbol(st_data_t key, st_data_t value, st_data_t arg)
3112{
3113 VALUE *kwdhash = (VALUE *)arg;
3114 if (!SYMBOL_P(key)) kwdhash++;
3115 if (!*kwdhash) *kwdhash = rb_hash_new();
3116 rb_hash_aset(*kwdhash, (VALUE)key, (VALUE)value);
3117 return ST_CONTINUE;
3118}
3119
3120VALUE
3122{
3123 VALUE parthash[2] = {0, 0};
3124 VALUE hash = *orighash;
3125
3126 if (RHASH_EMPTY_P(hash)) {
3127 *orighash = 0;
3128 return hash;
3129 }
3130 rb_hash_foreach(hash, separate_symbol, (st_data_t)&parthash);
3131 *orighash = parthash[1];
3132 if (parthash[1] && RBASIC_CLASS(hash) != rb_cHash) {
3133 RBASIC_SET_CLASS(parthash[1], RBASIC_CLASS(hash));
3134 }
3135 return parthash[0];
3136}
3137
3138int
3139rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
3140{
3141 int i = 0, j;
3142 int rest = 0;
3143 VALUE missing = Qnil;
3144 st_data_t key;
3145
3146#define extract_kwarg(keyword, val) \
3147 (key = (st_data_t)(keyword), values ? \
3148 (rb_hash_stlike_delete(keyword_hash, &key, &(val)) || ((val) = Qundef, 0)) : \
3149 rb_hash_stlike_lookup(keyword_hash, key, NULL))
3150
3151 if (NIL_P(keyword_hash)) keyword_hash = 0;
3152
3153 if (optional < 0) {
3154 rest = 1;
3155 optional = -1-optional;
3156 }
3157 if (required) {
3158 for (; i < required; i++) {
3159 VALUE keyword = ID2SYM(table[i]);
3160 if (keyword_hash) {
3161 if (extract_kwarg(keyword, values[i])) {
3162 continue;
3163 }
3164 }
3165 if (NIL_P(missing)) missing = rb_ary_hidden_new(1);
3166 rb_ary_push(missing, keyword);
3167 }
3168 if (!NIL_P(missing)) {
3169 rb_keyword_error("missing", missing);
3170 }
3171 }
3172 j = i;
3173 if (optional && keyword_hash) {
3174 for (i = 0; i < optional; i++) {
3175 if (extract_kwarg(ID2SYM(table[required+i]), values[required+i])) {
3176 j++;
3177 }
3178 }
3179 }
3180 if (!rest && keyword_hash) {
3181 if (RHASH_SIZE(keyword_hash) > (unsigned int)(values ? 0 : j)) {
3182 unknown_keyword_error(keyword_hash, table, required+optional);
3183 }
3184 }
3185 if (values && !keyword_hash) {
3186 for (i = 0; i < required + optional; i++) {
3187 values[i] = Qundef;
3188 }
3189 }
3190 return j;
3191#undef extract_kwarg
3192}
3193
3195 int kw_flag;
3196 int n_lead;
3197 int n_opt;
3198 int n_trail;
3199 bool f_var;
3200 bool f_hash;
3201 bool f_block;
3202};
3203
3204static void
3205rb_scan_args_parse(int kw_flag, const char *fmt, struct rb_scan_args_t *arg)
3206{
3207 const char *p = fmt;
3208
3209 memset(arg, 0, sizeof(*arg));
3210 arg->kw_flag = kw_flag;
3211
3212 if (ISDIGIT(*p)) {
3213 arg->n_lead = *p - '0';
3214 p++;
3215 if (ISDIGIT(*p)) {
3216 arg->n_opt = *p - '0';
3217 p++;
3218 }
3219 }
3220 if (*p == '*') {
3221 arg->f_var = 1;
3222 p++;
3223 }
3224 if (ISDIGIT(*p)) {
3225 arg->n_trail = *p - '0';
3226 p++;
3227 }
3228 if (*p == ':') {
3229 arg->f_hash = 1;
3230 p++;
3231 }
3232 if (*p == '&') {
3233 arg->f_block = 1;
3234 p++;
3235 }
3236 if (*p != '\0') {
3237 rb_fatal("bad scan arg format: %s", fmt);
3238 }
3239}
3240
3241static int
3242rb_scan_args_assign(const struct rb_scan_args_t *arg, int argc, const VALUE *const argv, va_list vargs)
3243{
3244 int i, argi = 0;
3245 VALUE *var, hash = Qnil;
3246#define rb_scan_args_next_param() va_arg(vargs, VALUE *)
3247 const int kw_flag = arg->kw_flag;
3248 const int n_lead = arg->n_lead;
3249 const int n_opt = arg->n_opt;
3250 const int n_trail = arg->n_trail;
3251 const int n_mand = n_lead + n_trail;
3252 const bool f_var = arg->f_var;
3253 const bool f_hash = arg->f_hash;
3254 const bool f_block = arg->f_block;
3255
3256 /* capture an option hash - phase 1: pop from the argv */
3257 if (f_hash && argc > 0) {
3258 VALUE last = argv[argc - 1];
3259 if (rb_scan_args_keyword_p(kw_flag, last)) {
3260 hash = rb_hash_dup(last);
3261 argc--;
3262 }
3263 }
3264
3265 if (argc < n_mand) {
3266 goto argc_error;
3267 }
3268
3269 /* capture leading mandatory arguments */
3270 for (i = 0; i < n_lead; i++) {
3271 var = rb_scan_args_next_param();
3272 if (var) *var = argv[argi];
3273 argi++;
3274 }
3275 /* capture optional arguments */
3276 for (i = 0; i < n_opt; i++) {
3277 var = rb_scan_args_next_param();
3278 if (argi < argc - n_trail) {
3279 if (var) *var = argv[argi];
3280 argi++;
3281 }
3282 else {
3283 if (var) *var = Qnil;
3284 }
3285 }
3286 /* capture variable length arguments */
3287 if (f_var) {
3288 int n_var = argc - argi - n_trail;
3289
3290 var = rb_scan_args_next_param();
3291 if (0 < n_var) {
3292 if (var) *var = rb_ary_new_from_values(n_var, &argv[argi]);
3293 argi += n_var;
3294 }
3295 else {
3296 if (var) *var = rb_ary_new();
3297 }
3298 }
3299 /* capture trailing mandatory arguments */
3300 for (i = 0; i < n_trail; i++) {
3301 var = rb_scan_args_next_param();
3302 if (var) *var = argv[argi];
3303 argi++;
3304 }
3305 /* capture an option hash - phase 2: assignment */
3306 if (f_hash) {
3307 var = rb_scan_args_next_param();
3308 if (var) *var = hash;
3309 }
3310 /* capture iterator block */
3311 if (f_block) {
3312 var = rb_scan_args_next_param();
3313 if (rb_block_given_p()) {
3314 *var = rb_block_proc();
3315 }
3316 else {
3317 *var = Qnil;
3318 }
3319 }
3320
3321 if (argi == argc) {
3322 return argc;
3323 }
3324
3325 argc_error:
3326 return -(argc + 1);
3327#undef rb_scan_args_next_param
3328}
3329
3330static int
3331rb_scan_args_result(const struct rb_scan_args_t *const arg, int argc)
3332{
3333 const int n_lead = arg->n_lead;
3334 const int n_opt = arg->n_opt;
3335 const int n_trail = arg->n_trail;
3336 const int n_mand = n_lead + n_trail;
3337 const bool f_var = arg->f_var;
3338
3339 if (argc >= 0) {
3340 return argc;
3341 }
3342
3343 argc = -argc - 1;
3344 rb_error_arity(argc, n_mand, f_var ? UNLIMITED_ARGUMENTS : n_mand + n_opt);
3346}
3347
3348#undef rb_scan_args
3349int
3350rb_scan_args(int argc, const VALUE *argv, const char *fmt, ...)
3351{
3352 va_list vargs;
3353 struct rb_scan_args_t arg;
3354 rb_scan_args_parse(RB_SCAN_ARGS_PASS_CALLED_KEYWORDS, fmt, &arg);
3355 va_start(vargs,fmt);
3356 argc = rb_scan_args_assign(&arg, argc, argv, vargs);
3357 va_end(vargs);
3358 return rb_scan_args_result(&arg, argc);
3359}
3360
3361#undef rb_scan_args_kw
3362int
3363rb_scan_args_kw(int kw_flag, int argc, const VALUE *argv, const char *fmt, ...)
3364{
3365 va_list vargs;
3366 struct rb_scan_args_t arg;
3367 rb_scan_args_parse(kw_flag, fmt, &arg);
3368 va_start(vargs,fmt);
3369 argc = rb_scan_args_assign(&arg, argc, argv, vargs);
3370 va_end(vargs);
3371 return rb_scan_args_result(&arg, argc);
3372}
3373
#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
void rb_obj_freeze_inline(VALUE obj)
Prevents further modifications to the given object.
Definition variable.c:2106
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:2609
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:1736
VALUE rb_refinement_new(void)
Creates a new, anonymous refinement.
Definition class.c:1634
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:1338
VALUE rb_singleton_class_clone(VALUE obj)
Clones a singleton class.
Definition class.c:1173
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:1995
VALUE rb_class_subclasses(VALUE klass)
Queries the class's direct descendants.
Definition class.c:2259
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3017
VALUE rb_class_attached_object(VALUE klass)
Returns the attached object for a singleton class.
Definition class.c:2401
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:2786
VALUE rb_module_new(void)
Creates a new, anonymous module.
Definition class.c:1628
#define META_CLASS_OF_CLASS_CLASS_P(k)
whether k is a meta^(n)-class of Class class
Definition class.c:1255
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:2594
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:2647
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:1665
void rb_singleton_class_attached(VALUE klass, VALUE obj)
Attaches a singleton class to its corresponding object.
Definition class.c:1243
VALUE rb_mod_included_modules(VALUE mod)
Queries the list of included modules.
Definition class.c:2075
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:1604
VALUE rb_mod_ancestors(VALUE mod)
Queries the module's ancestors.
Definition class.c:2147
static VALUE make_metaclass(VALUE klass)
Creates a metaclass of klass
Definition class.c:1300
VALUE rb_class_inherited(VALUE super, VALUE klass)
Calls Class::inherited.
Definition class.c:1528
VALUE rb_mod_include_p(VALUE mod, VALUE mod2)
Queries if the passed module is included by the module.
Definition class.c:2111
void rb_freeze_singleton_class(VALUE attached_object)
This is an implementation detail of RB_OBJ_FREEZE().
Definition class.c:2980
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:2632
#define ENSURE_EIGENCLASS(klass)
ensures klass belongs to its own eigenclass.
Definition class.c:1286
VALUE rb_mod_init_copy(VALUE clone, VALUE orig)
The comment that comes with this function says :nodoc:.
Definition class.c:1055
VALUE rb_mod_descendants(VALUE mod)
Queries the module's descendants.
Definition class.c:2350
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:3003
VALUE rb_define_module_id(ID id)
This is a very badly designed API that creates an anonymous module.
Definition class.c:1641
VALUE rb_define_class_id(ID id, VALUE super)
This is a very badly designed API that creates an anonymous class.
Definition class.c:1507
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3060
VALUE rb_extract_keywords(VALUE *orighash)
Splits a hash into two.
Definition class.c:3121
void rb_define_attr(VALUE klass, const char *name, int read, int write)
Defines public accessor method(s) for an attribute.
Definition class.c:3066
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2863
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:3363
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:3350
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:3139
#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:403
#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:405
#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:1457
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:1508
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:2320
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:654
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:230
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:665
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:221
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:504
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
VALUE rb_ary_new_capa(rb_len_t capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_resize(VALUE ary, rb_len_t len)
Expands or shrinks the passed array to the passed length.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_hidden_new(rb_len_t capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_cat(VALUE ary, const VALUE *train, rb_len_t len)
Destructively appends multiple elements at the end of the array.
VALUE rb_ary_new_from_values(rb_len_t n, const VALUE *elts)
Identical to rb_ary_new_from_args(), except how objects are passed.
#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:1259
int rb_is_class_id(ID id)
Classifies the given ID, then sees if it is a class variable.
Definition symbol.c:1247
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:1580
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:4005
#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:1681
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:3998
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:3521
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:439
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:3856
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:396
void rb_alias(VALUE klass, ID dst, ID src)
Resembles alias.
Definition vm_method.c:3081
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:2548
void rb_clear_constant_cache_for_id(ID id)
Clears the inline constant caches associated with a particular ID.
Definition vm_method.c:334
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:375
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
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)
References an object in an array.
Definition rarray.h:421
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:57
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition rhash.h:67
#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:90
Definition class.c:2474
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
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
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