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