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