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