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