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