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"
33 #define id_attached id__attached__
35 #define METACLASS_OF(k) RBASIC(k)->klass
36 #define SET_METACLASS_OF(k, cls) RBASIC_SET_CLASS(k, cls)
38 RUBY_EXTERN rb_serial_t ruby_vm_global_cvar_state
;
40 static rb_subclass_entry_t
*
41 push_subclass_entry_to_list(VALUE super
, VALUE klass
)
43 rb_subclass_entry_t
*entry
, *head
;
45 entry
= ZALLOC(rb_subclass_entry_t
);
48 head
= RCLASS_SUBCLASSES(super
);
50 head
= ZALLOC(rb_subclass_entry_t
);
51 RCLASS_SUBCLASSES(super
) = head
;
53 entry
->next
= head
->next
;
57 head
->next
->prev
= entry
;
65 rb_class_subclass_add(VALUE super
, VALUE klass
)
67 if (super
&& super
!= Qundef
) {
68 rb_subclass_entry_t
*entry
= push_subclass_entry_to_list(super
, klass
);
69 RCLASS_SUBCLASS_ENTRY(klass
) = entry
;
74 rb_module_add_to_subclasses_list(VALUE module
, VALUE iclass
)
76 rb_subclass_entry_t
*entry
= push_subclass_entry_to_list(module
, iclass
);
77 RCLASS_MODULE_SUBCLASS_ENTRY(iclass
) = entry
;
81 rb_class_remove_subclass_head(VALUE klass
)
83 rb_subclass_entry_t
*head
= RCLASS_SUBCLASSES(klass
);
87 head
->next
->prev
= NULL
;
89 RCLASS_SUBCLASSES(klass
) = NULL
;
95 rb_class_remove_from_super_subclasses(VALUE klass
)
97 rb_subclass_entry_t
*entry
= RCLASS_SUBCLASS_ENTRY(klass
);
100 rb_subclass_entry_t
*prev
= entry
->prev
, *next
= entry
->next
;
112 RCLASS_SUBCLASS_ENTRY(klass
) = NULL
;
116 rb_class_remove_from_module_subclasses(VALUE klass
)
118 rb_subclass_entry_t
*entry
= RCLASS_MODULE_SUBCLASS_ENTRY(klass
);
121 rb_subclass_entry_t
*prev
= entry
->prev
, *next
= entry
->next
;
133 RCLASS_MODULE_SUBCLASS_ENTRY(klass
) = NULL
;
137 rb_class_foreach_subclass(VALUE klass
, void (*f
)(VALUE
, VALUE
), VALUE arg
)
139 // RCLASS_SUBCLASSES should always point to our head element which has NULL klass
140 rb_subclass_entry_t
*cur
= RCLASS_SUBCLASSES(klass
);
141 // if we have a subclasses list, then the head is a placeholder with no valid
142 // class. So ignore it and use the next element in the list (if one exists)
144 RUBY_ASSERT(!cur
->klass
);
148 /* do not be tempted to simplify this loop into a for loop, the order of
149 operations is important here if `f` modifies the linked list */
151 VALUE curklass
= cur
->klass
;
153 // do not trigger GC during f, otherwise the cur will become
154 // a dangling pointer if the subclass is collected
160 class_detach_subclasses(VALUE klass
, VALUE arg
)
162 rb_class_remove_from_super_subclasses(klass
);
166 rb_class_detach_subclasses(VALUE klass
)
168 rb_class_foreach_subclass(klass
, class_detach_subclasses
, Qnil
);
172 class_detach_module_subclasses(VALUE klass
, VALUE arg
)
174 rb_class_remove_from_module_subclasses(klass
);
178 rb_class_detach_module_subclasses(VALUE klass
)
180 rb_class_foreach_subclass(klass
, class_detach_module_subclasses
, Qnil
);
184 * Allocates a struct RClass for a new class.
186 * \param flags initial value for basic.flags of the returned class.
187 * \param klass the class of the returned class.
188 * \return an uninitialized Class object.
189 * \pre \p klass must refer \c Class class or an ancestor of Class.
190 * \pre \code (flags | T_CLASS) != 0 \endcode
191 * \post the returned class can safely be \c #initialize 'd.
193 * \note this function is not Class#allocate.
196 class_alloc(VALUE flags
, VALUE klass
)
198 size_t alloc_size
= sizeof(struct RClass
);
201 alloc_size
+= sizeof(rb_classext_t
);
205 flags
|= FL_PROMOTED1
/* start from age == 2 */;
206 if (RGENGC_WB_PROTECTED_CLASS
) flags
|= FL_WB_PROTECTED
;
207 RVARGC_NEWOBJ_OF(obj
, struct RClass
, klass
, flags
, alloc_size
);
210 memset(RCLASS_EXT(obj
), 0, sizeof(rb_classext_t
));
212 obj
->ptr
= ZALLOC(rb_classext_t
);
216 RCLASS_IV_TBL(obj) = 0;
217 RCLASS_CONST_TBL(obj) = 0;
218 RCLASS_M_TBL(obj) = 0;
219 RCLASS_IV_INDEX_TBL(obj) = 0;
220 RCLASS_SET_SUPER((VALUE)obj, 0);
221 RCLASS_SUBCLASSES(obj) = NULL;
222 RCLASS_PARENT_SUBCLASSES(obj) = NULL;
223 RCLASS_MODULE_SUBCLASSES(obj) = NULL;
225 RCLASS_SET_ORIGIN((VALUE
)obj
, (VALUE
)obj
);
226 RCLASS_SERIAL(obj
) = rb_next_class_serial();
227 RB_OBJ_WRITE(obj
, &RCLASS_REFINED_CLASS(obj
), Qnil
);
228 RCLASS_ALLOCATOR(obj
) = 0;
234 RCLASS_M_TBL_INIT(VALUE c
)
236 RCLASS_M_TBL(c
) = rb_id_table_create(0);
240 * A utility function that wraps class_alloc.
242 * allocates a class and initializes safely.
243 * \param super a class from which the new class derives.
244 * \return a class object.
245 * \pre \a super must be a class.
246 * \post the metaclass of the new class is Class.
249 rb_class_boot(VALUE super
)
251 VALUE klass
= class_alloc(T_CLASS
, rb_cClass
);
253 RCLASS_SET_SUPER(klass
, super
);
254 RCLASS_M_TBL_INIT(klass
);
260 rb_check_inheritable(VALUE super
)
262 if (!RB_TYPE_P(super
, T_CLASS
)) {
263 rb_raise(rb_eTypeError
, "superclass must be an instance of Class (given an instance of %"PRIsVALUE
")",
264 rb_obj_class(super
));
266 if (RBASIC(super
)->flags
& FL_SINGLETON
) {
267 rb_raise(rb_eTypeError
, "can't make subclass of singleton class");
269 if (super
== rb_cClass
) {
270 rb_raise(rb_eTypeError
, "can't make subclass of Class");
275 rb_class_new(VALUE super
)
277 Check_Type(super
, T_CLASS
);
278 rb_check_inheritable(super
);
279 return rb_class_boot(super
);
283 rb_class_s_alloc(VALUE klass
)
285 return rb_class_boot(0);
289 clone_method(VALUE old_klass
, VALUE new_klass
, ID mid
, const rb_method_entry_t
*me
)
291 if (me
->def
->type
== VM_METHOD_TYPE_ISEQ
) {
293 rb_vm_rewrite_cref(me
->def
->body
.iseq
.cref
, old_klass
, new_klass
, &new_cref
);
294 rb_add_method_iseq(new_klass
, mid
, me
->def
->body
.iseq
.iseqptr
, new_cref
, METHOD_ENTRY_VISI(me
));
297 rb_method_entry_set(new_klass
, mid
, me
, METHOD_ENTRY_VISI(me
));
301 struct clone_method_arg
{
306 static enum rb_id_table_iterator_result
307 clone_method_i(ID key
, VALUE value
, void *data
)
309 const struct clone_method_arg
*arg
= (struct clone_method_arg
*)data
;
310 clone_method(arg
->old_klass
, arg
->new_klass
, key
, (const rb_method_entry_t
*)value
);
311 return ID_TABLE_CONTINUE
;
314 struct clone_const_arg
{
316 struct rb_id_table
*tbl
;
320 clone_const(ID key
, const rb_const_entry_t
*ce
, struct clone_const_arg
*arg
)
322 rb_const_entry_t
*nce
= ALLOC(rb_const_entry_t
);
323 MEMCPY(nce
, ce
, rb_const_entry_t
, 1);
324 RB_OBJ_WRITTEN(arg
->klass
, Qundef
, ce
->value
);
325 RB_OBJ_WRITTEN(arg
->klass
, Qundef
, ce
->file
);
327 rb_id_table_insert(arg
->tbl
, key
, (VALUE
)nce
);
328 return ID_TABLE_CONTINUE
;
331 static enum rb_id_table_iterator_result
332 clone_const_i(ID key
, VALUE value
, void *data
)
334 return clone_const(key
, (const rb_const_entry_t
*)value
, data
);
338 class_init_copy_check(VALUE clone
, VALUE orig
)
340 if (orig
== rb_cBasicObject
) {
341 rb_raise(rb_eTypeError
, "can't copy the root class");
343 if (RCLASS_SUPER(clone
) != 0 || clone
== rb_cBasicObject
) {
344 rb_raise(rb_eTypeError
, "already initialized class");
346 if (FL_TEST(orig
, FL_SINGLETON
)) {
347 rb_raise(rb_eTypeError
, "can't copy singleton class");
352 copy_tables(VALUE clone
, VALUE orig
)
354 if (RCLASS_IV_TBL(clone
)) {
355 st_free_table(RCLASS_IV_TBL(clone
));
356 RCLASS_IV_TBL(clone
) = 0;
358 if (RCLASS_CONST_TBL(clone
)) {
359 rb_free_const_table(RCLASS_CONST_TBL(clone
));
360 RCLASS_CONST_TBL(clone
) = 0;
362 RCLASS_M_TBL(clone
) = 0;
363 if (RCLASS_IV_TBL(orig
)) {
366 rb_iv_tbl_copy(clone
, orig
);
367 CONST_ID(id
, "__tmp_classpath__");
368 st_delete(RCLASS_IV_TBL(clone
), &id
, 0);
369 CONST_ID(id
, "__classpath__");
370 st_delete(RCLASS_IV_TBL(clone
), &id
, 0);
371 CONST_ID(id
, "__classid__");
372 st_delete(RCLASS_IV_TBL(clone
), &id
, 0);
374 if (RCLASS_CONST_TBL(orig
)) {
375 struct clone_const_arg arg
;
377 arg
.tbl
= RCLASS_CONST_TBL(clone
) = rb_id_table_create(0);
379 rb_id_table_foreach(RCLASS_CONST_TBL(orig
), clone_const_i
, &arg
);
383 static bool ensure_origin(VALUE klass
);
386 * If this flag is set, that module is allocated but not initialized yet.
388 enum {RMODULE_ALLOCATED_BUT_NOT_INITIALIZED
= RUBY_FL_USER5
};
391 RMODULE_UNINITIALIZED(VALUE module
)
393 return FL_TEST_RAW(module
, RMODULE_ALLOCATED_BUT_NOT_INITIALIZED
);
397 rb_module_set_initialized(VALUE mod
)
399 FL_UNSET_RAW(mod
, RMODULE_ALLOCATED_BUT_NOT_INITIALIZED
);
400 /* no more re-initialization */
404 rb_module_check_initializable(VALUE mod
)
406 if (!RMODULE_UNINITIALIZED(mod
)) {
407 rb_raise(rb_eTypeError
, "already initialized module");
409 RB_OBJ_WRITE(mod
, &RCLASS(mod
)->super
, 0);
414 rb_mod_init_copy(VALUE clone
, VALUE orig
)
416 switch (BUILTIN_TYPE(clone
)) {
419 class_init_copy_check(clone
, orig
);
422 rb_module_check_initializable(clone
);
427 if (!OBJ_INIT_COPY(clone
, orig
)) return clone
;
429 /* cloned flag is refer at constant inline cache
430 * see vm_get_const_key_cref() in vm_insnhelper.c
432 FL_SET(clone
, RCLASS_CLONED
);
433 FL_SET(orig
, RCLASS_CLONED
);
435 if (!FL_TEST(CLASS_OF(clone
), FL_SINGLETON
)) {
436 RBASIC_SET_CLASS(clone
, rb_singleton_class_clone(orig
));
437 rb_singleton_class_attached(RBASIC(clone
)->klass
, (VALUE
)clone
);
439 RCLASS_ALLOCATOR(clone
) = RCLASS_ALLOCATOR(orig
);
440 copy_tables(clone
, orig
);
441 if (RCLASS_M_TBL(orig
)) {
442 struct clone_method_arg arg
;
443 arg
.old_klass
= orig
;
444 arg
.new_klass
= clone
;
445 RCLASS_M_TBL_INIT(clone
);
446 rb_id_table_foreach(RCLASS_M_TBL(orig
), clone_method_i
, &arg
);
449 if (RCLASS_ORIGIN(orig
) == orig
) {
450 RCLASS_SET_SUPER(clone
, RCLASS_SUPER(orig
));
453 VALUE p
= RCLASS_SUPER(orig
);
454 VALUE orig_origin
= RCLASS_ORIGIN(orig
);
455 VALUE prev_clone_p
= clone
;
456 VALUE origin_stack
= rb_ary_tmp_new(2);
463 ensure_origin(clone
);
464 clone_origin
= RCLASS_ORIGIN(clone
);
466 while (p
&& p
!= orig_origin
) {
467 if (BUILTIN_TYPE(p
) != T_ICLASS
) {
468 rb_bug("non iclass between module/class and origin");
470 clone_p
= class_alloc(RBASIC(p
)->flags
, RBASIC(p
)->klass
);
471 RCLASS_SET_SUPER(prev_clone_p
, clone_p
);
472 prev_clone_p
= clone_p
;
473 RCLASS_M_TBL(clone_p
) = RCLASS_M_TBL(p
);
474 RCLASS_CONST_TBL(clone_p
) = RCLASS_CONST_TBL(p
);
475 RCLASS_IV_TBL(clone_p
) = RCLASS_IV_TBL(p
);
476 RCLASS_ALLOCATOR(clone_p
) = RCLASS_ALLOCATOR(p
);
477 if (RB_TYPE_P(clone
, T_CLASS
)) {
478 RCLASS_SET_INCLUDER(clone_p
, clone
);
481 if (p
!= RCLASS_ORIGIN(p
)) {
483 origin
[1] = RCLASS_ORIGIN(p
);
484 rb_ary_cat(origin_stack
, origin
, 2);
486 else if ((origin_len
= RARRAY_LEN(origin_stack
)) > 1 &&
487 RARRAY_AREF(origin_stack
, origin_len
- 1) == p
) {
488 RCLASS_SET_ORIGIN(RARRAY_AREF(origin_stack
, (origin_len
-= 2)), clone_p
);
489 RICLASS_SET_ORIGIN_SHARED_MTBL(clone_p
);
490 rb_ary_resize(origin_stack
, origin_len
);
491 add_subclass
= FALSE
;
494 rb_module_add_to_subclasses_list(RBASIC(p
)->klass
, clone_p
);
499 if (p
== orig_origin
) {
501 RCLASS_SET_SUPER(clone_p
, clone_origin
);
502 RCLASS_SET_SUPER(clone_origin
, RCLASS_SUPER(orig_origin
));
504 copy_tables(clone_origin
, orig_origin
);
505 if (RCLASS_M_TBL(orig_origin
)) {
506 struct clone_method_arg arg
;
507 arg
.old_klass
= orig
;
508 arg
.new_klass
= clone
;
509 RCLASS_M_TBL_INIT(clone_origin
);
510 rb_id_table_foreach(RCLASS_M_TBL(orig_origin
), clone_method_i
, &arg
);
514 rb_bug("no origin for class that has origin");
522 rb_singleton_class_clone(VALUE obj
)
524 return rb_singleton_class_clone_and_attach(obj
, Qundef
);
527 // Clone and return the singleton class of `obj` if it has been created and is attached to `obj`.
529 rb_singleton_class_clone_and_attach(VALUE obj
, VALUE attach
)
531 const VALUE klass
= RBASIC(obj
)->klass
;
533 // Note that `rb_singleton_class()` can create situations where `klass` is
534 // attached to an object other than `obj`. In which case `obj` does not have
535 // a material singleton class attached yet and there is no singleton class
537 if (!(FL_TEST(klass
, FL_SINGLETON
) && rb_attr_get(klass
, id_attached
) == obj
)) {
542 /* copy singleton(unnamed) class */
543 bool klass_of_clone_is_new
;
544 VALUE clone
= class_alloc(RBASIC(klass
)->flags
, 0);
546 if (BUILTIN_TYPE(obj
) == T_CLASS
) {
547 klass_of_clone_is_new
= true;
548 RBASIC_SET_CLASS(clone
, clone
);
551 VALUE klass_metaclass_clone
= rb_singleton_class_clone(klass
);
552 // When `METACLASS_OF(klass) == klass_metaclass_clone`, it means the
553 // recursive call did not clone `METACLASS_OF(klass)`.
554 klass_of_clone_is_new
= (METACLASS_OF(klass
) != klass_metaclass_clone
);
555 RBASIC_SET_CLASS(clone
, klass_metaclass_clone
);
558 RCLASS_SET_SUPER(clone
, RCLASS_SUPER(klass
));
559 RCLASS_ALLOCATOR(clone
) = RCLASS_ALLOCATOR(klass
);
560 if (RCLASS_IV_TBL(klass
)) {
561 rb_iv_tbl_copy(clone
, klass
);
563 if (RCLASS_CONST_TBL(klass
)) {
564 struct clone_const_arg arg
;
565 arg
.tbl
= RCLASS_CONST_TBL(clone
) = rb_id_table_create(0);
567 rb_id_table_foreach(RCLASS_CONST_TBL(klass
), clone_const_i
, &arg
);
569 if (attach
!= Qundef
) {
570 rb_singleton_class_attached(clone
, attach
);
572 RCLASS_M_TBL_INIT(clone
);
574 struct clone_method_arg arg
;
575 arg
.old_klass
= klass
;
576 arg
.new_klass
= clone
;
577 rb_id_table_foreach(RCLASS_M_TBL(klass
), clone_method_i
, &arg
);
579 if (klass_of_clone_is_new
) {
580 rb_singleton_class_attached(RBASIC(clone
)->klass
, clone
);
582 FL_SET(clone
, FL_SINGLETON
);
589 rb_singleton_class_attached(VALUE klass
, VALUE obj
)
591 if (FL_TEST(klass
, FL_SINGLETON
)) {
592 rb_class_ivar_set(klass
, id_attached
, obj
);
597 * whether k is a meta^(n)-class of Class class
598 * @retval 1 if \a k is a meta^(n)-class of Class class (n >= 0)
599 * @retval 0 otherwise
601 #define META_CLASS_OF_CLASS_CLASS_P(k) (METACLASS_OF(k) == (k))
604 rb_singleton_class_has_metaclass_p(VALUE sklass
)
606 return rb_attr_get(METACLASS_OF(sklass
), id_attached
) == sklass
;
610 rb_singleton_class_internal_p(VALUE sklass
)
612 return (RB_TYPE_P(rb_attr_get(sklass
, id_attached
), T_CLASS
) &&
613 !rb_singleton_class_has_metaclass_p(sklass
));
617 * whether k has a metaclass
618 * @retval 1 if \a k has a metaclass
619 * @retval 0 otherwise
621 #define HAVE_METACLASS_P(k) \
622 (FL_TEST(METACLASS_OF(k), FL_SINGLETON) && \
623 rb_singleton_class_has_metaclass_p(k))
626 * ensures \a klass belongs to its own eigenclass.
627 * @return the eigenclass of \a klass
628 * @post \a klass belongs to the returned eigenclass.
629 * i.e. the attached object of the eigenclass is \a klass.
630 * @note this macro creates a new eigenclass if necessary.
632 #define ENSURE_EIGENCLASS(klass) \
633 (HAVE_METACLASS_P(klass) ? METACLASS_OF(klass) : make_metaclass(klass))
637 * Creates a metaclass of \a klass
638 * \param klass a class
639 * \return created metaclass for the class
640 * \pre \a klass is a Class object
641 * \pre \a klass has no singleton class.
642 * \post the class of \a klass is the returned class.
643 * \post the returned class is meta^(n+1)-class when \a klass is a meta^(n)-klass for n >= 0
646 make_metaclass(VALUE klass
)
649 VALUE metaclass
= rb_class_boot(Qundef
);
651 FL_SET(metaclass
, FL_SINGLETON
);
652 rb_singleton_class_attached(metaclass
, klass
);
654 if (META_CLASS_OF_CLASS_CLASS_P(klass
)) {
655 SET_METACLASS_OF(klass
, metaclass
);
656 SET_METACLASS_OF(metaclass
, metaclass
);
659 VALUE tmp
= METACLASS_OF(klass
); /* for a meta^(n)-class klass, tmp is meta^(n)-class of Class class */
660 SET_METACLASS_OF(klass
, metaclass
);
661 SET_METACLASS_OF(metaclass
, ENSURE_EIGENCLASS(tmp
));
664 super
= RCLASS_SUPER(klass
);
665 while (RB_TYPE_P(super
, T_ICLASS
)) super
= RCLASS_SUPER(super
);
666 RCLASS_SET_SUPER(metaclass
, super
? ENSURE_EIGENCLASS(super
) : rb_cClass
);
672 * Creates a singleton class for \a obj.
673 * \pre \a obj must not a immediate nor a special const.
674 * \pre \a obj must not a Class object.
675 * \pre \a obj has no singleton class.
678 make_singleton_class(VALUE obj
)
680 VALUE orig_class
= RBASIC(obj
)->klass
;
681 VALUE klass
= rb_class_boot(orig_class
);
683 FL_SET(klass
, FL_SINGLETON
);
684 RBASIC_SET_CLASS(obj
, klass
);
685 rb_singleton_class_attached(klass
, obj
);
687 SET_METACLASS_OF(klass
, METACLASS_OF(rb_class_real(orig_class
)));
693 boot_defclass(const char *name
, VALUE super
)
695 VALUE obj
= rb_class_boot(super
);
696 ID id
= rb_intern(name
);
698 rb_const_set((rb_cObject
? rb_cObject
: obj
), id
, obj
);
699 rb_vm_add_root_module(obj
);
703 /***********************************************************************
705 * Document-class: Refinement
707 * Refinement is a class of the +self+ (current context) inside +refine+
708 * statement. It allows to import methods from other modules, see #import_methods.
713 * Document-method: Refinement#import_methods
716 * import_methods(module, ...) -> self
718 * Imports methods from modules. Unlike Module#include,
719 * Refinement#import_methods copies methods and adds them into the refinement,
720 * so the refinement is activated in the imported methods.
722 * Note that due to method copying, only methods defined in Ruby code can be imported.
732 * import_methods StrUtils
742 * import_methods Enumerable
743 * # Can't import method which is not defined with Ruby code: Enumerable#drop
750 refinement_import_methods(int argc
, VALUE
*argv
, VALUE refinement
)
756 Init_class_hierarchy(void)
758 rb_cBasicObject
= boot_defclass("BasicObject", 0);
759 rb_cObject
= boot_defclass("Object", rb_cBasicObject
);
760 rb_gc_register_mark_object(rb_cObject
);
762 /* resolve class name ASAP for order-independence */
763 rb_set_class_path_string(rb_cObject
, rb_cObject
, rb_fstring_lit("Object"));
765 rb_cModule
= boot_defclass("Module", rb_cObject
);
766 rb_cClass
= boot_defclass("Class", rb_cModule
);
767 rb_cRefinement
= boot_defclass("Refinement", rb_cModule
);
770 // we pretend it to be public, otherwise RDoc will ignore it
771 rb_define_method(rb_cRefinement
, "import_methods", refinement_import_methods
, -1);
774 rb_const_set(rb_cObject
, rb_intern_const("BasicObject"), rb_cBasicObject
);
775 RBASIC_SET_CLASS(rb_cClass
, rb_cClass
);
776 RBASIC_SET_CLASS(rb_cModule
, rb_cClass
);
777 RBASIC_SET_CLASS(rb_cObject
, rb_cClass
);
778 RBASIC_SET_CLASS(rb_cRefinement
, rb_cClass
);
779 RBASIC_SET_CLASS(rb_cBasicObject
, rb_cClass
);
781 ENSURE_EIGENCLASS(rb_cRefinement
);
787 * Creates a new *singleton class* for an object.
789 * \pre \a obj has no singleton class.
790 * \note DO NOT USE the function in an extension libraries. Use \ref rb_singleton_class.
791 * \param obj An object.
792 * \param unused ignored.
793 * \return The singleton class of the object.
796 rb_make_metaclass(VALUE obj
, VALUE unused
)
798 if (BUILTIN_TYPE(obj
) == T_CLASS
) {
799 return make_metaclass(obj
);
802 return make_singleton_class(obj
);
807 rb_define_class_id(ID id
, VALUE super
)
811 if (!super
) super
= rb_cObject
;
812 klass
= rb_class_new(super
);
813 rb_make_metaclass(klass
, RBASIC(super
)->klass
);
820 * Calls Class#inherited.
821 * \param super A class which will be called #inherited.
822 * NULL means Object class.
823 * \param klass A Class object which derived from \a super
824 * \return the value \c Class#inherited's returns
825 * \pre Each of \a super and \a klass must be a \c Class object.
827 MJIT_FUNC_EXPORTED VALUE
828 rb_class_inherited(VALUE super
, VALUE klass
)
831 if (!super
) super
= rb_cObject
;
832 CONST_ID(inherited
, "inherited");
833 return rb_funcall(super
, inherited
, 1, klass
);
837 rb_define_class(const char *name
, VALUE super
)
842 id
= rb_intern(name
);
843 if (rb_const_defined(rb_cObject
, id
)) {
844 klass
= rb_const_get(rb_cObject
, id
);
845 if (!RB_TYPE_P(klass
, T_CLASS
)) {
846 rb_raise(rb_eTypeError
, "%s is not a class (%"PRIsVALUE
")",
847 name
, rb_obj_class(klass
));
849 if (rb_class_real(RCLASS_SUPER(klass
)) != super
) {
850 rb_raise(rb_eTypeError
, "superclass mismatch for class %s", name
);
853 /* Class may have been defined in Ruby and not pin-rooted */
854 rb_vm_add_root_module(klass
);
858 rb_raise(rb_eArgError
, "no super class for `%s'", name
);
860 klass
= rb_define_class_id(id
, super
);
861 rb_vm_add_root_module(klass
);
862 rb_const_set(rb_cObject
, id
, klass
);
863 rb_class_inherited(super
, klass
);
869 rb_define_class_under(VALUE outer
, const char *name
, VALUE super
)
871 return rb_define_class_id_under(outer
, rb_intern(name
), super
);
875 rb_define_class_id_under(VALUE outer
, ID id
, VALUE super
)
879 if (rb_const_defined_at(outer
, id
)) {
880 klass
= rb_const_get_at(outer
, id
);
881 if (!RB_TYPE_P(klass
, T_CLASS
)) {
882 rb_raise(rb_eTypeError
, "%"PRIsVALUE
"::%"PRIsVALUE
" is not a class"
884 outer
, rb_id2str(id
), rb_obj_class(klass
));
886 if (rb_class_real(RCLASS_SUPER(klass
)) != super
) {
887 rb_raise(rb_eTypeError
, "superclass mismatch for class "
888 "%"PRIsVALUE
"::%"PRIsVALUE
""
889 " (%"PRIsVALUE
" is given but was %"PRIsVALUE
")",
890 outer
, rb_id2str(id
), RCLASS_SUPER(klass
), super
);
892 /* Class may have been defined in Ruby and not pin-rooted */
893 rb_vm_add_root_module(klass
);
898 rb_raise(rb_eArgError
, "no super class for `%"PRIsVALUE
"::%"PRIsVALUE
"'",
899 rb_class_path(outer
), rb_id2str(id
));
901 klass
= rb_define_class_id(id
, super
);
902 rb_set_class_path_string(klass
, outer
, rb_id2str(id
));
903 rb_const_set(outer
, id
, klass
);
904 rb_class_inherited(super
, klass
);
905 rb_vm_add_root_module(klass
);
911 rb_module_s_alloc(VALUE klass
)
913 VALUE mod
= class_alloc(T_MODULE
, klass
);
914 RCLASS_M_TBL_INIT(mod
);
915 FL_SET(mod
, RMODULE_ALLOCATED_BUT_NOT_INITIALIZED
);
920 module_new(VALUE klass
)
922 VALUE mdl
= class_alloc(T_MODULE
, klass
);
923 RCLASS_M_TBL_INIT(mdl
);
930 return module_new(rb_cModule
);
934 rb_refinement_new(void)
936 return module_new(rb_cRefinement
);
939 // Kept for compatibility. Use rb_module_new() instead.
941 rb_define_module_id(ID id
)
943 return rb_module_new();
947 rb_define_module(const char *name
)
952 id
= rb_intern(name
);
953 if (rb_const_defined(rb_cObject
, id
)) {
954 module
= rb_const_get(rb_cObject
, id
);
955 if (!RB_TYPE_P(module
, T_MODULE
)) {
956 rb_raise(rb_eTypeError
, "%s is not a module (%"PRIsVALUE
")",
957 name
, rb_obj_class(module
));
959 /* Module may have been defined in Ruby and not pin-rooted */
960 rb_vm_add_root_module(module
);
963 module
= rb_module_new();
964 rb_vm_add_root_module(module
);
965 rb_const_set(rb_cObject
, id
, module
);
971 rb_define_module_under(VALUE outer
, const char *name
)
973 return rb_define_module_id_under(outer
, rb_intern(name
));
977 rb_define_module_id_under(VALUE outer
, ID id
)
981 if (rb_const_defined_at(outer
, id
)) {
982 module
= rb_const_get_at(outer
, id
);
983 if (!RB_TYPE_P(module
, T_MODULE
)) {
984 rb_raise(rb_eTypeError
, "%"PRIsVALUE
"::%"PRIsVALUE
" is not a module"
986 outer
, rb_id2str(id
), rb_obj_class(module
));
988 /* Module may have been defined in Ruby and not pin-rooted */
989 rb_gc_register_mark_object(module
);
992 module
= rb_module_new();
993 rb_const_set(outer
, id
, module
);
994 rb_set_class_path_string(module
, outer
, rb_id2str(id
));
995 rb_gc_register_mark_object(module
);
1001 rb_include_class_new(VALUE module
, VALUE super
)
1003 VALUE klass
= class_alloc(T_ICLASS
, rb_cClass
);
1005 RCLASS_M_TBL(klass
) = RCLASS_M_TBL(module
);
1007 RCLASS_SET_ORIGIN(klass
, klass
);
1008 if (BUILTIN_TYPE(module
) == T_ICLASS
) {
1009 module
= RBASIC(module
)->klass
;
1011 RUBY_ASSERT(!RB_TYPE_P(module
, T_ICLASS
));
1012 if (!RCLASS_IV_TBL(module
)) {
1013 RCLASS_IV_TBL(module
) = st_init_numtable();
1015 if (!RCLASS_CONST_TBL(module
)) {
1016 RCLASS_CONST_TBL(module
) = rb_id_table_create(0);
1018 RCLASS_IV_TBL(klass
) = RCLASS_IV_TBL(module
);
1019 RCLASS_CVC_TBL(klass
) = RCLASS_CVC_TBL(module
);
1020 RCLASS_CONST_TBL(klass
) = RCLASS_CONST_TBL(module
);
1022 RCLASS_SET_SUPER(klass
, super
);
1023 RBASIC_SET_CLASS(klass
, module
);
1025 return (VALUE
)klass
;
1028 static int include_modules_at(const VALUE klass
, VALUE c
, VALUE module
, int search_super
);
1031 ensure_includable(VALUE klass
, VALUE module
)
1033 rb_class_modify_check(klass
);
1034 Check_Type(module
, T_MODULE
);
1035 rb_module_set_initialized(module
);
1036 if (!NIL_P(rb_refinement_module_get_refined_class(module
))) {
1037 rb_raise(rb_eArgError
, "refinement module is not allowed");
1042 rb_include_module(VALUE klass
, VALUE module
)
1046 ensure_includable(klass
, module
);
1048 changed
= include_modules_at(klass
, RCLASS_ORIGIN(klass
), module
, TRUE
);
1050 rb_raise(rb_eArgError
, "cyclic include detected");
1052 if (RB_TYPE_P(klass
, T_MODULE
)) {
1053 rb_subclass_entry_t
*iclass
= RCLASS_SUBCLASSES(klass
);
1054 // skip the placeholder subclass entry at the head of the list
1055 if (iclass
&& iclass
->next
) {
1056 RUBY_ASSERT(!iclass
->klass
);
1057 iclass
= iclass
->next
;
1062 VALUE check_class
= iclass
->klass
;
1063 while (check_class
) {
1064 if (RB_TYPE_P(check_class
, T_ICLASS
) &&
1065 (RBASIC(check_class
)->klass
== module
)) {
1068 check_class
= RCLASS_SUPER(check_class
);
1072 include_modules_at(iclass
->klass
, RCLASS_ORIGIN(iclass
->klass
), module
, TRUE
);
1074 iclass
= iclass
->next
;
1079 static enum rb_id_table_iterator_result
1080 add_refined_method_entry_i(ID key
, VALUE value
, void *data
)
1082 rb_add_refined_method_entry((VALUE
)data
, key
);
1083 return ID_TABLE_CONTINUE
;
1086 static enum rb_id_table_iterator_result
1087 clear_module_cache_i(ID id
, VALUE val
, void *data
)
1089 VALUE klass
= (VALUE
)data
;
1090 rb_clear_method_cache(klass
, id
);
1091 return ID_TABLE_CONTINUE
;
1095 module_in_super_chain(const VALUE klass
, VALUE module
)
1097 struct rb_id_table
*const klass_m_tbl
= RCLASS_M_TBL(RCLASS_ORIGIN(klass
));
1100 if (klass_m_tbl
== RCLASS_M_TBL(module
))
1102 module
= RCLASS_SUPER(module
);
1109 do_include_modules_at(const VALUE klass
, VALUE c
, VALUE module
, int search_super
, bool check_cyclic
)
1111 VALUE p
, iclass
, origin_stack
= 0;
1112 int method_changed
= 0, constant_changed
= 0, add_subclass
;
1114 VALUE klass_origin
= RCLASS_ORIGIN(klass
);
1115 VALUE original_klass
= klass
;
1117 if (check_cyclic
&& module_in_super_chain(klass
, module
))
1122 int superclass_seen
= FALSE
;
1123 struct rb_id_table
*tbl
;
1128 if (klass_origin
!= c
|| search_super
) {
1129 /* ignore if the module included already in superclasses for include,
1130 * ignore if the module included before origin class for prepend
1132 for (p
= RCLASS_SUPER(klass
); p
; p
= RCLASS_SUPER(p
)) {
1133 int type
= BUILTIN_TYPE(p
);
1134 if (klass_origin
== p
&& !search_super
)
1138 if (type
== T_ICLASS
) {
1139 if (RCLASS_M_TBL(p
) == RCLASS_M_TBL(module
)) {
1140 if (!superclass_seen
&& c_seen
) {
1141 c
= p
; /* move insertion point */
1146 else if (type
== T_CLASS
) {
1147 superclass_seen
= TRUE
;
1152 VALUE super_class
= RCLASS_SUPER(c
);
1154 // invalidate inline method cache
1155 RB_DEBUG_COUNTER_INC(cvar_include_invalidate
);
1156 ruby_vm_global_cvar_state
++;
1157 tbl
= RCLASS_M_TBL(module
);
1158 if (tbl
&& rb_id_table_size(tbl
)) {
1159 if (search_super
) { // include
1160 if (super_class
&& !RB_TYPE_P(super_class
, T_MODULE
)) {
1161 rb_id_table_foreach(tbl
, clear_module_cache_i
, (void *)super_class
);
1165 if (!RB_TYPE_P(original_klass
, T_MODULE
)) {
1166 rb_id_table_foreach(tbl
, clear_module_cache_i
, (void *)original_klass
);
1172 // setup T_ICLASS for the include/prepend module
1173 iclass
= rb_include_class_new(module
, super_class
);
1174 c
= RCLASS_SET_SUPER(c
, iclass
);
1175 RCLASS_SET_INCLUDER(iclass
, klass
);
1176 add_subclass
= TRUE
;
1177 if (module
!= RCLASS_ORIGIN(module
)) {
1178 if (!origin_stack
) origin_stack
= rb_ary_tmp_new(2);
1179 VALUE origin
[2] = {iclass
, RCLASS_ORIGIN(module
)};
1180 rb_ary_cat(origin_stack
, origin
, 2);
1182 else if (origin_stack
&& (origin_len
= RARRAY_LEN(origin_stack
)) > 1 &&
1183 RARRAY_AREF(origin_stack
, origin_len
- 1) == module
) {
1184 RCLASS_SET_ORIGIN(RARRAY_AREF(origin_stack
, (origin_len
-= 2)), iclass
);
1185 RICLASS_SET_ORIGIN_SHARED_MTBL(iclass
);
1186 rb_ary_resize(origin_stack
, origin_len
);
1187 add_subclass
= FALSE
;
1192 if (BUILTIN_TYPE(m
) == T_ICLASS
) m
= RBASIC(m
)->klass
;
1193 rb_module_add_to_subclasses_list(m
, iclass
);
1196 if (FL_TEST(klass
, RMODULE_IS_REFINEMENT
)) {
1197 VALUE refined_class
=
1198 rb_refinement_module_get_refined_class(klass
);
1200 rb_id_table_foreach(RCLASS_M_TBL(module
), add_refined_method_entry_i
, (void *)refined_class
);
1201 FL_SET(c
, RMODULE_INCLUDED_INTO_REFINEMENT
);
1204 tbl
= RCLASS_CONST_TBL(module
);
1205 if (tbl
&& rb_id_table_size(tbl
)) constant_changed
= 1;
1207 module
= RCLASS_SUPER(module
);
1210 if (constant_changed
) rb_clear_constant_cache();
1212 return method_changed
;
1216 include_modules_at(const VALUE klass
, VALUE c
, VALUE module
, int search_super
)
1218 return do_include_modules_at(klass
, c
, module
, search_super
, true);
1221 static enum rb_id_table_iterator_result
1222 move_refined_method(ID key
, VALUE value
, void *data
)
1224 rb_method_entry_t
*me
= (rb_method_entry_t
*)value
;
1226 if (me
->def
->type
== VM_METHOD_TYPE_REFINED
) {
1227 VALUE klass
= (VALUE
)data
;
1228 struct rb_id_table
*tbl
= RCLASS_M_TBL(klass
);
1230 if (me
->def
->body
.refined
.orig_me
) {
1231 const rb_method_entry_t
*orig_me
= me
->def
->body
.refined
.orig_me
, *new_me
;
1232 RB_OBJ_WRITE(me
, &me
->def
->body
.refined
.orig_me
, NULL
);
1233 new_me
= rb_method_entry_clone(me
);
1234 rb_method_table_insert(klass
, tbl
, key
, new_me
);
1235 rb_method_entry_copy(me
, orig_me
);
1236 return ID_TABLE_CONTINUE
;
1239 rb_method_table_insert(klass
, tbl
, key
, me
);
1240 return ID_TABLE_DELETE
;
1244 return ID_TABLE_CONTINUE
;
1248 static enum rb_id_table_iterator_result
1249 cache_clear_refined_method(ID key
, VALUE value
, void *data
)
1251 rb_method_entry_t
*me
= (rb_method_entry_t
*) value
;
1253 if (me
->def
->type
== VM_METHOD_TYPE_REFINED
&& me
->def
->body
.refined
.orig_me
) {
1254 VALUE klass
= (VALUE
)data
;
1255 rb_clear_method_cache(klass
, me
->called_id
);
1257 // Refined method entries without an orig_me is going to stay in the method
1258 // table of klass, like before the move, so no need to clear the cache.
1260 return ID_TABLE_CONTINUE
;
1264 ensure_origin(VALUE klass
)
1266 VALUE origin
= RCLASS_ORIGIN(klass
);
1267 if (origin
== klass
) {
1268 origin
= class_alloc(T_ICLASS
, klass
);
1269 RCLASS_SET_SUPER(origin
, RCLASS_SUPER(klass
));
1270 RCLASS_SET_SUPER(klass
, origin
);
1271 RCLASS_SET_ORIGIN(klass
, origin
);
1272 RCLASS_M_TBL(origin
) = RCLASS_M_TBL(klass
);
1273 RCLASS_M_TBL_INIT(klass
);
1274 rb_id_table_foreach(RCLASS_M_TBL(origin
), cache_clear_refined_method
, (void *)klass
);
1275 rb_id_table_foreach(RCLASS_M_TBL(origin
), move_refined_method
, (void *)klass
);
1282 rb_prepend_module(VALUE klass
, VALUE module
)
1285 bool klass_had_no_origin
;
1287 ensure_includable(klass
, module
);
1288 if (module_in_super_chain(klass
, module
))
1289 rb_raise(rb_eArgError
, "cyclic prepend detected");
1291 klass_had_no_origin
= ensure_origin(klass
);
1292 changed
= do_include_modules_at(klass
, klass
, module
, FALSE
, false);
1293 RUBY_ASSERT(changed
>= 0); // already checked for cyclic prepend above
1295 rb_vm_check_redefinition_by_prepend(klass
);
1297 if (RB_TYPE_P(klass
, T_MODULE
)) {
1298 rb_subclass_entry_t
*iclass
= RCLASS_SUBCLASSES(klass
);
1299 // skip the placeholder subclass entry at the head of the list if it exists
1300 if (iclass
&& iclass
->next
) {
1301 RUBY_ASSERT(!iclass
->klass
);
1302 iclass
= iclass
->next
;
1305 VALUE klass_origin
= RCLASS_ORIGIN(klass
);
1306 struct rb_id_table
*klass_m_tbl
= RCLASS_M_TBL(klass
);
1307 struct rb_id_table
*klass_origin_m_tbl
= RCLASS_M_TBL(klass_origin
);
1309 if (klass_had_no_origin
&& klass_origin_m_tbl
== RCLASS_M_TBL(iclass
->klass
)) {
1310 // backfill an origin iclass to handle refinements and future prepends
1311 rb_id_table_foreach(RCLASS_M_TBL(iclass
->klass
), clear_module_cache_i
, (void *)iclass
->klass
);
1312 RCLASS_M_TBL(iclass
->klass
) = klass_m_tbl
;
1313 VALUE origin
= rb_include_class_new(klass_origin
, RCLASS_SUPER(iclass
->klass
));
1314 RCLASS_SET_SUPER(iclass
->klass
, origin
);
1315 RCLASS_SET_INCLUDER(origin
, RCLASS_INCLUDER(iclass
->klass
));
1316 RCLASS_SET_ORIGIN(iclass
->klass
, origin
);
1317 RICLASS_SET_ORIGIN_SHARED_MTBL(origin
);
1319 include_modules_at(iclass
->klass
, iclass
->klass
, module
, FALSE
);
1320 iclass
= iclass
->next
;
1327 * mod.included_modules -> array
1329 * Returns the list of modules included or prepended in <i>mod</i>
1330 * or one of <i>mod</i>'s ancestors.
1343 * Mixin.included_modules #=> [Sub]
1344 * Outer.included_modules #=> [Sub, Mixin]
1348 rb_mod_included_modules(VALUE mod
)
1350 VALUE ary
= rb_ary_new();
1352 VALUE origin
= RCLASS_ORIGIN(mod
);
1354 for (p
= RCLASS_SUPER(mod
); p
; p
= RCLASS_SUPER(p
)) {
1355 if (p
!= origin
&& RCLASS_ORIGIN(p
) == p
&& BUILTIN_TYPE(p
) == T_ICLASS
) {
1356 VALUE m
= RBASIC(p
)->klass
;
1357 if (RB_TYPE_P(m
, T_MODULE
))
1358 rb_ary_push(ary
, m
);
1366 * mod.include?(module) -> true or false
1368 * Returns <code>true</code> if <i>module</i> is included
1369 * or prepended in <i>mod</i> or one of <i>mod</i>'s ancestors.
1378 * B.include?(A) #=> true
1379 * C.include?(A) #=> true
1380 * A.include?(A) #=> false
1384 rb_mod_include_p(VALUE mod
, VALUE mod2
)
1388 Check_Type(mod2
, T_MODULE
);
1389 for (p
= RCLASS_SUPER(mod
); p
; p
= RCLASS_SUPER(p
)) {
1390 if (BUILTIN_TYPE(p
) == T_ICLASS
&& !FL_TEST(p
, RICLASS_IS_ORIGIN
)) {
1391 if (RBASIC(p
)->klass
== mod2
) return Qtrue
;
1399 * mod.ancestors -> array
1401 * Returns a list of modules included/prepended in <i>mod</i>
1402 * (including <i>mod</i> itself).
1406 * include Comparable
1407 * prepend Enumerable
1410 * Mod.ancestors #=> [Enumerable, Mod, Comparable, Math]
1411 * Math.ancestors #=> [Math]
1412 * Enumerable.ancestors #=> [Enumerable]
1416 rb_mod_ancestors(VALUE mod
)
1418 VALUE p
, ary
= rb_ary_new();
1419 VALUE refined_class
= Qnil
;
1420 if (FL_TEST(mod
, RMODULE_IS_REFINEMENT
)) {
1421 refined_class
= rb_refinement_module_get_refined_class(mod
);
1424 for (p
= mod
; p
; p
= RCLASS_SUPER(p
)) {
1425 if (p
== refined_class
) break;
1426 if (p
!= RCLASS_ORIGIN(p
)) continue;
1427 if (BUILTIN_TYPE(p
) == T_ICLASS
) {
1428 rb_ary_push(ary
, RBASIC(p
)->klass
);
1431 rb_ary_push(ary
, p
);
1437 struct subclass_traverse_data
1442 bool immediate_only
;
1446 class_descendants_recursive(VALUE klass
, VALUE v
)
1448 struct subclass_traverse_data
*data
= (struct subclass_traverse_data
*) v
;
1450 if (BUILTIN_TYPE(klass
) == T_CLASS
&& !FL_TEST(klass
, FL_SINGLETON
)) {
1451 if (data
->buffer
&& data
->count
< data
->maxcount
&& !rb_objspace_garbage_object_p(klass
)) {
1452 // assumes that this does not cause GC as long as the length does not exceed the capacity
1453 rb_ary_push(data
->buffer
, klass
);
1456 if (!data
->immediate_only
) {
1457 rb_class_foreach_subclass(klass
, class_descendants_recursive
, v
);
1461 rb_class_foreach_subclass(klass
, class_descendants_recursive
, v
);
1466 class_descendants(VALUE klass
, bool immediate_only
)
1468 struct subclass_traverse_data data
= { Qfalse
, 0, -1, immediate_only
};
1470 // estimate the count of subclasses
1471 rb_class_foreach_subclass(klass
, class_descendants_recursive
, (VALUE
) &data
);
1473 // the following allocation may cause GC which may change the number of subclasses
1474 data
.buffer
= rb_ary_new_capa(data
.count
);
1475 data
.maxcount
= data
.count
;
1478 size_t gc_count
= rb_gc_count();
1480 // enumerate subclasses
1481 rb_class_foreach_subclass(klass
, class_descendants_recursive
, (VALUE
) &data
);
1483 if (gc_count
!= rb_gc_count()) {
1484 rb_bug("GC must not occur during the subclass iteration of Class#descendants");
1492 * subclasses -> array
1494 * Returns an array of classes where the receiver is the
1495 * direct superclass of the class, excluding singleton classes.
1496 * The order of the returned array is not defined.
1503 * A.subclasses #=> [D, B]
1504 * B.subclasses #=> [C]
1505 * C.subclasses #=> []
1509 rb_class_subclasses(VALUE klass
)
1511 return class_descendants(klass
, true);
1515 ins_methods_push(st_data_t name
, st_data_t ary
)
1517 rb_ary_push((VALUE
)ary
, ID2SYM((ID
)name
));
1521 ins_methods_i(st_data_t name
, st_data_t type
, st_data_t ary
)
1523 switch ((rb_method_visibility_t
)type
) {
1524 case METHOD_VISI_UNDEF
:
1525 case METHOD_VISI_PRIVATE
:
1527 default: /* everything but private */
1528 ins_methods_push(name
, ary
);
1535 ins_methods_type_i(st_data_t name
, st_data_t type
, st_data_t ary
, rb_method_visibility_t visi
)
1537 if ((rb_method_visibility_t
)type
== visi
) {
1538 ins_methods_push(name
, ary
);
1544 ins_methods_prot_i(st_data_t name
, st_data_t type
, st_data_t ary
)
1546 return ins_methods_type_i(name
, type
, ary
, METHOD_VISI_PROTECTED
);
1550 ins_methods_priv_i(st_data_t name
, st_data_t type
, st_data_t ary
)
1552 return ins_methods_type_i(name
, type
, ary
, METHOD_VISI_PRIVATE
);
1556 ins_methods_pub_i(st_data_t name
, st_data_t type
, st_data_t ary
)
1558 return ins_methods_type_i(name
, type
, ary
, METHOD_VISI_PUBLIC
);
1561 struct method_entry_arg
{
1566 static enum rb_id_table_iterator_result
1567 method_entry_i(ID key
, VALUE value
, void *data
)
1569 const rb_method_entry_t
*me
= (const rb_method_entry_t
*)value
;
1570 struct method_entry_arg
*arg
= (struct method_entry_arg
*)data
;
1571 rb_method_visibility_t type
;
1573 if (me
->def
->type
== VM_METHOD_TYPE_REFINED
) {
1574 VALUE owner
= me
->owner
;
1575 me
= rb_resolve_refined_method(Qnil
, me
);
1576 if (!me
) return ID_TABLE_CONTINUE
;
1577 if (!arg
->recur
&& me
->owner
!= owner
) return ID_TABLE_CONTINUE
;
1579 if (!st_is_member(arg
->list
, key
)) {
1580 if (UNDEFINED_METHOD_ENTRY_P(me
)) {
1581 type
= METHOD_VISI_UNDEF
; /* none */
1584 type
= METHOD_ENTRY_VISI(me
);
1585 RUBY_ASSERT(type
!= METHOD_VISI_UNDEF
);
1587 st_add_direct(arg
->list
, key
, (st_data_t
)type
);
1589 return ID_TABLE_CONTINUE
;
1593 add_instance_method_list(VALUE mod
, struct method_entry_arg
*me_arg
)
1595 struct rb_id_table
*m_tbl
= RCLASS_M_TBL(mod
);
1597 rb_id_table_foreach(m_tbl
, method_entry_i
, me_arg
);
1601 particular_class_p(VALUE mod
)
1603 if (!mod
) return false;
1604 if (FL_TEST(mod
, FL_SINGLETON
)) return true;
1605 if (BUILTIN_TYPE(mod
) == T_ICLASS
) return true;
1610 class_instance_method_list(int argc
, const VALUE
*argv
, VALUE mod
, int obj
, int (*func
) (st_data_t
, st_data_t
, st_data_t
))
1613 int recur
= TRUE
, prepended
= 0;
1614 struct method_entry_arg me_arg
;
1616 if (rb_check_arity(argc
, 0, 1)) recur
= RTEST(argv
[0]);
1618 me_arg
.list
= st_init_numtable();
1619 me_arg
.recur
= recur
;
1622 for (; particular_class_p(mod
); mod
= RCLASS_SUPER(mod
)) {
1623 add_instance_method_list(mod
, &me_arg
);
1627 if (!recur
&& RCLASS_ORIGIN(mod
) != mod
) {
1628 mod
= RCLASS_ORIGIN(mod
);
1632 for (; mod
; mod
= RCLASS_SUPER(mod
)) {
1633 add_instance_method_list(mod
, &me_arg
);
1634 if (BUILTIN_TYPE(mod
) == T_ICLASS
&& !prepended
) continue;
1637 ary
= rb_ary_new2(me_arg
.list
->num_entries
);
1638 st_foreach(me_arg
.list
, func
, ary
);
1639 st_free_table(me_arg
.list
);
1646 * mod.instance_methods(include_super=true) -> array
1648 * Returns an array containing the names of the public and protected instance
1649 * methods in the receiver. For a module, these are the public and protected methods;
1650 * for a class, they are the instance (not singleton) methods. If the optional
1651 * parameter is <code>false</code>, the methods of any ancestors are not included.
1664 * A.instance_methods(false) #=> [:method1]
1665 * B.instance_methods(false) #=> [:method2]
1666 * B.instance_methods(true).include?(:method1) #=> true
1667 * C.instance_methods(false) #=> [:method3]
1668 * C.instance_methods.include?(:method2) #=> true
1672 rb_class_instance_methods(int argc
, const VALUE
*argv
, VALUE mod
)
1674 return class_instance_method_list(argc
, argv
, mod
, 0, ins_methods_i
);
1679 * mod.protected_instance_methods(include_super=true) -> array
1681 * Returns a list of the protected instance methods defined in
1682 * <i>mod</i>. If the optional parameter is <code>false</code>, the
1683 * methods of any ancestors are not included.
1687 rb_class_protected_instance_methods(int argc
, const VALUE
*argv
, VALUE mod
)
1689 return class_instance_method_list(argc
, argv
, mod
, 0, ins_methods_prot_i
);
1694 * mod.private_instance_methods(include_super=true) -> array
1696 * Returns a list of the private instance methods defined in
1697 * <i>mod</i>. If the optional parameter is <code>false</code>, the
1698 * methods of any ancestors are not included.
1705 * Mod.instance_methods #=> [:method2]
1706 * Mod.private_instance_methods #=> [:method1]
1710 rb_class_private_instance_methods(int argc
, const VALUE
*argv
, VALUE mod
)
1712 return class_instance_method_list(argc
, argv
, mod
, 0, ins_methods_priv_i
);
1717 * mod.public_instance_methods(include_super=true) -> array
1719 * Returns a list of the public instance methods defined in <i>mod</i>.
1720 * If the optional parameter is <code>false</code>, the methods of
1721 * any ancestors are not included.
1725 rb_class_public_instance_methods(int argc
, const VALUE
*argv
, VALUE mod
)
1727 return class_instance_method_list(argc
, argv
, mod
, 0, ins_methods_pub_i
);
1732 * obj.methods(regular=true) -> array
1734 * Returns a list of the names of public and protected methods of
1735 * <i>obj</i>. This will include all the methods accessible in
1736 * <i>obj</i>'s ancestors.
1737 * If the optional parameter is <code>false</code>, it
1738 * returns an array of <i>obj</i>'s public and protected singleton methods,
1739 * the array will not include methods in modules included in <i>obj</i>.
1742 * def klass_method()
1746 * k.methods[0..9] #=> [:klass_method, :nil?, :===,
1748 * # :hash, :<=>, :class, :singleton_class]
1749 * k.methods.length #=> 56
1751 * k.methods(false) #=> []
1752 * def k.singleton_method; end
1753 * k.methods(false) #=> [:singleton_method]
1755 * module M123; def m123; end end
1757 * k.methods(false) #=> [:singleton_method]
1761 rb_obj_methods(int argc
, const VALUE
*argv
, VALUE obj
)
1763 rb_check_arity(argc
, 0, 1);
1764 if (argc
> 0 && !RTEST(argv
[0])) {
1765 return rb_obj_singleton_methods(argc
, argv
, obj
);
1767 return class_instance_method_list(argc
, argv
, CLASS_OF(obj
), 1, ins_methods_i
);
1772 * obj.protected_methods(all=true) -> array
1774 * Returns the list of protected methods accessible to <i>obj</i>. If
1775 * the <i>all</i> parameter is set to <code>false</code>, only those methods
1776 * in the receiver will be listed.
1780 rb_obj_protected_methods(int argc
, const VALUE
*argv
, VALUE obj
)
1782 return class_instance_method_list(argc
, argv
, CLASS_OF(obj
), 1, ins_methods_prot_i
);
1787 * obj.private_methods(all=true) -> array
1789 * Returns the list of private methods accessible to <i>obj</i>. If
1790 * the <i>all</i> parameter is set to <code>false</code>, only those methods
1791 * in the receiver will be listed.
1795 rb_obj_private_methods(int argc
, const VALUE
*argv
, VALUE obj
)
1797 return class_instance_method_list(argc
, argv
, CLASS_OF(obj
), 1, ins_methods_priv_i
);
1802 * obj.public_methods(all=true) -> array
1804 * Returns the list of public methods accessible to <i>obj</i>. If
1805 * the <i>all</i> parameter is set to <code>false</code>, only those methods
1806 * in the receiver will be listed.
1810 rb_obj_public_methods(int argc
, const VALUE
*argv
, VALUE obj
)
1812 return class_instance_method_list(argc
, argv
, CLASS_OF(obj
), 1, ins_methods_pub_i
);
1817 * obj.singleton_methods(all=true) -> array
1819 * Returns an array of the names of singleton methods for <i>obj</i>.
1820 * If the optional <i>all</i> parameter is true, the list will include
1821 * methods in modules included in <i>obj</i>.
1822 * Only public and protected singleton methods are returned.
1829 * def Single.four() end
1843 * Single.singleton_methods #=> [:four]
1844 * a.singleton_methods(false) #=> [:two, :one]
1845 * a.singleton_methods #=> [:two, :one, :three]
1849 rb_obj_singleton_methods(int argc
, const VALUE
*argv
, VALUE obj
)
1851 VALUE ary
, klass
, origin
;
1852 struct method_entry_arg me_arg
;
1853 struct rb_id_table
*mtbl
;
1856 if (rb_check_arity(argc
, 0, 1)) recur
= RTEST(argv
[0]);
1857 if (RB_TYPE_P(obj
, T_CLASS
) && FL_TEST(obj
, FL_SINGLETON
)) {
1858 rb_singleton_class(obj
);
1860 klass
= CLASS_OF(obj
);
1861 origin
= RCLASS_ORIGIN(klass
);
1862 me_arg
.list
= st_init_numtable();
1863 me_arg
.recur
= recur
;
1864 if (klass
&& FL_TEST(klass
, FL_SINGLETON
)) {
1865 if ((mtbl
= RCLASS_M_TBL(origin
)) != 0) rb_id_table_foreach(mtbl
, method_entry_i
, &me_arg
);
1866 klass
= RCLASS_SUPER(klass
);
1869 while (klass
&& (FL_TEST(klass
, FL_SINGLETON
) || RB_TYPE_P(klass
, T_ICLASS
))) {
1870 if (klass
!= origin
&& (mtbl
= RCLASS_M_TBL(klass
)) != 0) rb_id_table_foreach(mtbl
, method_entry_i
, &me_arg
);
1871 klass
= RCLASS_SUPER(klass
);
1874 ary
= rb_ary_new2(me_arg
.list
->num_entries
);
1875 st_foreach(me_arg
.list
, ins_methods_i
, ary
);
1876 st_free_table(me_arg
.list
);
1885 * \addtogroup defmethod
1889 #ifdef rb_define_method_id
1890 #undef rb_define_method_id
1893 rb_define_method_id(VALUE klass
, ID mid
, VALUE (*func
)(ANYARGS
), int argc
)
1895 rb_add_method_cfunc(klass
, mid
, func
, argc
, METHOD_VISI_PUBLIC
);
1898 #ifdef rb_define_method
1899 #undef rb_define_method
1902 rb_define_method(VALUE klass
, const char *name
, VALUE (*func
)(ANYARGS
), int argc
)
1904 rb_add_method_cfunc(klass
, rb_intern(name
), func
, argc
, METHOD_VISI_PUBLIC
);
1907 #ifdef rb_define_protected_method
1908 #undef rb_define_protected_method
1911 rb_define_protected_method(VALUE klass
, const char *name
, VALUE (*func
)(ANYARGS
), int argc
)
1913 rb_add_method_cfunc(klass
, rb_intern(name
), func
, argc
, METHOD_VISI_PROTECTED
);
1916 #ifdef rb_define_private_method
1917 #undef rb_define_private_method
1920 rb_define_private_method(VALUE klass
, const char *name
, VALUE (*func
)(ANYARGS
), int argc
)
1922 rb_add_method_cfunc(klass
, rb_intern(name
), func
, argc
, METHOD_VISI_PRIVATE
);
1926 rb_undef_method(VALUE klass
, const char *name
)
1928 rb_add_method(klass
, rb_intern(name
), VM_METHOD_TYPE_UNDEF
, 0, METHOD_VISI_UNDEF
);
1931 static enum rb_id_table_iterator_result
1932 undef_method_i(ID name
, VALUE value
, void *data
)
1934 VALUE klass
= (VALUE
)data
;
1935 rb_add_method(klass
, name
, VM_METHOD_TYPE_UNDEF
, 0, METHOD_VISI_UNDEF
);
1936 return ID_TABLE_CONTINUE
;
1940 rb_undef_methods_from(VALUE klass
, VALUE super
)
1942 struct rb_id_table
*mtbl
= RCLASS_M_TBL(super
);
1944 rb_id_table_foreach(mtbl
, undef_method_i
, (void *)klass
);
1957 special_singleton_class_of(VALUE obj
)
1960 case Qnil
: return rb_cNilClass
;
1961 case Qfalse
: return rb_cFalseClass
;
1962 case Qtrue
: return rb_cTrueClass
;
1963 default: return Qnil
;
1968 rb_special_singleton_class(VALUE obj
)
1970 return special_singleton_class_of(obj
);
1975 * Returns the singleton class of \a obj. Creates it if necessary.
1977 * \note DO NOT expose the returned singleton class to
1978 * outside of class.c.
1979 * Use \ref rb_singleton_class instead for
1980 * consistency of the metaclass hierarchy.
1983 singleton_class_of(VALUE obj
)
1987 switch (TYPE(obj
)) {
1992 rb_raise(rb_eTypeError
, "can't define singleton");
1997 klass
= special_singleton_class_of(obj
);
1999 rb_bug("unknown immediate %p", (void *)obj
);
2003 if (FL_TEST_RAW(obj
, RSTRING_FSTR
)) {
2004 rb_raise(rb_eTypeError
, "can't define singleton");
2008 klass
= RBASIC(obj
)->klass
;
2009 if (!(FL_TEST(klass
, FL_SINGLETON
) &&
2010 rb_attr_get(klass
, id_attached
) == obj
)) {
2011 rb_serial_t serial
= RCLASS_SERIAL(klass
);
2012 klass
= rb_make_metaclass(obj
, klass
);
2013 RCLASS_SERIAL(klass
) = serial
;
2016 RB_FL_SET_RAW(klass
, RB_OBJ_FROZEN_RAW(obj
));
2022 rb_freeze_singleton_class(VALUE x
)
2024 /* should not propagate to meta-meta-class, and so on */
2025 if (!(RBASIC(x
)->flags
& FL_SINGLETON
)) {
2026 VALUE klass
= RBASIC_CLASS(x
);
2027 if (klass
&& (klass
= RCLASS_ORIGIN(klass
)) != 0 &&
2028 FL_TEST(klass
, (FL_SINGLETON
|FL_FREEZE
)) == FL_SINGLETON
) {
2029 OBJ_FREEZE_RAW(klass
);
2035 * Returns the singleton class of \a obj, or nil if obj is not a
2038 * \param obj an arbitrary object.
2039 * \return the singleton class or nil.
2042 rb_singleton_class_get(VALUE obj
)
2046 if (SPECIAL_CONST_P(obj
)) {
2047 return rb_special_singleton_class(obj
);
2049 klass
= RBASIC(obj
)->klass
;
2050 if (!FL_TEST(klass
, FL_SINGLETON
)) return Qnil
;
2051 if (rb_attr_get(klass
, id_attached
) != obj
) return Qnil
;
2056 rb_singleton_class(VALUE obj
)
2058 VALUE klass
= singleton_class_of(obj
);
2060 /* ensures an exposed class belongs to its own eigenclass */
2061 if (RB_TYPE_P(obj
, T_CLASS
)) (void)ENSURE_EIGENCLASS(klass
);
2071 * \addtogroup defmethod
2075 #ifdef rb_define_singleton_method
2076 #undef rb_define_singleton_method
2079 rb_define_singleton_method(VALUE obj
, const char *name
, VALUE (*func
)(ANYARGS
), int argc
)
2081 rb_define_method(singleton_class_of(obj
), name
, func
, argc
);
2084 #ifdef rb_define_module_function
2085 #undef rb_define_module_function
2088 rb_define_module_function(VALUE module
, const char *name
, VALUE (*func
)(ANYARGS
), int argc
)
2090 rb_define_private_method(module
, name
, func
, argc
);
2091 rb_define_singleton_method(module
, name
, func
, argc
);
2094 #ifdef rb_define_global_function
2095 #undef rb_define_global_function
2098 rb_define_global_function(const char *name
, VALUE (*func
)(ANYARGS
), int argc
)
2100 rb_define_module_function(rb_mKernel
, name
, func
, argc
);
2104 rb_define_alias(VALUE klass
, const char *name1
, const char *name2
)
2106 rb_alias(klass
, rb_intern(name1
), rb_intern(name2
));
2110 rb_define_attr(VALUE klass
, const char *name
, int read
, int write
)
2112 rb_attr(klass
, rb_intern(name
), read
, write
, FALSE
);
2115 MJIT_FUNC_EXPORTED VALUE
2116 rb_keyword_error_new(const char *error
, VALUE keys
)
2118 long i
= 0, len
= RARRAY_LEN(keys
);
2119 VALUE error_message
= rb_sprintf("%s keyword%.*s", error
, len
> 1, "s");
2122 rb_str_cat_cstr(error_message
, ": ");
2124 const VALUE k
= RARRAY_AREF(keys
, i
);
2125 rb_str_append(error_message
, rb_inspect(k
));
2126 if (++i
>= len
) break;
2127 rb_str_cat_cstr(error_message
, ", ");
2131 return rb_exc_new_str(rb_eArgError
, error_message
);
2134 NORETURN(static void rb_keyword_error(const char *error
, VALUE keys
));
2136 rb_keyword_error(const char *error
, VALUE keys
)
2138 rb_exc_raise(rb_keyword_error_new(error
, keys
));
2141 NORETURN(static void unknown_keyword_error(VALUE hash
, const ID
*table
, int keywords
));
2143 unknown_keyword_error(VALUE hash
, const ID
*table
, int keywords
)
2146 for (i
= 0; i
< keywords
; i
++) {
2147 st_data_t key
= ID2SYM(table
[i
]);
2148 rb_hash_stlike_delete(hash
, &key
, NULL
);
2150 rb_keyword_error("unknown", rb_hash_keys(hash
));
2155 separate_symbol(st_data_t key
, st_data_t value
, st_data_t arg
)
2157 VALUE
*kwdhash
= (VALUE
*)arg
;
2158 if (!SYMBOL_P(key
)) kwdhash
++;
2159 if (!*kwdhash
) *kwdhash
= rb_hash_new();
2160 rb_hash_aset(*kwdhash
, (VALUE
)key
, (VALUE
)value
);
2165 rb_extract_keywords(VALUE
*orighash
)
2167 VALUE parthash
[2] = {0, 0};
2168 VALUE hash
= *orighash
;
2170 if (RHASH_EMPTY_P(hash
)) {
2174 rb_hash_foreach(hash
, separate_symbol
, (st_data_t
)&parthash
);
2175 *orighash
= parthash
[1];
2176 if (parthash
[1] && RBASIC_CLASS(hash
) != rb_cHash
) {
2177 RBASIC_SET_CLASS(parthash
[1], RBASIC_CLASS(hash
));
2183 rb_get_kwargs(VALUE keyword_hash
, const ID
*table
, int required
, int optional
, VALUE
*values
)
2187 VALUE missing
= Qnil
;
2190 #define extract_kwarg(keyword, val) \
2191 (key = (st_data_t)(keyword), values ? \
2192 (rb_hash_stlike_delete(keyword_hash, &key, &(val)) || ((val) = Qundef, 0)) : \
2193 rb_hash_stlike_lookup(keyword_hash, key, NULL))
2195 if (NIL_P(keyword_hash
)) keyword_hash
= 0;
2199 optional
= -1-optional
;
2202 for (; i
< required
; i
++) {
2203 VALUE keyword
= ID2SYM(table
[i
]);
2205 if (extract_kwarg(keyword
, values
[i
])) {
2209 if (NIL_P(missing
)) missing
= rb_ary_tmp_new(1);
2210 rb_ary_push(missing
, keyword
);
2212 if (!NIL_P(missing
)) {
2213 rb_keyword_error("missing", missing
);
2217 if (optional
&& keyword_hash
) {
2218 for (i
= 0; i
< optional
; i
++) {
2219 if (extract_kwarg(ID2SYM(table
[required
+i
]), values
[required
+i
])) {
2224 if (!rest
&& keyword_hash
) {
2225 if (RHASH_SIZE(keyword_hash
) > (unsigned int)(values
? 0 : j
)) {
2226 unknown_keyword_error(keyword_hash
, table
, required
+optional
);
2229 if (values
&& !keyword_hash
) {
2230 for (i
= 0; i
< required
+ optional
; i
++) {
2235 #undef extract_kwarg
2238 struct rb_scan_args_t
{
2249 rb_scan_args_parse(int kw_flag
, const char *fmt
, struct rb_scan_args_t
*arg
)
2251 const char *p
= fmt
;
2253 memset(arg
, 0, sizeof(*arg
));
2254 arg
->kw_flag
= kw_flag
;
2257 arg
->n_lead
= *p
- '0';
2260 arg
->n_opt
= *p
- '0';
2269 arg
->n_trail
= *p
- '0';
2281 rb_fatal("bad scan arg format: %s", fmt
);
2286 rb_scan_args_assign(const struct rb_scan_args_t
*arg
, int argc
, const VALUE
*const argv
, va_list vargs
)
2289 VALUE
*var
, hash
= Qnil
;
2290 #define rb_scan_args_next_param() va_arg(vargs, VALUE *)
2291 const int kw_flag
= arg
->kw_flag
;
2292 const int n_lead
= arg
->n_lead
;
2293 const int n_opt
= arg
->n_opt
;
2294 const int n_trail
= arg
->n_trail
;
2295 const int n_mand
= n_lead
+ n_trail
;
2296 const bool f_var
= arg
->f_var
;
2297 const bool f_hash
= arg
->f_hash
;
2298 const bool f_block
= arg
->f_block
;
2300 /* capture an option hash - phase 1: pop from the argv */
2301 if (f_hash
&& argc
> 0) {
2302 VALUE last
= argv
[argc
- 1];
2303 if (rb_scan_args_keyword_p(kw_flag
, last
)) {
2304 hash
= rb_hash_dup(last
);
2309 if (argc
< n_mand
) {
2313 /* capture leading mandatory arguments */
2314 for (i
= 0; i
< n_lead
; i
++) {
2315 var
= rb_scan_args_next_param();
2316 if (var
) *var
= argv
[argi
];
2319 /* capture optional arguments */
2320 for (i
= 0; i
< n_opt
; i
++) {
2321 var
= rb_scan_args_next_param();
2322 if (argi
< argc
- n_trail
) {
2323 if (var
) *var
= argv
[argi
];
2327 if (var
) *var
= Qnil
;
2330 /* capture variable length arguments */
2332 int n_var
= argc
- argi
- n_trail
;
2334 var
= rb_scan_args_next_param();
2336 if (var
) *var
= rb_ary_new_from_values(n_var
, &argv
[argi
]);
2340 if (var
) *var
= rb_ary_new();
2343 /* capture trailing mandatory arguments */
2344 for (i
= 0; i
< n_trail
; i
++) {
2345 var
= rb_scan_args_next_param();
2346 if (var
) *var
= argv
[argi
];
2349 /* capture an option hash - phase 2: assignment */
2351 var
= rb_scan_args_next_param();
2352 if (var
) *var
= hash
;
2354 /* capture iterator block */
2356 var
= rb_scan_args_next_param();
2357 if (rb_block_given_p()) {
2358 *var
= rb_block_proc();
2371 #undef rb_scan_args_next_param
2375 rb_scan_args_result(const struct rb_scan_args_t
*const arg
, int argc
)
2377 const int n_lead
= arg
->n_lead
;
2378 const int n_opt
= arg
->n_opt
;
2379 const int n_trail
= arg
->n_trail
;
2380 const int n_mand
= n_lead
+ n_trail
;
2381 const bool f_var
= arg
->f_var
;
2388 rb_error_arity(argc
, n_mand
, f_var
? UNLIMITED_ARGUMENTS
: n_mand
+ n_opt
);
2389 UNREACHABLE_RETURN(-1);
2394 rb_scan_args(int argc
, const VALUE
*argv
, const char *fmt
, ...)
2397 struct rb_scan_args_t arg
;
2398 rb_scan_args_parse(RB_SCAN_ARGS_PASS_CALLED_KEYWORDS
, fmt
, &arg
);
2399 va_start(vargs
,fmt
);
2400 argc
= rb_scan_args_assign(&arg
, argc
, argv
, vargs
);
2402 return rb_scan_args_result(&arg
, argc
);
2405 #undef rb_scan_args_kw
2407 rb_scan_args_kw(int kw_flag
, int argc
, const VALUE
*argv
, const char *fmt
, ...)
2410 struct rb_scan_args_t arg
;
2411 rb_scan_args_parse(kw_flag
, fmt
, &arg
);
2412 va_start(vargs
,fmt
);
2413 argc
= rb_scan_args_assign(&arg
, argc
, argv
, vargs
);
2415 return rb_scan_args_result(&arg
, argc
);