1 /**********************************************************************
6 created at: Tue Aug 10 15:05:44 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
17 #include "ruby/internal/config.h"
21 #include "debug_counter.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"
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.
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.
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.
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
);
91 head
= RCLASS_SUBCLASSES(super
);
93 head
= ZALLOC(rb_subclass_entry_t
);
94 RCLASS_SUBCLASSES(super
) = head
;
96 entry
->next
= head
->next
;
100 head
->next
->prev
= entry
;
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
;
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
;
124 rb_class_remove_subclass_head(VALUE klass
)
126 rb_subclass_entry_t
*head
= RCLASS_SUBCLASSES(klass
);
130 head
->next
->prev
= NULL
;
132 RCLASS_SUBCLASSES(klass
) = NULL
;
138 rb_class_remove_from_super_subclasses(VALUE klass
)
140 rb_subclass_entry_t
*entry
= RCLASS_SUBCLASS_ENTRY(klass
);
143 rb_subclass_entry_t
*prev
= entry
->prev
, *next
= entry
->next
;
155 RCLASS_SUBCLASS_ENTRY(klass
) = NULL
;
159 rb_class_remove_from_module_subclasses(VALUE klass
)
161 rb_subclass_entry_t
*entry
= RCLASS_MODULE_SUBCLASS_ENTRY(klass
);
164 rb_subclass_entry_t
*prev
= entry
->prev
, *next
= entry
->next
;
176 RCLASS_MODULE_SUBCLASS_ENTRY(klass
) = NULL
;
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)
187 RUBY_ASSERT(!cur
->klass
);
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 */
194 VALUE curklass
= cur
->klass
;
196 // do not trigger GC during f, otherwise the cur will become
197 // a dangling pointer if the subclass is collected
203 class_detach_subclasses(VALUE klass
, VALUE arg
)
205 rb_class_remove_from_super_subclasses(klass
);
209 rb_class_detach_subclasses(VALUE klass
)
211 rb_class_foreach_subclass(klass
, class_detach_subclasses
, Qnil
);
215 class_detach_module_subclasses(VALUE klass
, VALUE arg
)
217 rb_class_remove_from_module_subclasses(klass
);
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.
239 class_alloc(VALUE flags
, VALUE klass
)
241 size_t alloc_size
= sizeof(struct RClass
) + sizeof(rb_classext_t
);
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
));
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);
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.
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
);
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));
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
);
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
))
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
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
))
339 RCLASS_SUPERCLASSES(klass
) = class_superclasses_including_self(super
);
340 RCLASS_SUPERCLASS_DEPTH(klass
) = RCLASS_SUPERCLASS_DEPTH(super
) + 1;
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");
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
;
373 rb_class_s_alloc(VALUE klass
)
375 return rb_class_boot(0);
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
) {
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
));
387 rb_method_entry_set(new_klass
, mid
, me
, METHOD_ENTRY_VISI(me
));
391 struct clone_method_arg
{
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
{
406 struct rb_id_table
*tbl
;
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
);
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
{
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
;
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
;
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
)) {
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);
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
};
511 RMODULE_UNINITIALIZED(VALUE module
)
513 return FL_TEST_RAW(module
, RMODULE_ALLOCATED_BUT_NOT_INITIALIZED
);
517 rb_module_set_initialized(VALUE mod
)
519 FL_UNSET_RAW(mod
, RMODULE_ALLOCATED_BUT_NOT_INITIALIZED
);
520 /* no more re-initialization */
524 rb_module_check_initializable(VALUE mod
)
526 if (!RMODULE_UNINITIALIZED(mod
)) {
527 rb_raise(rb_eTypeError
, "already initialized module");
533 rb_mod_init_copy(VALUE clone
, VALUE orig
)
535 switch (BUILTIN_TYPE(clone
)) {
538 class_init_copy_check(clone
, orig
);
541 rb_module_check_initializable(clone
);
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
));
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);
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
);
602 if (p
!= RCLASS_ORIGIN(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
;
615 rb_module_add_to_subclasses_list(METACLASS_OF(p
), clone_p
);
620 if (p
== orig_origin
) {
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
);
635 rb_bug("no origin for class that has origin");
638 rb_class_update_superclasses(clone
);
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`.
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
660 if (!(RCLASS_SINGLETON_P(klass
) && RCLASS_ATTACHED_OBJECT(klass
) == obj
)) {
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
);
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);
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
);
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))
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
766 make_metaclass(VALUE klass
)
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
);
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
));
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.
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
)));
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
);
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.
837 * Document-method: Refinement#import_methods
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.
856 * import_methods StrUtils
866 * import_methods Enumerable
867 * # Can't import method which is not defined with Ruby code: Enumerable#drop
874 refinement_import_methods(int argc
, VALUE
*argv
, VALUE refinement
)
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.
890 * After the bootstrap step, the class hierarchy becomes as the following
893 * \image html boottime-classes.png
895 * Then, the function defines classes, modules and methods as usual.
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
);
915 // we pretend it to be public, otherwise RDoc will ignore it
916 rb_define_method(rb_cRefinement
, "import_methods", refinement_import_methods
, -1);
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
);
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.
941 rb_make_metaclass(VALUE obj
, VALUE unused
)
943 if (BUILTIN_TYPE(obj
) == T_CLASS
) {
944 return make_metaclass(obj
);
947 return make_singleton_class(obj
);
952 rb_define_class_id(ID id
, VALUE super
)
956 if (!super
) super
= rb_cObject
;
957 klass
= rb_class_new(super
);
958 rb_make_metaclass(klass
, METACLASS_OF(super
));
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.
973 rb_class_inherited(VALUE super
, VALUE klass
)
976 if (!super
) super
= rb_cObject
;
977 CONST_ID(inherited
, "inherited");
978 return rb_funcall(super
, inherited
, 1, klass
);
982 rb_define_class(const char *name
, VALUE super
)
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
);
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
);
1014 rb_define_class_under(VALUE outer
, const char *name
, VALUE super
)
1016 return rb_define_class_id_under(outer
, rb_intern(name
), super
);
1020 rb_define_class_id_under_no_pin(VALUE outer
, ID id
, VALUE super
)
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"
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
);
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
);
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
);
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
);
1070 module_new(VALUE klass
)
1072 VALUE mdl
= class_alloc(T_MODULE
, klass
);
1073 RCLASS_M_TBL_INIT(mdl
);
1080 return module_new(rb_cModule
);
1084 rb_refinement_new(void)
1086 return module_new(rb_cRefinement
);
1089 // Kept for compatibility. Use rb_module_new() instead.
1091 rb_define_module_id(ID id
)
1093 return rb_module_new();
1097 rb_define_module(const char *name
)
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
);
1113 module
= rb_module_new();
1114 rb_vm_register_global_object(module
);
1115 rb_const_set(rb_cObject
, id
, module
);
1121 rb_define_module_under(VALUE outer
, const char *name
)
1123 return rb_define_module_id_under(outer
, rb_intern(name
));
1127 rb_define_module_id_under(VALUE outer
, ID id
)
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"
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
);
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
);
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
);
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");
1189 rb_include_module(VALUE klass
, VALUE module
)
1193 ensure_includable(klass
, module
);
1195 changed
= include_modules_at(klass
, RCLASS_ORIGIN(klass
), module
, TRUE
);
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
1203 RUBY_ASSERT(!iclass
->klass
);
1204 iclass
= iclass
->next
;
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
)) {
1220 check_class
= RCLASS_SUPER(check_class
);
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
;
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
));
1254 if (klass_m_tbl
== RCLASS_M_TBL(module
))
1256 module
= RCLASS_SUPER(module
);
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
;
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
;
1277 VALUE klass_origin
= RCLASS_ORIGIN(klass
);
1278 VALUE original_klass
= klass
;
1280 if (check_cyclic
&& module_in_super_chain(klass
, module
))
1285 int superclass_seen
= FALSE
;
1286 struct rb_id_table
*tbl
;
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
)
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 */
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
);
1328 if (!RB_TYPE_P(original_klass
, T_MODULE
)) {
1329 rb_id_table_foreach(tbl
, clear_module_cache_i
, (void *)original_klass
);
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
;
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
);
1371 module
= RCLASS_SUPER(module
);
1374 return method_changed
;
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
;
1401 rb_method_table_insert(klass
, tbl
, key
, me
);
1402 return ID_TABLE_DELETE
;
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
;
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
);
1444 rb_prepend_module(VALUE klass
, VALUE module
)
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
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
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
);
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
;
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.
1511 * Mixin.included_modules #=> [Sub]
1512 * Outer.included_modules #=> [Sub, Mixin]
1516 rb_mod_included_modules(VALUE mod
)
1518 VALUE ary
= rb_ary_new();
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
);
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.
1546 * B.include?(A) #=> true
1547 * C.include?(A) #=> true
1548 * A.include?(A) #=> false
1552 rb_mod_include_p(VALUE mod
, VALUE mod2
)
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
;
1567 * mod.ancestors -> array
1569 * Returns a list of modules included/prepended in <i>mod</i>
1570 * (including <i>mod</i> itself).
1574 * include Comparable
1575 * prepend Enumerable
1578 * Mod.ancestors #=> [Enumerable, Mod, Comparable, Math]
1579 * Math.ancestors #=> [Math]
1580 * Enumerable.ancestors #=> [Enumerable]
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
));
1599 rb_ary_push(ary
, p
);
1605 struct subclass_traverse_data
1610 bool immediate_only
;
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
);
1624 if (!data
->immediate_only
) {
1625 rb_class_foreach_subclass(klass
, class_descendants_recursive
, v
);
1629 rb_class_foreach_subclass(klass
, class_descendants_recursive
, v
);
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
;
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");
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.
1671 * A.subclasses #=> [D, B]
1672 * B.subclasses #=> [C]
1673 * C.subclasses #=> []
1675 * Anonymous subclasses (not associated with a constant) are
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
1691 * # => [#<Class:0x00007f003c77bd78>, D, B]
1694 * # ...depending on whether garbage collector was run
1698 rb_class_subclasses(VALUE klass
)
1700 return class_descendants(klass
, true);
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.
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
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
);
1731 ins_methods_push(st_data_t name
, st_data_t ary
)
1733 rb_ary_push((VALUE
)ary
, ID2SYM((ID
)name
));
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
:
1743 default: /* everything but private */
1744 ins_methods_push(name
, ary
);
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
);
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
);
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
);
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
);
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
{
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 */
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
;
1815 add_instance_method_list(VALUE mod
, struct method_entry_arg
*me_arg
)
1817 struct rb_id_table
*m_tbl
= RCLASS_M_TBL(mod
);
1819 rb_id_table_foreach(m_tbl
, method_entry_i
, me_arg
);
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;
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
))
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
;
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
);
1854 for (; mod
; mod
= RCLASS_SUPER(mod
)) {
1855 add_instance_method_list(mod
, &me_arg
);
1856 if (BUILTIN_TYPE(mod
) == T_ICLASS
&& !prepended
) continue;
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
);
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.
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:
1896 * alias method4 method2
1897 * protected :method2
1899 * C.instance_methods(false).sort #=> [:method2, :method3, :method4]
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
);
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.
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
);
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.
1936 * Mod.instance_methods #=> [:method2]
1937 * Mod.private_instance_methods #=> [:method1]
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
);
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.
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
);
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.
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
);
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>.
1988 * def klass_method()
1992 * k.methods[0..9] #=> [:klass_method, :nil?, :===,
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
2003 * k.methods(false) #=> [:singleton_method]
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
);
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.
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
);
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.
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
);
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.
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
);
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.
2075 * def Single.four() end
2089 * Single.singleton_methods #=> [:four]
2090 * a.singleton_methods(false) #=> [:two, :one]
2091 * a.singleton_methods #=> [:two, :one, :three]
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
;
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
);
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
);
2131 * \addtogroup defmethod
2135 #ifdef rb_define_method_id
2136 #undef rb_define_method_id
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
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
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
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
);
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
;
2186 rb_undef_methods_from(VALUE klass
, VALUE super
)
2188 struct rb_id_table
*mtbl
= RCLASS_M_TBL(super
);
2190 rb_id_table_foreach(mtbl
, undef_method_i
, (void *)klass
);
2203 special_singleton_class_of(VALUE obj
)
2206 case Qnil
: return rb_cNilClass
;
2207 case Qfalse
: return rb_cFalseClass
;
2208 case Qtrue
: return rb_cTrueClass
;
2209 default: return Qnil
;
2214 rb_special_singleton_class(VALUE obj
)
2216 return special_singleton_class_of(obj
);
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.
2229 singleton_class_of(VALUE obj
)
2233 switch (TYPE(obj
)) {
2238 rb_raise(rb_eTypeError
, "can't define singleton");
2243 klass
= special_singleton_class_of(obj
);
2245 rb_bug("unknown immediate %p", (void *)obj
);
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
));
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
) {
2282 * Returns the singleton class of `obj`, or nil if obj is not a
2285 * @param obj an arbitrary object.
2286 * @return the singleton class or nil.
2289 rb_singleton_class_get(VALUE obj
)
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
;
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
);
2318 * \addtogroup defmethod
2322 #ifdef rb_define_singleton_method
2323 #undef rb_define_singleton_method
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
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
2345 rb_define_global_function(const char *name
, VALUE (*func
)(ANYARGS
), int argc
)
2347 rb_define_module_function(rb_mKernel
, name
, func
, argc
);
2351 rb_define_alias(VALUE klass
, const char *name1
, const char *name2
)
2353 rb_alias(klass
, rb_intern(name1
), rb_intern(name2
));
2357 rb_define_attr(VALUE klass
, const char *name
, int read
, int write
)
2359 rb_attr(klass
, rb_intern(name
), read
, write
, FALSE
);
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");
2369 rb_str_cat_cstr(error_message
, ": ");
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
));
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
));
2390 unknown_keyword_error(VALUE hash
, const ID
*table
, int keywords
)
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
));
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
);
2412 rb_extract_keywords(VALUE
*orighash
)
2414 VALUE parthash
[2] = {0, 0};
2415 VALUE hash
= *orighash
;
2417 if (RHASH_EMPTY_P(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
));
2430 rb_get_kwargs(VALUE keyword_hash
, const ID
*table
, int required
, int optional
, VALUE
*values
)
2434 VALUE missing
= Qnil
;
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;
2446 optional
= -1-optional
;
2449 for (; i
< required
; i
++) {
2450 VALUE keyword
= ID2SYM(table
[i
]);
2452 if (extract_kwarg(keyword
, values
[i
])) {
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
);
2464 if (optional
&& keyword_hash
) {
2465 for (i
= 0; i
< optional
; i
++) {
2466 if (extract_kwarg(ID2SYM(table
[required
+i
]), values
[required
+i
])) {
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
++) {
2482 #undef extract_kwarg
2485 struct rb_scan_args_t
{
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
;
2504 arg
->n_lead
= *p
- '0';
2507 arg
->n_opt
= *p
- '0';
2516 arg
->n_trail
= *p
- '0';
2528 rb_fatal("bad scan arg format: %s", fmt
);
2533 rb_scan_args_assign(const struct rb_scan_args_t
*arg
, int argc
, const VALUE
*const argv
, va_list vargs
)
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
);
2556 if (argc
< n_mand
) {
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
];
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
];
2574 if (var
) *var
= Qnil
;
2577 /* capture variable length arguments */
2579 int n_var
= argc
- argi
- n_trail
;
2581 var
= rb_scan_args_next_param();
2583 if (var
) *var
= rb_ary_new_from_values(n_var
, &argv
[argi
]);
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
];
2596 /* capture an option hash - phase 2: assignment */
2598 var
= rb_scan_args_next_param();
2599 if (var
) *var
= hash
;
2601 /* capture iterator block */
2603 var
= rb_scan_args_next_param();
2604 if (rb_block_given_p()) {
2605 *var
= rb_block_proc();
2618 #undef rb_scan_args_next_param
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
;
2635 rb_error_arity(argc
, n_mand
, f_var
? UNLIMITED_ARGUMENTS
: n_mand
+ n_opt
);
2636 UNREACHABLE_RETURN(-1);
2641 rb_scan_args(int argc
, const VALUE
*argv
, const char *fmt
, ...)
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
);
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
, ...)
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
);
2662 return rb_scan_args_result(&arg
, argc
);