[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / class.c
blob5cce99e334d8b1aadcb38931d942ef5c48ba6f17
1 /**********************************************************************
3 class.c -
5 $Author$
6 created at: Tue Aug 10 15:05:44 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 /*!
13 * \addtogroup class
14 * \{
17 #include "ruby/internal/config.h"
18 #include <ctype.h>
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/object.h"
28 #include "internal/string.h"
29 #include "internal/variable.h"
30 #include "ruby/st.h"
31 #include "vm_core.h"
32 #include "yjit.h"
34 /* Flags of T_CLASS
36 * 0: RCLASS_IS_ROOT
37 * The class has been added to the VM roots. Will always be marked and pinned.
38 * This is done for classes defined from C to allow storing them in global variables.
39 * 1: RUBY_FL_SINGLETON
40 * This class is a singleton class.
41 * 2: RCLASS_SUPERCLASSES_INCLUDE_SELF
42 * The RCLASS_SUPERCLASSES contains the class as the last element.
43 * This means that this class owns the RCLASS_SUPERCLASSES list.
44 * if !SHAPE_IN_BASIC_FLAGS
45 * 4-19: SHAPE_FLAG_MASK
46 * Shape ID for the class.
47 * endif
50 /* Flags of T_ICLASS
52 * 0: RICLASS_IS_ORIGIN
53 * 3: RICLASS_ORIGIN_SHARED_MTBL
54 * The T_ICLASS does not own the method table.
55 * if !SHAPE_IN_BASIC_FLAGS
56 * 4-19: SHAPE_FLAG_MASK
57 * Shape ID. This is set but not used.
58 * endif
61 /* Flags of T_MODULE
63 * 0: RCLASS_IS_ROOT
64 * The class has been added to the VM roots. Will always be marked and pinned.
65 * This is done for classes defined from C to allow storing them in global variables.
66 * 1: RMODULE_ALLOCATED_BUT_NOT_INITIALIZED
67 * Module has not been initialized.
68 * 2: RCLASS_SUPERCLASSES_INCLUDE_SELF
69 * See RCLASS_SUPERCLASSES_INCLUDE_SELF in T_CLASS.
70 * 3: RMODULE_IS_REFINEMENT
71 * Module is used for refinements.
72 * if !SHAPE_IN_BASIC_FLAGS
73 * 4-19: SHAPE_FLAG_MASK
74 * Shape ID for the module.
75 * endif
78 #define METACLASS_OF(k) RBASIC(k)->klass
79 #define SET_METACLASS_OF(k, cls) RBASIC_SET_CLASS(k, cls)
81 RUBY_EXTERN rb_serial_t ruby_vm_global_cvar_state;
83 static rb_subclass_entry_t *
84 push_subclass_entry_to_list(VALUE super, VALUE klass)
86 rb_subclass_entry_t *entry, *head;
88 entry = ZALLOC(rb_subclass_entry_t);
89 entry->klass = klass;
91 head = RCLASS_SUBCLASSES(super);
92 if (!head) {
93 head = ZALLOC(rb_subclass_entry_t);
94 RCLASS_SUBCLASSES(super) = head;
96 entry->next = head->next;
97 entry->prev = head;
99 if (head->next) {
100 head->next->prev = entry;
102 head->next = entry;
104 return entry;
107 void
108 rb_class_subclass_add(VALUE super, VALUE klass)
110 if (super && !UNDEF_P(super)) {
111 rb_subclass_entry_t *entry = push_subclass_entry_to_list(super, klass);
112 RCLASS_SUBCLASS_ENTRY(klass) = entry;
116 static void
117 rb_module_add_to_subclasses_list(VALUE module, VALUE iclass)
119 rb_subclass_entry_t *entry = push_subclass_entry_to_list(module, iclass);
120 RCLASS_MODULE_SUBCLASS_ENTRY(iclass) = entry;
123 void
124 rb_class_remove_subclass_head(VALUE klass)
126 rb_subclass_entry_t *head = RCLASS_SUBCLASSES(klass);
128 if (head) {
129 if (head->next) {
130 head->next->prev = NULL;
132 RCLASS_SUBCLASSES(klass) = NULL;
133 xfree(head);
137 void
138 rb_class_remove_from_super_subclasses(VALUE klass)
140 rb_subclass_entry_t *entry = RCLASS_SUBCLASS_ENTRY(klass);
142 if (entry) {
143 rb_subclass_entry_t *prev = entry->prev, *next = entry->next;
145 if (prev) {
146 prev->next = next;
148 if (next) {
149 next->prev = prev;
152 xfree(entry);
155 RCLASS_SUBCLASS_ENTRY(klass) = NULL;
158 void
159 rb_class_remove_from_module_subclasses(VALUE klass)
161 rb_subclass_entry_t *entry = RCLASS_MODULE_SUBCLASS_ENTRY(klass);
163 if (entry) {
164 rb_subclass_entry_t *prev = entry->prev, *next = entry->next;
166 if (prev) {
167 prev->next = next;
169 if (next) {
170 next->prev = prev;
173 xfree(entry);
176 RCLASS_MODULE_SUBCLASS_ENTRY(klass) = NULL;
179 void
180 rb_class_foreach_subclass(VALUE klass, void (*f)(VALUE, VALUE), VALUE arg)
182 // RCLASS_SUBCLASSES should always point to our head element which has NULL klass
183 rb_subclass_entry_t *cur = RCLASS_SUBCLASSES(klass);
184 // if we have a subclasses list, then the head is a placeholder with no valid
185 // class. So ignore it and use the next element in the list (if one exists)
186 if (cur) {
187 RUBY_ASSERT(!cur->klass);
188 cur = cur->next;
191 /* do not be tempted to simplify this loop into a for loop, the order of
192 operations is important here if `f` modifies the linked list */
193 while (cur) {
194 VALUE curklass = cur->klass;
195 cur = cur->next;
196 // do not trigger GC during f, otherwise the cur will become
197 // a dangling pointer if the subclass is collected
198 f(curklass, arg);
202 static void
203 class_detach_subclasses(VALUE klass, VALUE arg)
205 rb_class_remove_from_super_subclasses(klass);
208 void
209 rb_class_detach_subclasses(VALUE klass)
211 rb_class_foreach_subclass(klass, class_detach_subclasses, Qnil);
214 static void
215 class_detach_module_subclasses(VALUE klass, VALUE arg)
217 rb_class_remove_from_module_subclasses(klass);
220 void
221 rb_class_detach_module_subclasses(VALUE klass)
223 rb_class_foreach_subclass(klass, class_detach_module_subclasses, Qnil);
227 * Allocates a struct RClass for a new class.
229 * @param flags initial value for basic.flags of the returned class.
230 * @param klass the class of the returned class.
231 * @return an uninitialized Class object.
232 * @pre `klass` must refer `Class` class or an ancestor of Class.
233 * @pre `(flags | T_CLASS) != 0`
234 * @post the returned class can safely be `#initialize` 'd.
236 * @note this function is not Class#allocate.
238 static VALUE
239 class_alloc(VALUE flags, VALUE klass)
241 size_t alloc_size = sizeof(struct RClass) + sizeof(rb_classext_t);
243 flags &= T_MASK;
244 if (RGENGC_WB_PROTECTED_CLASS) flags |= FL_WB_PROTECTED;
245 NEWOBJ_OF(obj, struct RClass, klass, flags, alloc_size, 0);
247 memset(RCLASS_EXT(obj), 0, sizeof(rb_classext_t));
249 /* ZALLOC
250 RCLASS_CONST_TBL(obj) = 0;
251 RCLASS_M_TBL(obj) = 0;
252 RCLASS_IV_INDEX_TBL(obj) = 0;
253 RCLASS_SET_SUPER((VALUE)obj, 0);
254 RCLASS_SUBCLASSES(obj) = NULL;
255 RCLASS_PARENT_SUBCLASSES(obj) = NULL;
256 RCLASS_MODULE_SUBCLASSES(obj) = NULL;
258 RCLASS_SET_ORIGIN((VALUE)obj, (VALUE)obj);
259 RB_OBJ_WRITE(obj, &RCLASS_REFINED_CLASS(obj), Qnil);
260 RCLASS_SET_ALLOCATOR((VALUE)obj, 0);
262 return (VALUE)obj;
265 static void
266 RCLASS_M_TBL_INIT(VALUE c)
268 RCLASS_M_TBL(c) = rb_id_table_create(0);
272 * A utility function that wraps class_alloc.
274 * allocates a class and initializes safely.
275 * @param super a class from which the new class derives.
276 * @return a class object.
277 * @pre `super` must be a class.
278 * @post the metaclass of the new class is Class.
280 VALUE
281 rb_class_boot(VALUE super)
283 VALUE klass = class_alloc(T_CLASS, rb_cClass);
285 RCLASS_SET_SUPER(klass, super);
286 RCLASS_M_TBL_INIT(klass);
288 return (VALUE)klass;
291 static VALUE *
292 class_superclasses_including_self(VALUE klass)
294 if (FL_TEST_RAW(klass, RCLASS_SUPERCLASSES_INCLUDE_SELF))
295 return RCLASS_SUPERCLASSES(klass);
297 size_t depth = RCLASS_SUPERCLASS_DEPTH(klass);
298 VALUE *superclasses = xmalloc(sizeof(VALUE) * (depth + 1));
299 if (depth > 0)
300 memcpy(superclasses, RCLASS_SUPERCLASSES(klass), sizeof(VALUE) * depth);
301 superclasses[depth] = klass;
303 RCLASS_SUPERCLASSES(klass) = superclasses;
304 FL_SET_RAW(klass, RCLASS_SUPERCLASSES_INCLUDE_SELF);
305 return superclasses;
308 void
309 rb_class_update_superclasses(VALUE klass)
311 VALUE super = RCLASS_SUPER(klass);
313 if (!RB_TYPE_P(klass, T_CLASS)) return;
314 if (UNDEF_P(super)) return;
316 // If the superclass array is already built
317 if (RCLASS_SUPERCLASSES(klass))
318 return;
320 // find the proper superclass
321 while (super != Qfalse && !RB_TYPE_P(super, T_CLASS)) {
322 super = RCLASS_SUPER(super);
325 // For BasicObject and uninitialized classes, depth=0 and ary=NULL
326 if (super == Qfalse)
327 return;
329 // Sometimes superclasses are set before the full ancestry tree is built
330 // This happens during metaclass construction
331 if (super != rb_cBasicObject && !RCLASS_SUPERCLASS_DEPTH(super)) {
332 rb_class_update_superclasses(super);
334 // If it is still unset we need to try later
335 if (!RCLASS_SUPERCLASS_DEPTH(super))
336 return;
339 RCLASS_SUPERCLASSES(klass) = class_superclasses_including_self(super);
340 RCLASS_SUPERCLASS_DEPTH(klass) = RCLASS_SUPERCLASS_DEPTH(super) + 1;
343 void
344 rb_check_inheritable(VALUE super)
346 if (!RB_TYPE_P(super, T_CLASS)) {
347 rb_raise(rb_eTypeError, "superclass must be an instance of Class (given an instance of %"PRIsVALUE")",
348 rb_obj_class(super));
350 if (RCLASS_SINGLETON_P(super)) {
351 rb_raise(rb_eTypeError, "can't make subclass of singleton class");
353 if (super == rb_cClass) {
354 rb_raise(rb_eTypeError, "can't make subclass of Class");
358 VALUE
359 rb_class_new(VALUE super)
361 Check_Type(super, T_CLASS);
362 rb_check_inheritable(super);
363 VALUE klass = rb_class_boot(super);
365 if (super != rb_cObject && super != rb_cBasicObject) {
366 RCLASS_EXT(klass)->max_iv_count = RCLASS_EXT(super)->max_iv_count;
369 return klass;
372 VALUE
373 rb_class_s_alloc(VALUE klass)
375 return rb_class_boot(0);
378 static void
379 clone_method(VALUE old_klass, VALUE new_klass, ID mid, const rb_method_entry_t *me)
381 if (me->def->type == VM_METHOD_TYPE_ISEQ) {
382 rb_cref_t *new_cref;
383 rb_vm_rewrite_cref(me->def->body.iseq.cref, old_klass, new_klass, &new_cref);
384 rb_add_method_iseq(new_klass, mid, me->def->body.iseq.iseqptr, new_cref, METHOD_ENTRY_VISI(me));
386 else {
387 rb_method_entry_set(new_klass, mid, me, METHOD_ENTRY_VISI(me));
391 struct clone_method_arg {
392 VALUE new_klass;
393 VALUE old_klass;
396 static enum rb_id_table_iterator_result
397 clone_method_i(ID key, VALUE value, void *data)
399 const struct clone_method_arg *arg = (struct clone_method_arg *)data;
400 clone_method(arg->old_klass, arg->new_klass, key, (const rb_method_entry_t *)value);
401 return ID_TABLE_CONTINUE;
404 struct clone_const_arg {
405 VALUE klass;
406 struct rb_id_table *tbl;
409 static int
410 clone_const(ID key, const rb_const_entry_t *ce, struct clone_const_arg *arg)
412 rb_const_entry_t *nce = ALLOC(rb_const_entry_t);
413 MEMCPY(nce, ce, rb_const_entry_t, 1);
414 RB_OBJ_WRITTEN(arg->klass, Qundef, ce->value);
415 RB_OBJ_WRITTEN(arg->klass, Qundef, ce->file);
417 rb_id_table_insert(arg->tbl, key, (VALUE)nce);
418 return ID_TABLE_CONTINUE;
421 static enum rb_id_table_iterator_result
422 clone_const_i(ID key, VALUE value, void *data)
424 return clone_const(key, (const rb_const_entry_t *)value, data);
427 static void
428 class_init_copy_check(VALUE clone, VALUE orig)
430 if (orig == rb_cBasicObject) {
431 rb_raise(rb_eTypeError, "can't copy the root class");
433 if (RCLASS_SUPER(clone) != 0 || clone == rb_cBasicObject) {
434 rb_raise(rb_eTypeError, "already initialized class");
436 if (RCLASS_SINGLETON_P(orig)) {
437 rb_raise(rb_eTypeError, "can't copy singleton class");
441 struct cvc_table_copy_ctx {
442 VALUE clone;
443 struct rb_id_table * new_table;
446 static enum rb_id_table_iterator_result
447 cvc_table_copy(ID id, VALUE val, void *data)
449 struct cvc_table_copy_ctx *ctx = (struct cvc_table_copy_ctx *)data;
450 struct rb_cvar_class_tbl_entry * orig_entry;
451 orig_entry = (struct rb_cvar_class_tbl_entry *)val;
453 struct rb_cvar_class_tbl_entry *ent;
455 ent = ALLOC(struct rb_cvar_class_tbl_entry);
456 ent->class_value = ctx->clone;
457 ent->cref = orig_entry->cref;
458 ent->global_cvar_state = orig_entry->global_cvar_state;
459 rb_id_table_insert(ctx->new_table, id, (VALUE)ent);
461 RB_OBJ_WRITTEN(ctx->clone, Qundef, ent->cref);
463 return ID_TABLE_CONTINUE;
466 static void
467 copy_tables(VALUE clone, VALUE orig)
469 if (RCLASS_CONST_TBL(clone)) {
470 rb_free_const_table(RCLASS_CONST_TBL(clone));
471 RCLASS_CONST_TBL(clone) = 0;
473 if (RCLASS_CVC_TBL(orig)) {
474 struct rb_id_table *rb_cvc_tbl = RCLASS_CVC_TBL(orig);
475 struct rb_id_table *rb_cvc_tbl_dup = rb_id_table_create(rb_id_table_size(rb_cvc_tbl));
477 struct cvc_table_copy_ctx ctx;
478 ctx.clone = clone;
479 ctx.new_table = rb_cvc_tbl_dup;
480 rb_id_table_foreach(rb_cvc_tbl, cvc_table_copy, &ctx);
481 RCLASS_CVC_TBL(clone) = rb_cvc_tbl_dup;
483 rb_id_table_free(RCLASS_M_TBL(clone));
484 RCLASS_M_TBL(clone) = 0;
485 if (!RB_TYPE_P(clone, T_ICLASS)) {
486 st_data_t id;
488 rb_iv_tbl_copy(clone, orig);
489 CONST_ID(id, "__tmp_classpath__");
490 rb_attr_delete(clone, id);
491 CONST_ID(id, "__classpath__");
492 rb_attr_delete(clone, id);
494 if (RCLASS_CONST_TBL(orig)) {
495 struct clone_const_arg arg;
497 arg.tbl = RCLASS_CONST_TBL(clone) = rb_id_table_create(0);
498 arg.klass = clone;
499 rb_id_table_foreach(RCLASS_CONST_TBL(orig), clone_const_i, &arg);
503 static bool ensure_origin(VALUE klass);
506 * If this flag is set, that module is allocated but not initialized yet.
508 enum {RMODULE_ALLOCATED_BUT_NOT_INITIALIZED = RUBY_FL_USER1};
510 static inline bool
511 RMODULE_UNINITIALIZED(VALUE module)
513 return FL_TEST_RAW(module, RMODULE_ALLOCATED_BUT_NOT_INITIALIZED);
516 void
517 rb_module_set_initialized(VALUE mod)
519 FL_UNSET_RAW(mod, RMODULE_ALLOCATED_BUT_NOT_INITIALIZED);
520 /* no more re-initialization */
523 void
524 rb_module_check_initializable(VALUE mod)
526 if (!RMODULE_UNINITIALIZED(mod)) {
527 rb_raise(rb_eTypeError, "already initialized module");
531 /* :nodoc: */
532 VALUE
533 rb_mod_init_copy(VALUE clone, VALUE orig)
535 switch (BUILTIN_TYPE(clone)) {
536 case T_CLASS:
537 case T_ICLASS:
538 class_init_copy_check(clone, orig);
539 break;
540 case T_MODULE:
541 rb_module_check_initializable(clone);
542 break;
543 default:
544 break;
546 if (!OBJ_INIT_COPY(clone, orig)) return clone;
548 /* cloned flag is refer at constant inline cache
549 * see vm_get_const_key_cref() in vm_insnhelper.c
551 RCLASS_EXT(clone)->cloned = true;
552 RCLASS_EXT(orig)->cloned = true;
554 if (!RCLASS_SINGLETON_P(CLASS_OF(clone))) {
555 RBASIC_SET_CLASS(clone, rb_singleton_class_clone(orig));
556 rb_singleton_class_attached(METACLASS_OF(clone), (VALUE)clone);
558 RCLASS_SET_ALLOCATOR(clone, RCLASS_ALLOCATOR(orig));
559 copy_tables(clone, orig);
560 if (RCLASS_M_TBL(orig)) {
561 struct clone_method_arg arg;
562 arg.old_klass = orig;
563 arg.new_klass = clone;
564 RCLASS_M_TBL_INIT(clone);
565 rb_id_table_foreach(RCLASS_M_TBL(orig), clone_method_i, &arg);
568 if (RCLASS_ORIGIN(orig) == orig) {
569 RCLASS_SET_SUPER(clone, RCLASS_SUPER(orig));
571 else {
572 VALUE p = RCLASS_SUPER(orig);
573 VALUE orig_origin = RCLASS_ORIGIN(orig);
574 VALUE prev_clone_p = clone;
575 VALUE origin_stack = rb_ary_hidden_new(2);
576 VALUE origin[2];
577 VALUE clone_p = 0;
578 long origin_len;
579 int add_subclass;
580 VALUE clone_origin;
582 ensure_origin(clone);
583 clone_origin = RCLASS_ORIGIN(clone);
585 while (p && p != orig_origin) {
586 if (BUILTIN_TYPE(p) != T_ICLASS) {
587 rb_bug("non iclass between module/class and origin");
589 clone_p = class_alloc(RBASIC(p)->flags, METACLASS_OF(p));
590 /* We should set the m_tbl right after allocation before anything
591 * that can trigger GC to avoid clone_p from becoming old and
592 * needing to fire write barriers. */
593 RCLASS_SET_M_TBL(clone_p, RCLASS_M_TBL(p));
594 RCLASS_SET_SUPER(prev_clone_p, clone_p);
595 prev_clone_p = clone_p;
596 RCLASS_CONST_TBL(clone_p) = RCLASS_CONST_TBL(p);
597 RCLASS_SET_ALLOCATOR(clone_p, RCLASS_ALLOCATOR(p));
598 if (RB_TYPE_P(clone, T_CLASS)) {
599 RCLASS_SET_INCLUDER(clone_p, clone);
601 add_subclass = TRUE;
602 if (p != RCLASS_ORIGIN(p)) {
603 origin[0] = clone_p;
604 origin[1] = RCLASS_ORIGIN(p);
605 rb_ary_cat(origin_stack, origin, 2);
607 else if ((origin_len = RARRAY_LEN(origin_stack)) > 1 &&
608 RARRAY_AREF(origin_stack, origin_len - 1) == p) {
609 RCLASS_SET_ORIGIN(RARRAY_AREF(origin_stack, (origin_len -= 2)), clone_p);
610 RICLASS_SET_ORIGIN_SHARED_MTBL(clone_p);
611 rb_ary_resize(origin_stack, origin_len);
612 add_subclass = FALSE;
614 if (add_subclass) {
615 rb_module_add_to_subclasses_list(METACLASS_OF(p), clone_p);
617 p = RCLASS_SUPER(p);
620 if (p == orig_origin) {
621 if (clone_p) {
622 RCLASS_SET_SUPER(clone_p, clone_origin);
623 RCLASS_SET_SUPER(clone_origin, RCLASS_SUPER(orig_origin));
625 copy_tables(clone_origin, orig_origin);
626 if (RCLASS_M_TBL(orig_origin)) {
627 struct clone_method_arg arg;
628 arg.old_klass = orig;
629 arg.new_klass = clone;
630 RCLASS_M_TBL_INIT(clone_origin);
631 rb_id_table_foreach(RCLASS_M_TBL(orig_origin), clone_method_i, &arg);
634 else {
635 rb_bug("no origin for class that has origin");
638 rb_class_update_superclasses(clone);
641 return clone;
644 VALUE
645 rb_singleton_class_clone(VALUE obj)
647 return rb_singleton_class_clone_and_attach(obj, Qundef);
650 // Clone and return the singleton class of `obj` if it has been created and is attached to `obj`.
651 VALUE
652 rb_singleton_class_clone_and_attach(VALUE obj, VALUE attach)
654 const VALUE klass = METACLASS_OF(obj);
656 // Note that `rb_singleton_class()` can create situations where `klass` is
657 // attached to an object other than `obj`. In which case `obj` does not have
658 // a material singleton class attached yet and there is no singleton class
659 // to clone.
660 if (!(RCLASS_SINGLETON_P(klass) && RCLASS_ATTACHED_OBJECT(klass) == obj)) {
661 // nothing to clone
662 return klass;
664 else {
665 /* copy singleton(unnamed) class */
666 bool klass_of_clone_is_new;
667 VALUE clone = class_alloc(RBASIC(klass)->flags, 0);
669 if (BUILTIN_TYPE(obj) == T_CLASS) {
670 klass_of_clone_is_new = true;
671 RBASIC_SET_CLASS(clone, clone);
673 else {
674 VALUE klass_metaclass_clone = rb_singleton_class_clone(klass);
675 // When `METACLASS_OF(klass) == klass_metaclass_clone`, it means the
676 // recursive call did not clone `METACLASS_OF(klass)`.
677 klass_of_clone_is_new = (METACLASS_OF(klass) != klass_metaclass_clone);
678 RBASIC_SET_CLASS(clone, klass_metaclass_clone);
681 RCLASS_SET_SUPER(clone, RCLASS_SUPER(klass));
682 rb_iv_tbl_copy(clone, klass);
683 if (RCLASS_CONST_TBL(klass)) {
684 struct clone_const_arg arg;
685 arg.tbl = RCLASS_CONST_TBL(clone) = rb_id_table_create(0);
686 arg.klass = clone;
687 rb_id_table_foreach(RCLASS_CONST_TBL(klass), clone_const_i, &arg);
689 if (!UNDEF_P(attach)) {
690 rb_singleton_class_attached(clone, attach);
692 RCLASS_M_TBL_INIT(clone);
694 struct clone_method_arg arg;
695 arg.old_klass = klass;
696 arg.new_klass = clone;
697 rb_id_table_foreach(RCLASS_M_TBL(klass), clone_method_i, &arg);
699 if (klass_of_clone_is_new) {
700 rb_singleton_class_attached(METACLASS_OF(clone), clone);
702 FL_SET(clone, FL_SINGLETON);
704 return clone;
708 void
709 rb_singleton_class_attached(VALUE klass, VALUE obj)
711 if (RCLASS_SINGLETON_P(klass)) {
712 RCLASS_SET_ATTACHED_OBJECT(klass, obj);
717 * whether k is a meta^(n)-class of Class class
718 * @retval 1 if \a k is a meta^(n)-class of Class class (n >= 0)
719 * @retval 0 otherwise
721 #define META_CLASS_OF_CLASS_CLASS_P(k) (METACLASS_OF(k) == (k))
723 static int
724 rb_singleton_class_has_metaclass_p(VALUE sklass)
726 return RCLASS_ATTACHED_OBJECT(METACLASS_OF(sklass)) == sklass;
730 rb_singleton_class_internal_p(VALUE sklass)
732 return (RB_TYPE_P(RCLASS_ATTACHED_OBJECT(sklass), T_CLASS) &&
733 !rb_singleton_class_has_metaclass_p(sklass));
737 * whether k has a metaclass
738 * @retval 1 if \a k has a metaclass
739 * @retval 0 otherwise
741 #define HAVE_METACLASS_P(k) \
742 (FL_TEST(METACLASS_OF(k), FL_SINGLETON) && \
743 rb_singleton_class_has_metaclass_p(k))
746 * ensures `klass` belongs to its own eigenclass.
747 * @return the eigenclass of `klass`
748 * @post `klass` belongs to the returned eigenclass.
749 * i.e. the attached object of the eigenclass is `klass`.
750 * @note this macro creates a new eigenclass if necessary.
752 #define ENSURE_EIGENCLASS(klass) \
753 (HAVE_METACLASS_P(klass) ? METACLASS_OF(klass) : make_metaclass(klass))
757 * Creates a metaclass of `klass`
758 * @param klass a class
759 * @return created metaclass for the class
760 * @pre `klass` is a Class object
761 * @pre `klass` has no singleton class.
762 * @post the class of `klass` is the returned class.
763 * @post the returned class is meta^(n+1)-class when `klass` is a meta^(n)-klass for n >= 0
765 static inline VALUE
766 make_metaclass(VALUE klass)
768 VALUE super;
769 VALUE metaclass = rb_class_boot(Qundef);
771 FL_SET(metaclass, FL_SINGLETON);
772 rb_singleton_class_attached(metaclass, klass);
774 if (META_CLASS_OF_CLASS_CLASS_P(klass)) {
775 SET_METACLASS_OF(klass, metaclass);
776 SET_METACLASS_OF(metaclass, metaclass);
778 else {
779 VALUE tmp = METACLASS_OF(klass); /* for a meta^(n)-class klass, tmp is meta^(n)-class of Class class */
780 SET_METACLASS_OF(klass, metaclass);
781 SET_METACLASS_OF(metaclass, ENSURE_EIGENCLASS(tmp));
784 super = RCLASS_SUPER(klass);
785 while (RB_TYPE_P(super, T_ICLASS)) super = RCLASS_SUPER(super);
786 RCLASS_SET_SUPER(metaclass, super ? ENSURE_EIGENCLASS(super) : rb_cClass);
788 // Full class ancestry may not have been filled until we reach here.
789 rb_class_update_superclasses(METACLASS_OF(metaclass));
791 return metaclass;
795 * Creates a singleton class for `obj`.
796 * @pre `obj` must not be an immediate nor a special const.
797 * @pre `obj` must not be a Class object.
798 * @pre `obj` has no singleton class.
800 static inline VALUE
801 make_singleton_class(VALUE obj)
803 VALUE orig_class = METACLASS_OF(obj);
804 VALUE klass = rb_class_boot(orig_class);
806 FL_SET(klass, FL_SINGLETON);
807 RBASIC_SET_CLASS(obj, klass);
808 rb_singleton_class_attached(klass, obj);
809 rb_yjit_invalidate_no_singleton_class(orig_class);
811 SET_METACLASS_OF(klass, METACLASS_OF(rb_class_real(orig_class)));
812 return klass;
816 static VALUE
817 boot_defclass(const char *name, VALUE super)
819 VALUE obj = rb_class_boot(super);
820 ID id = rb_intern(name);
822 rb_const_set((rb_cObject ? rb_cObject : obj), id, obj);
823 rb_vm_register_global_object(obj);
824 return obj;
827 /***********************************************************************
829 * Document-class: Refinement
831 * Refinement is a class of the +self+ (current context) inside +refine+
832 * statement. It allows to import methods from other modules, see #import_methods.
835 #if 0 /* for RDoc */
837 * Document-method: Refinement#import_methods
839 * call-seq:
840 * import_methods(module, ...) -> self
842 * Imports methods from modules. Unlike Module#include,
843 * Refinement#import_methods copies methods and adds them into the refinement,
844 * so the refinement is activated in the imported methods.
846 * Note that due to method copying, only methods defined in Ruby code can be imported.
848 * module StrUtils
849 * def indent(level)
850 * ' ' * level + self
851 * end
852 * end
854 * module M
855 * refine String do
856 * import_methods StrUtils
857 * end
858 * end
860 * using M
861 * "foo".indent(3)
862 * #=> " foo"
864 * module M
865 * refine String do
866 * import_methods Enumerable
867 * # Can't import method which is not defined with Ruby code: Enumerable#drop
868 * end
869 * end
873 static VALUE
874 refinement_import_methods(int argc, VALUE *argv, VALUE refinement)
877 # endif
881 * \private
882 * Initializes the world of objects and classes.
884 * At first, the function bootstraps the class hierarchy.
885 * It initializes the most fundamental classes and their metaclasses.
886 * - \c BasicObject
887 * - \c Object
888 * - \c Module
889 * - \c Class
890 * After the bootstrap step, the class hierarchy becomes as the following
891 * diagram.
893 * \image html boottime-classes.png
895 * Then, the function defines classes, modules and methods as usual.
896 * \ingroup class
900 void
901 Init_class_hierarchy(void)
903 rb_cBasicObject = boot_defclass("BasicObject", 0);
904 rb_cObject = boot_defclass("Object", rb_cBasicObject);
905 rb_vm_register_global_object(rb_cObject);
907 /* resolve class name ASAP for order-independence */
908 rb_set_class_path_string(rb_cObject, rb_cObject, rb_fstring_lit("Object"));
910 rb_cModule = boot_defclass("Module", rb_cObject);
911 rb_cClass = boot_defclass("Class", rb_cModule);
912 rb_cRefinement = boot_defclass("Refinement", rb_cModule);
914 #if 0 /* for RDoc */
915 // we pretend it to be public, otherwise RDoc will ignore it
916 rb_define_method(rb_cRefinement, "import_methods", refinement_import_methods, -1);
917 #endif
919 rb_const_set(rb_cObject, rb_intern_const("BasicObject"), rb_cBasicObject);
920 RBASIC_SET_CLASS(rb_cClass, rb_cClass);
921 RBASIC_SET_CLASS(rb_cModule, rb_cClass);
922 RBASIC_SET_CLASS(rb_cObject, rb_cClass);
923 RBASIC_SET_CLASS(rb_cRefinement, rb_cClass);
924 RBASIC_SET_CLASS(rb_cBasicObject, rb_cClass);
926 ENSURE_EIGENCLASS(rb_cRefinement);
931 * @internal
932 * Creates a new *singleton class* for an object.
934 * @pre `obj` has no singleton class.
935 * @note DO NOT USE the function in an extension libraries. Use @ref rb_singleton_class.
936 * @param obj An object.
937 * @param unused ignored.
938 * @return The singleton class of the object.
940 VALUE
941 rb_make_metaclass(VALUE obj, VALUE unused)
943 if (BUILTIN_TYPE(obj) == T_CLASS) {
944 return make_metaclass(obj);
946 else {
947 return make_singleton_class(obj);
951 VALUE
952 rb_define_class_id(ID id, VALUE super)
954 VALUE klass;
956 if (!super) super = rb_cObject;
957 klass = rb_class_new(super);
958 rb_make_metaclass(klass, METACLASS_OF(super));
960 return klass;
965 * Calls Class#inherited.
966 * @param super A class which will be called #inherited.
967 * NULL means Object class.
968 * @param klass A Class object which derived from `super`
969 * @return the value `Class#inherited` returns
970 * @pre Each of `super` and `klass` must be a `Class` object.
972 VALUE
973 rb_class_inherited(VALUE super, VALUE klass)
975 ID inherited;
976 if (!super) super = rb_cObject;
977 CONST_ID(inherited, "inherited");
978 return rb_funcall(super, inherited, 1, klass);
981 VALUE
982 rb_define_class(const char *name, VALUE super)
984 VALUE klass;
985 ID id;
987 id = rb_intern(name);
988 if (rb_const_defined(rb_cObject, id)) {
989 klass = rb_const_get(rb_cObject, id);
990 if (!RB_TYPE_P(klass, T_CLASS)) {
991 rb_raise(rb_eTypeError, "%s is not a class (%"PRIsVALUE")",
992 name, rb_obj_class(klass));
994 if (rb_class_real(RCLASS_SUPER(klass)) != super) {
995 rb_raise(rb_eTypeError, "superclass mismatch for class %s", name);
998 /* Class may have been defined in Ruby and not pin-rooted */
999 rb_vm_register_global_object(klass);
1000 return klass;
1002 if (!super) {
1003 rb_raise(rb_eArgError, "no super class for '%s'", name);
1005 klass = rb_define_class_id(id, super);
1006 rb_vm_register_global_object(klass);
1007 rb_const_set(rb_cObject, id, klass);
1008 rb_class_inherited(super, klass);
1010 return klass;
1013 VALUE
1014 rb_define_class_under(VALUE outer, const char *name, VALUE super)
1016 return rb_define_class_id_under(outer, rb_intern(name), super);
1019 VALUE
1020 rb_define_class_id_under_no_pin(VALUE outer, ID id, VALUE super)
1022 VALUE klass;
1024 if (rb_const_defined_at(outer, id)) {
1025 klass = rb_const_get_at(outer, id);
1026 if (!RB_TYPE_P(klass, T_CLASS)) {
1027 rb_raise(rb_eTypeError, "%"PRIsVALUE"::%"PRIsVALUE" is not a class"
1028 " (%"PRIsVALUE")",
1029 outer, rb_id2str(id), rb_obj_class(klass));
1031 if (rb_class_real(RCLASS_SUPER(klass)) != super) {
1032 rb_raise(rb_eTypeError, "superclass mismatch for class "
1033 "%"PRIsVALUE"::%"PRIsVALUE""
1034 " (%"PRIsVALUE" is given but was %"PRIsVALUE")",
1035 outer, rb_id2str(id), RCLASS_SUPER(klass), super);
1038 return klass;
1040 if (!super) {
1041 rb_raise(rb_eArgError, "no super class for '%"PRIsVALUE"::%"PRIsVALUE"'",
1042 rb_class_path(outer), rb_id2str(id));
1044 klass = rb_define_class_id(id, super);
1045 rb_set_class_path_string(klass, outer, rb_id2str(id));
1046 rb_const_set(outer, id, klass);
1047 rb_class_inherited(super, klass);
1049 return klass;
1052 VALUE
1053 rb_define_class_id_under(VALUE outer, ID id, VALUE super)
1055 VALUE klass = rb_define_class_id_under_no_pin(outer, id, super);
1056 rb_vm_register_global_object(klass);
1057 return klass;
1060 VALUE
1061 rb_module_s_alloc(VALUE klass)
1063 VALUE mod = class_alloc(T_MODULE, klass);
1064 RCLASS_M_TBL_INIT(mod);
1065 FL_SET(mod, RMODULE_ALLOCATED_BUT_NOT_INITIALIZED);
1066 return mod;
1069 static inline VALUE
1070 module_new(VALUE klass)
1072 VALUE mdl = class_alloc(T_MODULE, klass);
1073 RCLASS_M_TBL_INIT(mdl);
1074 return (VALUE)mdl;
1077 VALUE
1078 rb_module_new(void)
1080 return module_new(rb_cModule);
1083 VALUE
1084 rb_refinement_new(void)
1086 return module_new(rb_cRefinement);
1089 // Kept for compatibility. Use rb_module_new() instead.
1090 VALUE
1091 rb_define_module_id(ID id)
1093 return rb_module_new();
1096 VALUE
1097 rb_define_module(const char *name)
1099 VALUE module;
1100 ID id;
1102 id = rb_intern(name);
1103 if (rb_const_defined(rb_cObject, id)) {
1104 module = rb_const_get(rb_cObject, id);
1105 if (!RB_TYPE_P(module, T_MODULE)) {
1106 rb_raise(rb_eTypeError, "%s is not a module (%"PRIsVALUE")",
1107 name, rb_obj_class(module));
1109 /* Module may have been defined in Ruby and not pin-rooted */
1110 rb_vm_register_global_object(module);
1111 return module;
1113 module = rb_module_new();
1114 rb_vm_register_global_object(module);
1115 rb_const_set(rb_cObject, id, module);
1117 return module;
1120 VALUE
1121 rb_define_module_under(VALUE outer, const char *name)
1123 return rb_define_module_id_under(outer, rb_intern(name));
1126 VALUE
1127 rb_define_module_id_under(VALUE outer, ID id)
1129 VALUE module;
1131 if (rb_const_defined_at(outer, id)) {
1132 module = rb_const_get_at(outer, id);
1133 if (!RB_TYPE_P(module, T_MODULE)) {
1134 rb_raise(rb_eTypeError, "%"PRIsVALUE"::%"PRIsVALUE" is not a module"
1135 " (%"PRIsVALUE")",
1136 outer, rb_id2str(id), rb_obj_class(module));
1138 /* Module may have been defined in Ruby and not pin-rooted */
1139 rb_vm_register_global_object(module);
1140 return module;
1142 module = rb_module_new();
1143 rb_const_set(outer, id, module);
1144 rb_set_class_path_string(module, outer, rb_id2str(id));
1145 rb_vm_register_global_object(module);
1147 return module;
1150 VALUE
1151 rb_include_class_new(VALUE module, VALUE super)
1153 VALUE klass = class_alloc(T_ICLASS, rb_cClass);
1155 RCLASS_SET_M_TBL(klass, RCLASS_M_TBL(module));
1157 RCLASS_SET_ORIGIN(klass, klass);
1158 if (BUILTIN_TYPE(module) == T_ICLASS) {
1159 module = METACLASS_OF(module);
1161 RUBY_ASSERT(!RB_TYPE_P(module, T_ICLASS));
1162 if (!RCLASS_CONST_TBL(module)) {
1163 RCLASS_CONST_TBL(module) = rb_id_table_create(0);
1166 RCLASS_CVC_TBL(klass) = RCLASS_CVC_TBL(module);
1167 RCLASS_CONST_TBL(klass) = RCLASS_CONST_TBL(module);
1169 RCLASS_SET_SUPER(klass, super);
1170 RBASIC_SET_CLASS(klass, module);
1172 return (VALUE)klass;
1175 static int include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super);
1177 static void
1178 ensure_includable(VALUE klass, VALUE module)
1180 rb_class_modify_check(klass);
1181 Check_Type(module, T_MODULE);
1182 rb_module_set_initialized(module);
1183 if (!NIL_P(rb_refinement_module_get_refined_class(module))) {
1184 rb_raise(rb_eArgError, "refinement module is not allowed");
1188 void
1189 rb_include_module(VALUE klass, VALUE module)
1191 int changed = 0;
1193 ensure_includable(klass, module);
1195 changed = include_modules_at(klass, RCLASS_ORIGIN(klass), module, TRUE);
1196 if (changed < 0)
1197 rb_raise(rb_eArgError, "cyclic include detected");
1199 if (RB_TYPE_P(klass, T_MODULE)) {
1200 rb_subclass_entry_t *iclass = RCLASS_SUBCLASSES(klass);
1201 // skip the placeholder subclass entry at the head of the list
1202 if (iclass) {
1203 RUBY_ASSERT(!iclass->klass);
1204 iclass = iclass->next;
1207 int do_include = 1;
1208 while (iclass) {
1209 VALUE check_class = iclass->klass;
1210 /* During lazy sweeping, iclass->klass could be a dead object that
1211 * has not yet been swept. */
1212 if (!rb_objspace_garbage_object_p(check_class)) {
1213 while (check_class) {
1214 RUBY_ASSERT(!rb_objspace_garbage_object_p(check_class));
1216 if (RB_TYPE_P(check_class, T_ICLASS) &&
1217 (METACLASS_OF(check_class) == module)) {
1218 do_include = 0;
1220 check_class = RCLASS_SUPER(check_class);
1223 if (do_include) {
1224 include_modules_at(iclass->klass, RCLASS_ORIGIN(iclass->klass), module, TRUE);
1228 iclass = iclass->next;
1233 static enum rb_id_table_iterator_result
1234 add_refined_method_entry_i(ID key, VALUE value, void *data)
1236 rb_add_refined_method_entry((VALUE)data, key);
1237 return ID_TABLE_CONTINUE;
1240 static enum rb_id_table_iterator_result
1241 clear_module_cache_i(ID id, VALUE val, void *data)
1243 VALUE klass = (VALUE)data;
1244 rb_clear_method_cache(klass, id);
1245 return ID_TABLE_CONTINUE;
1248 static bool
1249 module_in_super_chain(const VALUE klass, VALUE module)
1251 struct rb_id_table *const klass_m_tbl = RCLASS_M_TBL(RCLASS_ORIGIN(klass));
1252 if (klass_m_tbl) {
1253 while (module) {
1254 if (klass_m_tbl == RCLASS_M_TBL(module))
1255 return true;
1256 module = RCLASS_SUPER(module);
1259 return false;
1262 // For each ID key in the class constant table, we're going to clear the VM's
1263 // inline constant caches associated with it.
1264 static enum rb_id_table_iterator_result
1265 clear_constant_cache_i(ID id, VALUE value, void *data)
1267 rb_clear_constant_cache_for_id(id);
1268 return ID_TABLE_CONTINUE;
1271 static int
1272 do_include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super, bool check_cyclic)
1274 VALUE p, iclass, origin_stack = 0;
1275 int method_changed = 0, add_subclass;
1276 long origin_len;
1277 VALUE klass_origin = RCLASS_ORIGIN(klass);
1278 VALUE original_klass = klass;
1280 if (check_cyclic && module_in_super_chain(klass, module))
1281 return -1;
1283 while (module) {
1284 int c_seen = FALSE;
1285 int superclass_seen = FALSE;
1286 struct rb_id_table *tbl;
1288 if (klass == c) {
1289 c_seen = TRUE;
1291 if (klass_origin != c || search_super) {
1292 /* ignore if the module included already in superclasses for include,
1293 * ignore if the module included before origin class for prepend
1295 for (p = RCLASS_SUPER(klass); p; p = RCLASS_SUPER(p)) {
1296 int type = BUILTIN_TYPE(p);
1297 if (klass_origin == p && !search_super)
1298 break;
1299 if (c == p)
1300 c_seen = TRUE;
1301 if (type == T_ICLASS) {
1302 if (RCLASS_M_TBL(p) == RCLASS_M_TBL(module)) {
1303 if (!superclass_seen && c_seen) {
1304 c = p; /* move insertion point */
1306 goto skip;
1309 else if (type == T_CLASS) {
1310 superclass_seen = TRUE;
1315 VALUE super_class = RCLASS_SUPER(c);
1317 // invalidate inline method cache
1318 RB_DEBUG_COUNTER_INC(cvar_include_invalidate);
1319 ruby_vm_global_cvar_state++;
1320 tbl = RCLASS_M_TBL(module);
1321 if (tbl && rb_id_table_size(tbl)) {
1322 if (search_super) { // include
1323 if (super_class && !RB_TYPE_P(super_class, T_MODULE)) {
1324 rb_id_table_foreach(tbl, clear_module_cache_i, (void *)super_class);
1327 else { // prepend
1328 if (!RB_TYPE_P(original_klass, T_MODULE)) {
1329 rb_id_table_foreach(tbl, clear_module_cache_i, (void *)original_klass);
1332 method_changed = 1;
1335 // setup T_ICLASS for the include/prepend module
1336 iclass = rb_include_class_new(module, super_class);
1337 c = RCLASS_SET_SUPER(c, iclass);
1338 RCLASS_SET_INCLUDER(iclass, klass);
1339 add_subclass = TRUE;
1340 if (module != RCLASS_ORIGIN(module)) {
1341 if (!origin_stack) origin_stack = rb_ary_hidden_new(2);
1342 VALUE origin[2] = {iclass, RCLASS_ORIGIN(module)};
1343 rb_ary_cat(origin_stack, origin, 2);
1345 else if (origin_stack && (origin_len = RARRAY_LEN(origin_stack)) > 1 &&
1346 RARRAY_AREF(origin_stack, origin_len - 1) == module) {
1347 RCLASS_SET_ORIGIN(RARRAY_AREF(origin_stack, (origin_len -= 2)), iclass);
1348 RICLASS_SET_ORIGIN_SHARED_MTBL(iclass);
1349 rb_ary_resize(origin_stack, origin_len);
1350 add_subclass = FALSE;
1353 if (add_subclass) {
1354 VALUE m = module;
1355 if (BUILTIN_TYPE(m) == T_ICLASS) m = METACLASS_OF(m);
1356 rb_module_add_to_subclasses_list(m, iclass);
1359 if (BUILTIN_TYPE(klass) == T_MODULE && FL_TEST(klass, RMODULE_IS_REFINEMENT)) {
1360 VALUE refined_class =
1361 rb_refinement_module_get_refined_class(klass);
1363 rb_id_table_foreach(RCLASS_M_TBL(module), add_refined_method_entry_i, (void *)refined_class);
1364 RUBY_ASSERT(BUILTIN_TYPE(c) == T_MODULE);
1367 tbl = RCLASS_CONST_TBL(module);
1368 if (tbl && rb_id_table_size(tbl))
1369 rb_id_table_foreach(tbl, clear_constant_cache_i, NULL);
1370 skip:
1371 module = RCLASS_SUPER(module);
1374 return method_changed;
1377 static int
1378 include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super)
1380 return do_include_modules_at(klass, c, module, search_super, true);
1383 static enum rb_id_table_iterator_result
1384 move_refined_method(ID key, VALUE value, void *data)
1386 rb_method_entry_t *me = (rb_method_entry_t *)value;
1388 if (me->def->type == VM_METHOD_TYPE_REFINED) {
1389 VALUE klass = (VALUE)data;
1390 struct rb_id_table *tbl = RCLASS_M_TBL(klass);
1392 if (me->def->body.refined.orig_me) {
1393 const rb_method_entry_t *orig_me = me->def->body.refined.orig_me, *new_me;
1394 RB_OBJ_WRITE(me, &me->def->body.refined.orig_me, NULL);
1395 new_me = rb_method_entry_clone(me);
1396 rb_method_table_insert(klass, tbl, key, new_me);
1397 rb_method_entry_copy(me, orig_me);
1398 return ID_TABLE_CONTINUE;
1400 else {
1401 rb_method_table_insert(klass, tbl, key, me);
1402 return ID_TABLE_DELETE;
1405 else {
1406 return ID_TABLE_CONTINUE;
1410 static enum rb_id_table_iterator_result
1411 cache_clear_refined_method(ID key, VALUE value, void *data)
1413 rb_method_entry_t *me = (rb_method_entry_t *) value;
1415 if (me->def->type == VM_METHOD_TYPE_REFINED && me->def->body.refined.orig_me) {
1416 VALUE klass = (VALUE)data;
1417 rb_clear_method_cache(klass, me->called_id);
1419 // Refined method entries without an orig_me is going to stay in the method
1420 // table of klass, like before the move, so no need to clear the cache.
1422 return ID_TABLE_CONTINUE;
1425 static bool
1426 ensure_origin(VALUE klass)
1428 VALUE origin = RCLASS_ORIGIN(klass);
1429 if (origin == klass) {
1430 origin = class_alloc(T_ICLASS, klass);
1431 RCLASS_SET_M_TBL(origin, RCLASS_M_TBL(klass));
1432 RCLASS_SET_SUPER(origin, RCLASS_SUPER(klass));
1433 RCLASS_SET_SUPER(klass, origin);
1434 RCLASS_SET_ORIGIN(klass, origin);
1435 RCLASS_M_TBL_INIT(klass);
1436 rb_id_table_foreach(RCLASS_M_TBL(origin), cache_clear_refined_method, (void *)klass);
1437 rb_id_table_foreach(RCLASS_M_TBL(origin), move_refined_method, (void *)klass);
1438 return true;
1440 return false;
1443 void
1444 rb_prepend_module(VALUE klass, VALUE module)
1446 int changed;
1447 bool klass_had_no_origin;
1449 ensure_includable(klass, module);
1450 if (module_in_super_chain(klass, module))
1451 rb_raise(rb_eArgError, "cyclic prepend detected");
1453 klass_had_no_origin = ensure_origin(klass);
1454 changed = do_include_modules_at(klass, klass, module, FALSE, false);
1455 RUBY_ASSERT(changed >= 0); // already checked for cyclic prepend above
1456 if (changed) {
1457 rb_vm_check_redefinition_by_prepend(klass);
1459 if (RB_TYPE_P(klass, T_MODULE)) {
1460 rb_subclass_entry_t *iclass = RCLASS_SUBCLASSES(klass);
1461 // skip the placeholder subclass entry at the head of the list if it exists
1462 if (iclass) {
1463 RUBY_ASSERT(!iclass->klass);
1464 iclass = iclass->next;
1467 VALUE klass_origin = RCLASS_ORIGIN(klass);
1468 struct rb_id_table *klass_m_tbl = RCLASS_M_TBL(klass);
1469 struct rb_id_table *klass_origin_m_tbl = RCLASS_M_TBL(klass_origin);
1470 while (iclass) {
1471 /* During lazy sweeping, iclass->klass could be a dead object that
1472 * has not yet been swept. */
1473 if (!rb_objspace_garbage_object_p(iclass->klass)) {
1474 const VALUE subclass = iclass->klass;
1475 if (klass_had_no_origin && klass_origin_m_tbl == RCLASS_M_TBL(subclass)) {
1476 // backfill an origin iclass to handle refinements and future prepends
1477 rb_id_table_foreach(RCLASS_M_TBL(subclass), clear_module_cache_i, (void *)subclass);
1478 RCLASS_M_TBL(subclass) = klass_m_tbl;
1479 VALUE origin = rb_include_class_new(klass_origin, RCLASS_SUPER(subclass));
1480 RCLASS_SET_SUPER(subclass, origin);
1481 RCLASS_SET_INCLUDER(origin, RCLASS_INCLUDER(subclass));
1482 RCLASS_SET_ORIGIN(subclass, origin);
1483 RICLASS_SET_ORIGIN_SHARED_MTBL(origin);
1485 include_modules_at(subclass, subclass, module, FALSE);
1488 iclass = iclass->next;
1494 * call-seq:
1495 * mod.included_modules -> array
1497 * Returns the list of modules included or prepended in <i>mod</i>
1498 * or one of <i>mod</i>'s ancestors.
1500 * module Sub
1501 * end
1503 * module Mixin
1504 * prepend Sub
1505 * end
1507 * module Outer
1508 * include Mixin
1509 * end
1511 * Mixin.included_modules #=> [Sub]
1512 * Outer.included_modules #=> [Sub, Mixin]
1515 VALUE
1516 rb_mod_included_modules(VALUE mod)
1518 VALUE ary = rb_ary_new();
1519 VALUE p;
1520 VALUE origin = RCLASS_ORIGIN(mod);
1522 for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
1523 if (p != origin && RCLASS_ORIGIN(p) == p && BUILTIN_TYPE(p) == T_ICLASS) {
1524 VALUE m = METACLASS_OF(p);
1525 if (RB_TYPE_P(m, T_MODULE))
1526 rb_ary_push(ary, m);
1529 return ary;
1533 * call-seq:
1534 * mod.include?(module) -> true or false
1536 * Returns <code>true</code> if <i>module</i> is included
1537 * or prepended in <i>mod</i> or one of <i>mod</i>'s ancestors.
1539 * module A
1540 * end
1541 * class B
1542 * include A
1543 * end
1544 * class C < B
1545 * end
1546 * B.include?(A) #=> true
1547 * C.include?(A) #=> true
1548 * A.include?(A) #=> false
1551 VALUE
1552 rb_mod_include_p(VALUE mod, VALUE mod2)
1554 VALUE p;
1556 Check_Type(mod2, T_MODULE);
1557 for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
1558 if (BUILTIN_TYPE(p) == T_ICLASS && !FL_TEST(p, RICLASS_IS_ORIGIN)) {
1559 if (METACLASS_OF(p) == mod2) return Qtrue;
1562 return Qfalse;
1566 * call-seq:
1567 * mod.ancestors -> array
1569 * Returns a list of modules included/prepended in <i>mod</i>
1570 * (including <i>mod</i> itself).
1572 * module Mod
1573 * include Math
1574 * include Comparable
1575 * prepend Enumerable
1576 * end
1578 * Mod.ancestors #=> [Enumerable, Mod, Comparable, Math]
1579 * Math.ancestors #=> [Math]
1580 * Enumerable.ancestors #=> [Enumerable]
1583 VALUE
1584 rb_mod_ancestors(VALUE mod)
1586 VALUE p, ary = rb_ary_new();
1587 VALUE refined_class = Qnil;
1588 if (BUILTIN_TYPE(mod) == T_MODULE && FL_TEST(mod, RMODULE_IS_REFINEMENT)) {
1589 refined_class = rb_refinement_module_get_refined_class(mod);
1592 for (p = mod; p; p = RCLASS_SUPER(p)) {
1593 if (p == refined_class) break;
1594 if (p != RCLASS_ORIGIN(p)) continue;
1595 if (BUILTIN_TYPE(p) == T_ICLASS) {
1596 rb_ary_push(ary, METACLASS_OF(p));
1598 else {
1599 rb_ary_push(ary, p);
1602 return ary;
1605 struct subclass_traverse_data
1607 VALUE buffer;
1608 long count;
1609 long maxcount;
1610 bool immediate_only;
1613 static void
1614 class_descendants_recursive(VALUE klass, VALUE v)
1616 struct subclass_traverse_data *data = (struct subclass_traverse_data *) v;
1618 if (BUILTIN_TYPE(klass) == T_CLASS && !RCLASS_SINGLETON_P(klass)) {
1619 if (data->buffer && data->count < data->maxcount && !rb_objspace_garbage_object_p(klass)) {
1620 // assumes that this does not cause GC as long as the length does not exceed the capacity
1621 rb_ary_push(data->buffer, klass);
1623 data->count++;
1624 if (!data->immediate_only) {
1625 rb_class_foreach_subclass(klass, class_descendants_recursive, v);
1628 else {
1629 rb_class_foreach_subclass(klass, class_descendants_recursive, v);
1633 static VALUE
1634 class_descendants(VALUE klass, bool immediate_only)
1636 struct subclass_traverse_data data = { Qfalse, 0, -1, immediate_only };
1638 // estimate the count of subclasses
1639 rb_class_foreach_subclass(klass, class_descendants_recursive, (VALUE) &data);
1641 // the following allocation may cause GC which may change the number of subclasses
1642 data.buffer = rb_ary_new_capa(data.count);
1643 data.maxcount = data.count;
1644 data.count = 0;
1646 size_t gc_count = rb_gc_count();
1648 // enumerate subclasses
1649 rb_class_foreach_subclass(klass, class_descendants_recursive, (VALUE) &data);
1651 if (gc_count != rb_gc_count()) {
1652 rb_bug("GC must not occur during the subclass iteration of Class#descendants");
1655 return data.buffer;
1659 * call-seq:
1660 * subclasses -> array
1662 * Returns an array of classes where the receiver is the
1663 * direct superclass of the class, excluding singleton classes.
1664 * The order of the returned array is not defined.
1666 * class A; end
1667 * class B < A; end
1668 * class C < B; end
1669 * class D < A; end
1671 * A.subclasses #=> [D, B]
1672 * B.subclasses #=> [C]
1673 * C.subclasses #=> []
1675 * Anonymous subclasses (not associated with a constant) are
1676 * returned, too:
1678 * c = Class.new(A)
1679 * A.subclasses # => [#<Class:0x00007f003c77bd78>, D, B]
1681 * Note that the parent does not hold references to subclasses
1682 * and doesn't prevent them from being garbage collected. This
1683 * means that the subclass might disappear when all references
1684 * to it are dropped:
1686 * # drop the reference to subclass, it can be garbage-collected now
1687 * c = nil
1689 * A.subclasses
1690 * # It can be
1691 * # => [#<Class:0x00007f003c77bd78>, D, B]
1692 * # ...or just
1693 * # => [D, B]
1694 * # ...depending on whether garbage collector was run
1697 VALUE
1698 rb_class_subclasses(VALUE klass)
1700 return class_descendants(klass, true);
1704 * call-seq:
1705 * attached_object -> object
1707 * Returns the object for which the receiver is the singleton class.
1709 * Raises an TypeError if the class is not a singleton class.
1711 * class Foo; end
1713 * Foo.singleton_class.attached_object #=> Foo
1714 * Foo.attached_object #=> TypeError: `Foo' is not a singleton class
1715 * Foo.new.singleton_class.attached_object #=> #<Foo:0x000000010491a370>
1716 * TrueClass.attached_object #=> TypeError: `TrueClass' is not a singleton class
1717 * NilClass.attached_object #=> TypeError: `NilClass' is not a singleton class
1720 VALUE
1721 rb_class_attached_object(VALUE klass)
1723 if (!RCLASS_SINGLETON_P(klass)) {
1724 rb_raise(rb_eTypeError, "'%"PRIsVALUE"' is not a singleton class", klass);
1727 return RCLASS_ATTACHED_OBJECT(klass);
1730 static void
1731 ins_methods_push(st_data_t name, st_data_t ary)
1733 rb_ary_push((VALUE)ary, ID2SYM((ID)name));
1736 static int
1737 ins_methods_i(st_data_t name, st_data_t type, st_data_t ary)
1739 switch ((rb_method_visibility_t)type) {
1740 case METHOD_VISI_UNDEF:
1741 case METHOD_VISI_PRIVATE:
1742 break;
1743 default: /* everything but private */
1744 ins_methods_push(name, ary);
1745 break;
1747 return ST_CONTINUE;
1750 static int
1751 ins_methods_type_i(st_data_t name, st_data_t type, st_data_t ary, rb_method_visibility_t visi)
1753 if ((rb_method_visibility_t)type == visi) {
1754 ins_methods_push(name, ary);
1756 return ST_CONTINUE;
1759 static int
1760 ins_methods_prot_i(st_data_t name, st_data_t type, st_data_t ary)
1762 return ins_methods_type_i(name, type, ary, METHOD_VISI_PROTECTED);
1765 static int
1766 ins_methods_priv_i(st_data_t name, st_data_t type, st_data_t ary)
1768 return ins_methods_type_i(name, type, ary, METHOD_VISI_PRIVATE);
1771 static int
1772 ins_methods_pub_i(st_data_t name, st_data_t type, st_data_t ary)
1774 return ins_methods_type_i(name, type, ary, METHOD_VISI_PUBLIC);
1777 static int
1778 ins_methods_undef_i(st_data_t name, st_data_t type, st_data_t ary)
1780 return ins_methods_type_i(name, type, ary, METHOD_VISI_UNDEF);
1783 struct method_entry_arg {
1784 st_table *list;
1785 int recur;
1788 static enum rb_id_table_iterator_result
1789 method_entry_i(ID key, VALUE value, void *data)
1791 const rb_method_entry_t *me = (const rb_method_entry_t *)value;
1792 struct method_entry_arg *arg = (struct method_entry_arg *)data;
1793 rb_method_visibility_t type;
1795 if (me->def->type == VM_METHOD_TYPE_REFINED) {
1796 VALUE owner = me->owner;
1797 me = rb_resolve_refined_method(Qnil, me);
1798 if (!me) return ID_TABLE_CONTINUE;
1799 if (!arg->recur && me->owner != owner) return ID_TABLE_CONTINUE;
1801 if (!st_is_member(arg->list, key)) {
1802 if (UNDEFINED_METHOD_ENTRY_P(me)) {
1803 type = METHOD_VISI_UNDEF; /* none */
1805 else {
1806 type = METHOD_ENTRY_VISI(me);
1807 RUBY_ASSERT(type != METHOD_VISI_UNDEF);
1809 st_add_direct(arg->list, key, (st_data_t)type);
1811 return ID_TABLE_CONTINUE;
1814 static void
1815 add_instance_method_list(VALUE mod, struct method_entry_arg *me_arg)
1817 struct rb_id_table *m_tbl = RCLASS_M_TBL(mod);
1818 if (!m_tbl) return;
1819 rb_id_table_foreach(m_tbl, method_entry_i, me_arg);
1822 static bool
1823 particular_class_p(VALUE mod)
1825 if (!mod) return false;
1826 if (RCLASS_SINGLETON_P(mod)) return true;
1827 if (BUILTIN_TYPE(mod) == T_ICLASS) return true;
1828 return false;
1831 static VALUE
1832 class_instance_method_list(int argc, const VALUE *argv, VALUE mod, int obj, int (*func) (st_data_t, st_data_t, st_data_t))
1834 VALUE ary;
1835 int recur = TRUE, prepended = 0;
1836 struct method_entry_arg me_arg;
1838 if (rb_check_arity(argc, 0, 1)) recur = RTEST(argv[0]);
1840 me_arg.list = st_init_numtable();
1841 me_arg.recur = recur;
1843 if (obj) {
1844 for (; particular_class_p(mod); mod = RCLASS_SUPER(mod)) {
1845 add_instance_method_list(mod, &me_arg);
1849 if (!recur && RCLASS_ORIGIN(mod) != mod) {
1850 mod = RCLASS_ORIGIN(mod);
1851 prepended = 1;
1854 for (; mod; mod = RCLASS_SUPER(mod)) {
1855 add_instance_method_list(mod, &me_arg);
1856 if (BUILTIN_TYPE(mod) == T_ICLASS && !prepended) continue;
1857 if (!recur) break;
1859 ary = rb_ary_new2(me_arg.list->num_entries);
1860 st_foreach(me_arg.list, func, ary);
1861 st_free_table(me_arg.list);
1863 return ary;
1867 * call-seq:
1868 * mod.instance_methods(include_super=true) -> array
1870 * Returns an array containing the names of the public and protected instance
1871 * methods in the receiver. For a module, these are the public and protected methods;
1872 * for a class, they are the instance (not singleton) methods. If the optional
1873 * parameter is <code>false</code>, the methods of any ancestors are not included.
1875 * module A
1876 * def method1() end
1877 * end
1878 * class B
1879 * include A
1880 * def method2() end
1881 * end
1882 * class C < B
1883 * def method3() end
1884 * end
1886 * A.instance_methods(false) #=> [:method1]
1887 * B.instance_methods(false) #=> [:method2]
1888 * B.instance_methods(true).include?(:method1) #=> true
1889 * C.instance_methods(false) #=> [:method3]
1890 * C.instance_methods.include?(:method2) #=> true
1892 * Note that method visibility changes in the current class, as well as aliases,
1893 * are considered as methods of the current class by this method:
1895 * class C < B
1896 * alias method4 method2
1897 * protected :method2
1898 * end
1899 * C.instance_methods(false).sort #=> [:method2, :method3, :method4]
1902 VALUE
1903 rb_class_instance_methods(int argc, const VALUE *argv, VALUE mod)
1905 return class_instance_method_list(argc, argv, mod, 0, ins_methods_i);
1909 * call-seq:
1910 * mod.protected_instance_methods(include_super=true) -> array
1912 * Returns a list of the protected instance methods defined in
1913 * <i>mod</i>. If the optional parameter is <code>false</code>, the
1914 * methods of any ancestors are not included.
1917 VALUE
1918 rb_class_protected_instance_methods(int argc, const VALUE *argv, VALUE mod)
1920 return class_instance_method_list(argc, argv, mod, 0, ins_methods_prot_i);
1924 * call-seq:
1925 * mod.private_instance_methods(include_super=true) -> array
1927 * Returns a list of the private instance methods defined in
1928 * <i>mod</i>. If the optional parameter is <code>false</code>, the
1929 * methods of any ancestors are not included.
1931 * module Mod
1932 * def method1() end
1933 * private :method1
1934 * def method2() end
1935 * end
1936 * Mod.instance_methods #=> [:method2]
1937 * Mod.private_instance_methods #=> [:method1]
1940 VALUE
1941 rb_class_private_instance_methods(int argc, const VALUE *argv, VALUE mod)
1943 return class_instance_method_list(argc, argv, mod, 0, ins_methods_priv_i);
1947 * call-seq:
1948 * mod.public_instance_methods(include_super=true) -> array
1950 * Returns a list of the public instance methods defined in <i>mod</i>.
1951 * If the optional parameter is <code>false</code>, the methods of
1952 * any ancestors are not included.
1955 VALUE
1956 rb_class_public_instance_methods(int argc, const VALUE *argv, VALUE mod)
1958 return class_instance_method_list(argc, argv, mod, 0, ins_methods_pub_i);
1962 * call-seq:
1963 * mod.undefined_instance_methods -> array
1965 * Returns a list of the undefined instance methods defined in <i>mod</i>.
1966 * The undefined methods of any ancestors are not included.
1969 VALUE
1970 rb_class_undefined_instance_methods(VALUE mod)
1972 VALUE include_super = Qfalse;
1973 return class_instance_method_list(1, &include_super, mod, 0, ins_methods_undef_i);
1977 * call-seq:
1978 * obj.methods(regular=true) -> array
1980 * Returns a list of the names of public and protected methods of
1981 * <i>obj</i>. This will include all the methods accessible in
1982 * <i>obj</i>'s ancestors.
1983 * If the optional parameter is <code>false</code>, it
1984 * returns an array of <i>obj</i>'s public and protected singleton methods,
1985 * the array will not include methods in modules included in <i>obj</i>.
1987 * class Klass
1988 * def klass_method()
1989 * end
1990 * end
1991 * k = Klass.new
1992 * k.methods[0..9] #=> [:klass_method, :nil?, :===,
1993 * # :==~, :!, :eql?
1994 * # :hash, :<=>, :class, :singleton_class]
1995 * k.methods.length #=> 56
1997 * k.methods(false) #=> []
1998 * def k.singleton_method; end
1999 * k.methods(false) #=> [:singleton_method]
2001 * module M123; def m123; end end
2002 * k.extend M123
2003 * k.methods(false) #=> [:singleton_method]
2006 VALUE
2007 rb_obj_methods(int argc, const VALUE *argv, VALUE obj)
2009 rb_check_arity(argc, 0, 1);
2010 if (argc > 0 && !RTEST(argv[0])) {
2011 return rb_obj_singleton_methods(argc, argv, obj);
2013 return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_i);
2017 * call-seq:
2018 * obj.protected_methods(all=true) -> array
2020 * Returns the list of protected methods accessible to <i>obj</i>. If
2021 * the <i>all</i> parameter is set to <code>false</code>, only those methods
2022 * in the receiver will be listed.
2025 VALUE
2026 rb_obj_protected_methods(int argc, const VALUE *argv, VALUE obj)
2028 return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_prot_i);
2032 * call-seq:
2033 * obj.private_methods(all=true) -> array
2035 * Returns the list of private methods accessible to <i>obj</i>. If
2036 * the <i>all</i> parameter is set to <code>false</code>, only those methods
2037 * in the receiver will be listed.
2040 VALUE
2041 rb_obj_private_methods(int argc, const VALUE *argv, VALUE obj)
2043 return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_priv_i);
2047 * call-seq:
2048 * obj.public_methods(all=true) -> array
2050 * Returns the list of public methods accessible to <i>obj</i>. If
2051 * the <i>all</i> parameter is set to <code>false</code>, only those methods
2052 * in the receiver will be listed.
2055 VALUE
2056 rb_obj_public_methods(int argc, const VALUE *argv, VALUE obj)
2058 return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_pub_i);
2062 * call-seq:
2063 * obj.singleton_methods(all=true) -> array
2065 * Returns an array of the names of singleton methods for <i>obj</i>.
2066 * If the optional <i>all</i> parameter is true, the list will include
2067 * methods in modules included in <i>obj</i>.
2068 * Only public and protected singleton methods are returned.
2070 * module Other
2071 * def three() end
2072 * end
2074 * class Single
2075 * def Single.four() end
2076 * end
2078 * a = Single.new
2080 * def a.one()
2081 * end
2083 * class << a
2084 * include Other
2085 * def two()
2086 * end
2087 * end
2089 * Single.singleton_methods #=> [:four]
2090 * a.singleton_methods(false) #=> [:two, :one]
2091 * a.singleton_methods #=> [:two, :one, :three]
2094 VALUE
2095 rb_obj_singleton_methods(int argc, const VALUE *argv, VALUE obj)
2097 VALUE ary, klass, origin;
2098 struct method_entry_arg me_arg;
2099 struct rb_id_table *mtbl;
2100 int recur = TRUE;
2102 if (rb_check_arity(argc, 0, 1)) recur = RTEST(argv[0]);
2103 if (RCLASS_SINGLETON_P(obj)) {
2104 rb_singleton_class(obj);
2106 klass = CLASS_OF(obj);
2107 origin = RCLASS_ORIGIN(klass);
2108 me_arg.list = st_init_numtable();
2109 me_arg.recur = recur;
2110 if (klass && RCLASS_SINGLETON_P(klass)) {
2111 if ((mtbl = RCLASS_M_TBL(origin)) != 0) rb_id_table_foreach(mtbl, method_entry_i, &me_arg);
2112 klass = RCLASS_SUPER(klass);
2114 if (recur) {
2115 while (klass && (RCLASS_SINGLETON_P(klass) || RB_TYPE_P(klass, T_ICLASS))) {
2116 if (klass != origin && (mtbl = RCLASS_M_TBL(klass)) != 0) rb_id_table_foreach(mtbl, method_entry_i, &me_arg);
2117 klass = RCLASS_SUPER(klass);
2120 ary = rb_ary_new2(me_arg.list->num_entries);
2121 st_foreach(me_arg.list, ins_methods_i, ary);
2122 st_free_table(me_arg.list);
2124 return ary;
2128 * \}
2131 * \addtogroup defmethod
2132 * \{
2135 #ifdef rb_define_method_id
2136 #undef rb_define_method_id
2137 #endif
2138 void
2139 rb_define_method_id(VALUE klass, ID mid, VALUE (*func)(ANYARGS), int argc)
2141 rb_add_method_cfunc(klass, mid, func, argc, METHOD_VISI_PUBLIC);
2144 #ifdef rb_define_method
2145 #undef rb_define_method
2146 #endif
2147 void
2148 rb_define_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc)
2150 rb_add_method_cfunc(klass, rb_intern(name), func, argc, METHOD_VISI_PUBLIC);
2153 #ifdef rb_define_protected_method
2154 #undef rb_define_protected_method
2155 #endif
2156 void
2157 rb_define_protected_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc)
2159 rb_add_method_cfunc(klass, rb_intern(name), func, argc, METHOD_VISI_PROTECTED);
2162 #ifdef rb_define_private_method
2163 #undef rb_define_private_method
2164 #endif
2165 void
2166 rb_define_private_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc)
2168 rb_add_method_cfunc(klass, rb_intern(name), func, argc, METHOD_VISI_PRIVATE);
2171 void
2172 rb_undef_method(VALUE klass, const char *name)
2174 rb_add_method(klass, rb_intern(name), VM_METHOD_TYPE_UNDEF, 0, METHOD_VISI_UNDEF);
2177 static enum rb_id_table_iterator_result
2178 undef_method_i(ID name, VALUE value, void *data)
2180 VALUE klass = (VALUE)data;
2181 rb_add_method(klass, name, VM_METHOD_TYPE_UNDEF, 0, METHOD_VISI_UNDEF);
2182 return ID_TABLE_CONTINUE;
2185 void
2186 rb_undef_methods_from(VALUE klass, VALUE super)
2188 struct rb_id_table *mtbl = RCLASS_M_TBL(super);
2189 if (mtbl) {
2190 rb_id_table_foreach(mtbl, undef_method_i, (void *)klass);
2195 * \}
2198 * \addtogroup class
2199 * \{
2202 static inline VALUE
2203 special_singleton_class_of(VALUE obj)
2205 switch (obj) {
2206 case Qnil: return rb_cNilClass;
2207 case Qfalse: return rb_cFalseClass;
2208 case Qtrue: return rb_cTrueClass;
2209 default: return Qnil;
2213 VALUE
2214 rb_special_singleton_class(VALUE obj)
2216 return special_singleton_class_of(obj);
2220 * @internal
2221 * Returns the singleton class of `obj`. Creates it if necessary.
2223 * @note DO NOT expose the returned singleton class to
2224 * outside of class.c.
2225 * Use @ref rb_singleton_class instead for
2226 * consistency of the metaclass hierarchy.
2228 static VALUE
2229 singleton_class_of(VALUE obj)
2231 VALUE klass;
2233 switch (TYPE(obj)) {
2234 case T_FIXNUM:
2235 case T_BIGNUM:
2236 case T_FLOAT:
2237 case T_SYMBOL:
2238 rb_raise(rb_eTypeError, "can't define singleton");
2240 case T_FALSE:
2241 case T_TRUE:
2242 case T_NIL:
2243 klass = special_singleton_class_of(obj);
2244 if (NIL_P(klass))
2245 rb_bug("unknown immediate %p", (void *)obj);
2246 return klass;
2248 case T_STRING:
2249 if (CHILLED_STRING_P(obj)) {
2250 CHILLED_STRING_MUTATED(obj);
2252 else if (FL_TEST_RAW(obj, RSTRING_FSTR)) {
2253 rb_raise(rb_eTypeError, "can't define singleton");
2257 klass = METACLASS_OF(obj);
2258 if (!(RCLASS_SINGLETON_P(klass) &&
2259 RCLASS_ATTACHED_OBJECT(klass) == obj)) {
2260 klass = rb_make_metaclass(obj, klass);
2263 RB_FL_SET_RAW(klass, RB_OBJ_FROZEN_RAW(obj));
2265 return klass;
2268 void
2269 rb_freeze_singleton_class(VALUE x)
2271 /* should not propagate to meta-meta-class, and so on */
2272 if (!RCLASS_SINGLETON_P(x)) {
2273 VALUE klass = RBASIC_CLASS(x);
2274 if (klass && // no class when hidden from ObjectSpace
2275 FL_TEST(klass, (FL_SINGLETON|FL_FREEZE)) == FL_SINGLETON) {
2276 OBJ_FREEZE(klass);
2282 * Returns the singleton class of `obj`, or nil if obj is not a
2283 * singleton object.
2285 * @param obj an arbitrary object.
2286 * @return the singleton class or nil.
2288 VALUE
2289 rb_singleton_class_get(VALUE obj)
2291 VALUE klass;
2293 if (SPECIAL_CONST_P(obj)) {
2294 return rb_special_singleton_class(obj);
2296 klass = METACLASS_OF(obj);
2297 if (!RCLASS_SINGLETON_P(klass)) return Qnil;
2298 if (RCLASS_ATTACHED_OBJECT(klass) != obj) return Qnil;
2299 return klass;
2302 VALUE
2303 rb_singleton_class(VALUE obj)
2305 VALUE klass = singleton_class_of(obj);
2307 /* ensures an exposed class belongs to its own eigenclass */
2308 if (RB_TYPE_P(obj, T_CLASS)) (void)ENSURE_EIGENCLASS(klass);
2310 return klass;
2314 * \}
2318 * \addtogroup defmethod
2319 * \{
2322 #ifdef rb_define_singleton_method
2323 #undef rb_define_singleton_method
2324 #endif
2325 void
2326 rb_define_singleton_method(VALUE obj, const char *name, VALUE (*func)(ANYARGS), int argc)
2328 rb_define_method(singleton_class_of(obj), name, func, argc);
2331 #ifdef rb_define_module_function
2332 #undef rb_define_module_function
2333 #endif
2334 void
2335 rb_define_module_function(VALUE module, const char *name, VALUE (*func)(ANYARGS), int argc)
2337 rb_define_private_method(module, name, func, argc);
2338 rb_define_singleton_method(module, name, func, argc);
2341 #ifdef rb_define_global_function
2342 #undef rb_define_global_function
2343 #endif
2344 void
2345 rb_define_global_function(const char *name, VALUE (*func)(ANYARGS), int argc)
2347 rb_define_module_function(rb_mKernel, name, func, argc);
2350 void
2351 rb_define_alias(VALUE klass, const char *name1, const char *name2)
2353 rb_alias(klass, rb_intern(name1), rb_intern(name2));
2356 void
2357 rb_define_attr(VALUE klass, const char *name, int read, int write)
2359 rb_attr(klass, rb_intern(name), read, write, FALSE);
2362 VALUE
2363 rb_keyword_error_new(const char *error, VALUE keys)
2365 long i = 0, len = RARRAY_LEN(keys);
2366 VALUE error_message = rb_sprintf("%s keyword%.*s", error, len > 1, "s");
2368 if (len > 0) {
2369 rb_str_cat_cstr(error_message, ": ");
2370 while (1) {
2371 const VALUE k = RARRAY_AREF(keys, i);
2372 rb_str_append(error_message, rb_inspect(k));
2373 if (++i >= len) break;
2374 rb_str_cat_cstr(error_message, ", ");
2378 return rb_exc_new_str(rb_eArgError, error_message);
2381 NORETURN(static void rb_keyword_error(const char *error, VALUE keys));
2382 static void
2383 rb_keyword_error(const char *error, VALUE keys)
2385 rb_exc_raise(rb_keyword_error_new(error, keys));
2388 NORETURN(static void unknown_keyword_error(VALUE hash, const ID *table, int keywords));
2389 static void
2390 unknown_keyword_error(VALUE hash, const ID *table, int keywords)
2392 int i;
2393 for (i = 0; i < keywords; i++) {
2394 st_data_t key = ID2SYM(table[i]);
2395 rb_hash_stlike_delete(hash, &key, NULL);
2397 rb_keyword_error("unknown", rb_hash_keys(hash));
2401 static int
2402 separate_symbol(st_data_t key, st_data_t value, st_data_t arg)
2404 VALUE *kwdhash = (VALUE *)arg;
2405 if (!SYMBOL_P(key)) kwdhash++;
2406 if (!*kwdhash) *kwdhash = rb_hash_new();
2407 rb_hash_aset(*kwdhash, (VALUE)key, (VALUE)value);
2408 return ST_CONTINUE;
2411 VALUE
2412 rb_extract_keywords(VALUE *orighash)
2414 VALUE parthash[2] = {0, 0};
2415 VALUE hash = *orighash;
2417 if (RHASH_EMPTY_P(hash)) {
2418 *orighash = 0;
2419 return hash;
2421 rb_hash_foreach(hash, separate_symbol, (st_data_t)&parthash);
2422 *orighash = parthash[1];
2423 if (parthash[1] && RBASIC_CLASS(hash) != rb_cHash) {
2424 RBASIC_SET_CLASS(parthash[1], RBASIC_CLASS(hash));
2426 return parthash[0];
2430 rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
2432 int i = 0, j;
2433 int rest = 0;
2434 VALUE missing = Qnil;
2435 st_data_t key;
2437 #define extract_kwarg(keyword, val) \
2438 (key = (st_data_t)(keyword), values ? \
2439 (rb_hash_stlike_delete(keyword_hash, &key, &(val)) || ((val) = Qundef, 0)) : \
2440 rb_hash_stlike_lookup(keyword_hash, key, NULL))
2442 if (NIL_P(keyword_hash)) keyword_hash = 0;
2444 if (optional < 0) {
2445 rest = 1;
2446 optional = -1-optional;
2448 if (required) {
2449 for (; i < required; i++) {
2450 VALUE keyword = ID2SYM(table[i]);
2451 if (keyword_hash) {
2452 if (extract_kwarg(keyword, values[i])) {
2453 continue;
2456 if (NIL_P(missing)) missing = rb_ary_hidden_new(1);
2457 rb_ary_push(missing, keyword);
2459 if (!NIL_P(missing)) {
2460 rb_keyword_error("missing", missing);
2463 j = i;
2464 if (optional && keyword_hash) {
2465 for (i = 0; i < optional; i++) {
2466 if (extract_kwarg(ID2SYM(table[required+i]), values[required+i])) {
2467 j++;
2471 if (!rest && keyword_hash) {
2472 if (RHASH_SIZE(keyword_hash) > (unsigned int)(values ? 0 : j)) {
2473 unknown_keyword_error(keyword_hash, table, required+optional);
2476 if (values && !keyword_hash) {
2477 for (i = 0; i < required + optional; i++) {
2478 values[i] = Qundef;
2481 return j;
2482 #undef extract_kwarg
2485 struct rb_scan_args_t {
2486 int kw_flag;
2487 int n_lead;
2488 int n_opt;
2489 int n_trail;
2490 bool f_var;
2491 bool f_hash;
2492 bool f_block;
2495 static void
2496 rb_scan_args_parse(int kw_flag, const char *fmt, struct rb_scan_args_t *arg)
2498 const char *p = fmt;
2500 memset(arg, 0, sizeof(*arg));
2501 arg->kw_flag = kw_flag;
2503 if (ISDIGIT(*p)) {
2504 arg->n_lead = *p - '0';
2505 p++;
2506 if (ISDIGIT(*p)) {
2507 arg->n_opt = *p - '0';
2508 p++;
2511 if (*p == '*') {
2512 arg->f_var = 1;
2513 p++;
2515 if (ISDIGIT(*p)) {
2516 arg->n_trail = *p - '0';
2517 p++;
2519 if (*p == ':') {
2520 arg->f_hash = 1;
2521 p++;
2523 if (*p == '&') {
2524 arg->f_block = 1;
2525 p++;
2527 if (*p != '\0') {
2528 rb_fatal("bad scan arg format: %s", fmt);
2532 static int
2533 rb_scan_args_assign(const struct rb_scan_args_t *arg, int argc, const VALUE *const argv, va_list vargs)
2535 int i, argi = 0;
2536 VALUE *var, hash = Qnil;
2537 #define rb_scan_args_next_param() va_arg(vargs, VALUE *)
2538 const int kw_flag = arg->kw_flag;
2539 const int n_lead = arg->n_lead;
2540 const int n_opt = arg->n_opt;
2541 const int n_trail = arg->n_trail;
2542 const int n_mand = n_lead + n_trail;
2543 const bool f_var = arg->f_var;
2544 const bool f_hash = arg->f_hash;
2545 const bool f_block = arg->f_block;
2547 /* capture an option hash - phase 1: pop from the argv */
2548 if (f_hash && argc > 0) {
2549 VALUE last = argv[argc - 1];
2550 if (rb_scan_args_keyword_p(kw_flag, last)) {
2551 hash = rb_hash_dup(last);
2552 argc--;
2556 if (argc < n_mand) {
2557 goto argc_error;
2560 /* capture leading mandatory arguments */
2561 for (i = 0; i < n_lead; i++) {
2562 var = rb_scan_args_next_param();
2563 if (var) *var = argv[argi];
2564 argi++;
2566 /* capture optional arguments */
2567 for (i = 0; i < n_opt; i++) {
2568 var = rb_scan_args_next_param();
2569 if (argi < argc - n_trail) {
2570 if (var) *var = argv[argi];
2571 argi++;
2573 else {
2574 if (var) *var = Qnil;
2577 /* capture variable length arguments */
2578 if (f_var) {
2579 int n_var = argc - argi - n_trail;
2581 var = rb_scan_args_next_param();
2582 if (0 < n_var) {
2583 if (var) *var = rb_ary_new_from_values(n_var, &argv[argi]);
2584 argi += n_var;
2586 else {
2587 if (var) *var = rb_ary_new();
2590 /* capture trailing mandatory arguments */
2591 for (i = 0; i < n_trail; i++) {
2592 var = rb_scan_args_next_param();
2593 if (var) *var = argv[argi];
2594 argi++;
2596 /* capture an option hash - phase 2: assignment */
2597 if (f_hash) {
2598 var = rb_scan_args_next_param();
2599 if (var) *var = hash;
2601 /* capture iterator block */
2602 if (f_block) {
2603 var = rb_scan_args_next_param();
2604 if (rb_block_given_p()) {
2605 *var = rb_block_proc();
2607 else {
2608 *var = Qnil;
2612 if (argi == argc) {
2613 return argc;
2616 argc_error:
2617 return -(argc + 1);
2618 #undef rb_scan_args_next_param
2621 static int
2622 rb_scan_args_result(const struct rb_scan_args_t *const arg, int argc)
2624 const int n_lead = arg->n_lead;
2625 const int n_opt = arg->n_opt;
2626 const int n_trail = arg->n_trail;
2627 const int n_mand = n_lead + n_trail;
2628 const bool f_var = arg->f_var;
2630 if (argc >= 0) {
2631 return argc;
2634 argc = -argc - 1;
2635 rb_error_arity(argc, n_mand, f_var ? UNLIMITED_ARGUMENTS : n_mand + n_opt);
2636 UNREACHABLE_RETURN(-1);
2639 #undef rb_scan_args
2641 rb_scan_args(int argc, const VALUE *argv, const char *fmt, ...)
2643 va_list vargs;
2644 struct rb_scan_args_t arg;
2645 rb_scan_args_parse(RB_SCAN_ARGS_PASS_CALLED_KEYWORDS, fmt, &arg);
2646 va_start(vargs,fmt);
2647 argc = rb_scan_args_assign(&arg, argc, argv, vargs);
2648 va_end(vargs);
2649 return rb_scan_args_result(&arg, argc);
2652 #undef rb_scan_args_kw
2654 rb_scan_args_kw(int kw_flag, int argc, const VALUE *argv, const char *fmt, ...)
2656 va_list vargs;
2657 struct rb_scan_args_t arg;
2658 rb_scan_args_parse(kw_flag, fmt, &arg);
2659 va_start(vargs,fmt);
2660 argc = rb_scan_args_assign(&arg, argc, argv, vargs);
2661 va_end(vargs);
2662 return rb_scan_args_result(&arg, argc);
2666 * \}