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