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