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