[ruby/etc] bump up to 1.3.1
[ruby-80x24.org.git] / class.c
blobf83a16a08e8afffb8e7214076929e825171d2847
1 /**********************************************************************
3 class.c -
5 $Author$
6 created at: Tue Aug 10 15:05:44 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 /*!
13 * \addtogroup class
14 * \{
17 #include "ruby/internal/config.h"
18 #include <ctype.h>
20 #include "constant.h"
21 #include "debug_counter.h"
22 #include "id_table.h"
23 #include "internal.h"
24 #include "internal/class.h"
25 #include "internal/eval.h"
26 #include "internal/hash.h"
27 #include "internal/object.h"
28 #include "internal/string.h"
29 #include "internal/variable.h"
30 #include "ruby/st.h"
31 #include "vm_core.h"
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);
46 entry->klass = klass;
48 head = RCLASS_SUBCLASSES(super);
49 if (!head) {
50 head = ZALLOC(rb_subclass_entry_t);
51 RCLASS_SUBCLASSES(super) = head;
53 entry->next = head->next;
54 entry->prev = head;
56 if (head->next) {
57 head->next->prev = entry;
59 head->next = entry;
61 return entry;
64 void
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;
73 static void
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;
80 void
81 rb_class_remove_subclass_head(VALUE klass)
83 rb_subclass_entry_t *head = RCLASS_SUBCLASSES(klass);
85 if (head) {
86 if (head->next) {
87 head->next->prev = NULL;
89 RCLASS_SUBCLASSES(klass) = NULL;
90 xfree(head);
94 void
95 rb_class_remove_from_super_subclasses(VALUE klass)
97 rb_subclass_entry_t *entry = RCLASS_SUBCLASS_ENTRY(klass);
99 if (entry) {
100 rb_subclass_entry_t *prev = entry->prev, *next = entry->next;
102 if (prev) {
103 prev->next = next;
105 if (next) {
106 next->prev = prev;
109 xfree(entry);
112 RCLASS_SUBCLASS_ENTRY(klass) = NULL;
115 void
116 rb_class_remove_from_module_subclasses(VALUE klass)
118 rb_subclass_entry_t *entry = RCLASS_MODULE_SUBCLASS_ENTRY(klass);
120 if (entry) {
121 rb_subclass_entry_t *prev = entry->prev, *next = entry->next;
123 if (prev) {
124 prev->next = next;
126 if (next) {
127 next->prev = prev;
130 xfree(entry);
133 RCLASS_MODULE_SUBCLASS_ENTRY(klass) = NULL;
136 void
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)
143 if (cur) {
144 RUBY_ASSERT(!cur->klass);
145 cur = cur->next;
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 */
150 while (cur) {
151 VALUE curklass = cur->klass;
152 cur = cur->next;
153 // do not trigger GC during f, otherwise the cur will become
154 // a dangling pointer if the subclass is collected
155 f(curklass, arg);
159 static void
160 class_detach_subclasses(VALUE klass, VALUE arg)
162 rb_class_remove_from_super_subclasses(klass);
165 void
166 rb_class_detach_subclasses(VALUE klass)
168 rb_class_foreach_subclass(klass, class_detach_subclasses, Qnil);
171 static void
172 class_detach_module_subclasses(VALUE klass, VALUE arg)
174 rb_class_remove_from_module_subclasses(klass);
177 void
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.
195 static VALUE
196 class_alloc(VALUE flags, VALUE klass)
198 size_t alloc_size = sizeof(struct RClass);
200 #if USE_RVARGC
201 alloc_size += sizeof(rb_classext_t);
202 #endif
204 flags &= T_MASK;
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);
209 #if USE_RVARGC
210 memset(RCLASS_EXT(obj), 0, sizeof(rb_classext_t));
211 #else
212 obj->ptr = ZALLOC(rb_classext_t);
213 #endif
215 /* ZALLOC
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;
230 return (VALUE)obj;
233 static void
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.
248 VALUE
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);
256 return (VALUE)klass;
259 void
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");
274 VALUE
275 rb_class_new(VALUE super)
277 Check_Type(super, T_CLASS);
278 rb_check_inheritable(super);
279 return rb_class_boot(super);
282 VALUE
283 rb_class_s_alloc(VALUE klass)
285 return rb_class_boot(0);
288 static void
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) {
292 rb_cref_t *new_cref;
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));
296 else {
297 rb_method_entry_set(new_klass, mid, me, METHOD_ENTRY_VISI(me));
301 struct clone_method_arg {
302 VALUE new_klass;
303 VALUE old_klass;
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 {
315 VALUE klass;
316 struct rb_id_table *tbl;
319 static int
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);
337 static void
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");
351 static void
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)) {
364 st_data_t id;
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);
378 arg.klass = clone;
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};
390 static inline bool
391 RMODULE_UNINITIALIZED(VALUE module)
393 return FL_TEST_RAW(module, RMODULE_ALLOCATED_BUT_NOT_INITIALIZED);
396 void
397 rb_module_set_initialized(VALUE mod)
399 FL_UNSET_RAW(mod, RMODULE_ALLOCATED_BUT_NOT_INITIALIZED);
400 /* no more re-initialization */
403 void
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);
412 /* :nodoc: */
413 VALUE
414 rb_mod_init_copy(VALUE clone, VALUE orig)
416 switch (BUILTIN_TYPE(clone)) {
417 case T_CLASS:
418 case T_ICLASS:
419 class_init_copy_check(clone, orig);
420 break;
421 case T_MODULE:
422 rb_module_check_initializable(clone);
423 break;
424 default:
425 break;
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));
452 else {
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);
457 VALUE origin[2];
458 VALUE clone_p = 0;
459 long origin_len;
460 int add_subclass;
461 VALUE clone_origin;
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);
480 add_subclass = TRUE;
481 if (p != RCLASS_ORIGIN(p)) {
482 origin[0] = clone_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;
493 if (add_subclass) {
494 rb_module_add_to_subclasses_list(RBASIC(p)->klass, clone_p);
496 p = RCLASS_SUPER(p);
499 if (p == orig_origin) {
500 if (clone_p) {
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);
513 else {
514 rb_bug("no origin for class that has origin");
518 return clone;
521 VALUE
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`.
528 VALUE
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
536 // to clone.
537 if (!(FL_TEST(klass, FL_SINGLETON) && rb_attr_get(klass, id_attached) == obj)) {
538 // nothing to clone
539 return klass;
541 else {
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);
550 else {
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);
566 arg.klass = clone;
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);
584 return clone;
588 void
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))
603 static int
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
645 static inline VALUE
646 make_metaclass(VALUE klass)
648 VALUE super;
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);
658 else {
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);
668 return metaclass;
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.
677 static inline VALUE
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)));
688 return klass;
692 static VALUE
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);
700 return 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.
711 #if 0 /* for RDoc */
713 * Document-method: Refinement#import_methods
715 * call-seq:
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.
724 * module StrUtils
725 * def indent(level)
726 * ' ' * level + self
727 * end
728 * end
730 * module M
731 * refine String do
732 * import_methods StrUtils
733 * end
734 * end
736 * using M
737 * "foo".indent(3)
738 * #=> " foo"
740 * module M
741 * refine String do
742 * import_methods Enumerable
743 * # Can't import method which is not defined with Ruby code: Enumerable#drop
744 * end
745 * end
749 static VALUE
750 refinement_import_methods(int argc, VALUE *argv, VALUE refinement)
753 # endif
755 void
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);
769 #if 0 /* for RDoc */
770 // we pretend it to be public, otherwise RDoc will ignore it
771 rb_define_method(rb_cRefinement, "import_methods", refinement_import_methods, -1);
772 #endif
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);
786 * \internal
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.
795 VALUE
796 rb_make_metaclass(VALUE obj, VALUE unused)
798 if (BUILTIN_TYPE(obj) == T_CLASS) {
799 return make_metaclass(obj);
801 else {
802 return make_singleton_class(obj);
806 VALUE
807 rb_define_class_id(ID id, VALUE super)
809 VALUE klass;
811 if (!super) super = rb_cObject;
812 klass = rb_class_new(super);
813 rb_make_metaclass(klass, RBASIC(super)->klass);
815 return 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)
830 ID inherited;
831 if (!super) super = rb_cObject;
832 CONST_ID(inherited, "inherited");
833 return rb_funcall(super, inherited, 1, klass);
836 VALUE
837 rb_define_class(const char *name, VALUE super)
839 VALUE klass;
840 ID id;
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);
855 return klass;
857 if (!super) {
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);
865 return klass;
868 VALUE
869 rb_define_class_under(VALUE outer, const char *name, VALUE super)
871 return rb_define_class_id_under(outer, rb_intern(name), super);
874 VALUE
875 rb_define_class_id_under(VALUE outer, ID id, VALUE super)
877 VALUE klass;
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"
883 " (%"PRIsVALUE")",
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);
895 return klass;
897 if (!super) {
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);
907 return klass;
910 VALUE
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);
916 return mod;
919 static inline VALUE
920 module_new(VALUE klass)
922 VALUE mdl = class_alloc(T_MODULE, klass);
923 RCLASS_M_TBL_INIT(mdl);
924 return (VALUE)mdl;
927 VALUE
928 rb_module_new(void)
930 return module_new(rb_cModule);
933 VALUE
934 rb_refinement_new(void)
936 return module_new(rb_cRefinement);
939 // Kept for compatibility. Use rb_module_new() instead.
940 VALUE
941 rb_define_module_id(ID id)
943 return rb_module_new();
946 VALUE
947 rb_define_module(const char *name)
949 VALUE module;
950 ID id;
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);
961 return module;
963 module = rb_module_new();
964 rb_vm_add_root_module(module);
965 rb_const_set(rb_cObject, id, module);
967 return module;
970 VALUE
971 rb_define_module_under(VALUE outer, const char *name)
973 return rb_define_module_id_under(outer, rb_intern(name));
976 VALUE
977 rb_define_module_id_under(VALUE outer, ID id)
979 VALUE module;
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"
985 " (%"PRIsVALUE")",
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);
990 return 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);
997 return module;
1000 VALUE
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);
1030 static void
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");
1041 void
1042 rb_include_module(VALUE klass, VALUE module)
1044 int changed = 0;
1046 ensure_includable(klass, module);
1048 changed = include_modules_at(klass, RCLASS_ORIGIN(klass), module, TRUE);
1049 if (changed < 0)
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;
1060 int do_include = 1;
1061 while (iclass) {
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)) {
1066 do_include = 0;
1068 check_class = RCLASS_SUPER(check_class);
1071 if (do_include) {
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;
1094 static bool
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));
1098 if (klass_m_tbl) {
1099 while (module) {
1100 if (klass_m_tbl == RCLASS_M_TBL(module))
1101 return true;
1102 module = RCLASS_SUPER(module);
1105 return false;
1108 static int
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;
1113 long origin_len;
1114 VALUE klass_origin = RCLASS_ORIGIN(klass);
1115 VALUE original_klass = klass;
1117 if (check_cyclic && module_in_super_chain(klass, module))
1118 return -1;
1120 while (module) {
1121 int c_seen = FALSE;
1122 int superclass_seen = FALSE;
1123 struct rb_id_table *tbl;
1125 if (klass == c) {
1126 c_seen = TRUE;
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)
1135 break;
1136 if (c == p)
1137 c_seen = TRUE;
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 */
1143 goto skip;
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);
1164 else { // prepend
1165 if (!RB_TYPE_P(original_klass, T_MODULE)) {
1166 rb_id_table_foreach(tbl, clear_module_cache_i, (void *)original_klass);
1169 method_changed = 1;
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;
1190 if (add_subclass) {
1191 VALUE m = module;
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;
1206 skip:
1207 module = RCLASS_SUPER(module);
1210 if (constant_changed) rb_clear_constant_cache();
1212 return method_changed;
1215 static int
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;
1238 else {
1239 rb_method_table_insert(klass, tbl, key, me);
1240 return ID_TABLE_DELETE;
1243 else {
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;
1263 static bool
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);
1276 return true;
1278 return false;
1281 void
1282 rb_prepend_module(VALUE klass, VALUE module)
1284 int changed;
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
1294 if (changed) {
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);
1308 while (iclass) {
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;
1326 * call-seq:
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.
1332 * module Sub
1333 * end
1335 * module Mixin
1336 * prepend Sub
1337 * end
1339 * module Outer
1340 * include Mixin
1341 * end
1343 * Mixin.included_modules #=> [Sub]
1344 * Outer.included_modules #=> [Sub, Mixin]
1347 VALUE
1348 rb_mod_included_modules(VALUE mod)
1350 VALUE ary = rb_ary_new();
1351 VALUE p;
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);
1361 return ary;
1365 * call-seq:
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.
1371 * module A
1372 * end
1373 * class B
1374 * include A
1375 * end
1376 * class C < B
1377 * end
1378 * B.include?(A) #=> true
1379 * C.include?(A) #=> true
1380 * A.include?(A) #=> false
1383 VALUE
1384 rb_mod_include_p(VALUE mod, VALUE mod2)
1386 VALUE p;
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;
1394 return Qfalse;
1398 * call-seq:
1399 * mod.ancestors -> array
1401 * Returns a list of modules included/prepended in <i>mod</i>
1402 * (including <i>mod</i> itself).
1404 * module Mod
1405 * include Math
1406 * include Comparable
1407 * prepend Enumerable
1408 * end
1410 * Mod.ancestors #=> [Enumerable, Mod, Comparable, Math]
1411 * Math.ancestors #=> [Math]
1412 * Enumerable.ancestors #=> [Enumerable]
1415 VALUE
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);
1430 else {
1431 rb_ary_push(ary, p);
1434 return ary;
1437 struct subclass_traverse_data
1439 VALUE buffer;
1440 long count;
1441 long maxcount;
1442 bool immediate_only;
1445 static void
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);
1455 data->count++;
1456 if (!data->immediate_only) {
1457 rb_class_foreach_subclass(klass, class_descendants_recursive, v);
1460 else {
1461 rb_class_foreach_subclass(klass, class_descendants_recursive, v);
1465 static VALUE
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;
1476 data.count = 0;
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");
1487 return data.buffer;
1491 * call-seq:
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.
1498 * class A; end
1499 * class B < A; end
1500 * class C < B; end
1501 * class D < A; end
1503 * A.subclasses #=> [D, B]
1504 * B.subclasses #=> [C]
1505 * C.subclasses #=> []
1508 VALUE
1509 rb_class_subclasses(VALUE klass)
1511 return class_descendants(klass, true);
1514 static void
1515 ins_methods_push(st_data_t name, st_data_t ary)
1517 rb_ary_push((VALUE)ary, ID2SYM((ID)name));
1520 static int
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:
1526 break;
1527 default: /* everything but private */
1528 ins_methods_push(name, ary);
1529 break;
1531 return ST_CONTINUE;
1534 static int
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);
1540 return ST_CONTINUE;
1543 static int
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);
1549 static int
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);
1555 static int
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 {
1562 st_table *list;
1563 int recur;
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 */
1583 else {
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;
1592 static void
1593 add_instance_method_list(VALUE mod, struct method_entry_arg *me_arg)
1595 struct rb_id_table *m_tbl = RCLASS_M_TBL(mod);
1596 if (!m_tbl) return;
1597 rb_id_table_foreach(m_tbl, method_entry_i, me_arg);
1600 static bool
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;
1606 return false;
1609 static VALUE
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))
1612 VALUE ary;
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;
1621 if (obj) {
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);
1629 prepended = 1;
1632 for (; mod; mod = RCLASS_SUPER(mod)) {
1633 add_instance_method_list(mod, &me_arg);
1634 if (BUILTIN_TYPE(mod) == T_ICLASS && !prepended) continue;
1635 if (!recur) break;
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);
1641 return ary;
1645 * call-seq:
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.
1653 * module A
1654 * def method1() end
1655 * end
1656 * class B
1657 * include A
1658 * def method2() end
1659 * end
1660 * class C < B
1661 * def method3() end
1662 * end
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
1671 VALUE
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);
1678 * call-seq:
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.
1686 VALUE
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);
1693 * call-seq:
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.
1700 * module Mod
1701 * def method1() end
1702 * private :method1
1703 * def method2() end
1704 * end
1705 * Mod.instance_methods #=> [:method2]
1706 * Mod.private_instance_methods #=> [:method1]
1709 VALUE
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);
1716 * call-seq:
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.
1724 VALUE
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);
1731 * call-seq:
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>.
1741 * class Klass
1742 * def klass_method()
1743 * end
1744 * end
1745 * k = Klass.new
1746 * k.methods[0..9] #=> [:klass_method, :nil?, :===,
1747 * # :==~, :!, :eql?
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
1756 * k.extend M123
1757 * k.methods(false) #=> [:singleton_method]
1760 VALUE
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);
1771 * call-seq:
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.
1779 VALUE
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);
1786 * call-seq:
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.
1794 VALUE
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);
1801 * call-seq:
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.
1809 VALUE
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);
1816 * call-seq:
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.
1824 * module Other
1825 * def three() end
1826 * end
1828 * class Single
1829 * def Single.four() end
1830 * end
1832 * a = Single.new
1834 * def a.one()
1835 * end
1837 * class << a
1838 * include Other
1839 * def two()
1840 * end
1841 * end
1843 * Single.singleton_methods #=> [:four]
1844 * a.singleton_methods(false) #=> [:two, :one]
1845 * a.singleton_methods #=> [:two, :one, :three]
1848 VALUE
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;
1854 int recur = TRUE;
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);
1868 if (recur) {
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);
1878 return ary;
1882 * \}
1885 * \addtogroup defmethod
1886 * \{
1889 #ifdef rb_define_method_id
1890 #undef rb_define_method_id
1891 #endif
1892 void
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
1900 #endif
1901 void
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
1909 #endif
1910 void
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
1918 #endif
1919 void
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);
1925 void
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;
1939 void
1940 rb_undef_methods_from(VALUE klass, VALUE super)
1942 struct rb_id_table *mtbl = RCLASS_M_TBL(super);
1943 if (mtbl) {
1944 rb_id_table_foreach(mtbl, undef_method_i, (void *)klass);
1949 * \}
1952 * \addtogroup class
1953 * \{
1956 static inline VALUE
1957 special_singleton_class_of(VALUE obj)
1959 switch (obj) {
1960 case Qnil: return rb_cNilClass;
1961 case Qfalse: return rb_cFalseClass;
1962 case Qtrue: return rb_cTrueClass;
1963 default: return Qnil;
1967 VALUE
1968 rb_special_singleton_class(VALUE obj)
1970 return special_singleton_class_of(obj);
1974 * \internal
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.
1982 static VALUE
1983 singleton_class_of(VALUE obj)
1985 VALUE klass;
1987 switch (TYPE(obj)) {
1988 case T_FIXNUM:
1989 case T_BIGNUM:
1990 case T_FLOAT:
1991 case T_SYMBOL:
1992 rb_raise(rb_eTypeError, "can't define singleton");
1994 case T_FALSE:
1995 case T_TRUE:
1996 case T_NIL:
1997 klass = special_singleton_class_of(obj);
1998 if (NIL_P(klass))
1999 rb_bug("unknown immediate %p", (void *)obj);
2000 return klass;
2002 case T_STRING:
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));
2018 return klass;
2021 void
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
2036 * singleton object.
2038 * \param obj an arbitrary object.
2039 * \return the singleton class or nil.
2041 VALUE
2042 rb_singleton_class_get(VALUE obj)
2044 VALUE klass;
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;
2052 return klass;
2055 VALUE
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);
2063 return klass;
2067 * \}
2071 * \addtogroup defmethod
2072 * \{
2075 #ifdef rb_define_singleton_method
2076 #undef rb_define_singleton_method
2077 #endif
2078 void
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
2086 #endif
2087 void
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
2096 #endif
2097 void
2098 rb_define_global_function(const char *name, VALUE (*func)(ANYARGS), int argc)
2100 rb_define_module_function(rb_mKernel, name, func, argc);
2103 void
2104 rb_define_alias(VALUE klass, const char *name1, const char *name2)
2106 rb_alias(klass, rb_intern(name1), rb_intern(name2));
2109 void
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");
2121 if (len > 0) {
2122 rb_str_cat_cstr(error_message, ": ");
2123 while (1) {
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));
2135 static void
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));
2142 static void
2143 unknown_keyword_error(VALUE hash, const ID *table, int keywords)
2145 int i;
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));
2154 static int
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);
2161 return ST_CONTINUE;
2164 VALUE
2165 rb_extract_keywords(VALUE *orighash)
2167 VALUE parthash[2] = {0, 0};
2168 VALUE hash = *orighash;
2170 if (RHASH_EMPTY_P(hash)) {
2171 *orighash = 0;
2172 return 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));
2179 return parthash[0];
2183 rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
2185 int i = 0, j;
2186 int rest = 0;
2187 VALUE missing = Qnil;
2188 st_data_t key;
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;
2197 if (optional < 0) {
2198 rest = 1;
2199 optional = -1-optional;
2201 if (required) {
2202 for (; i < required; i++) {
2203 VALUE keyword = ID2SYM(table[i]);
2204 if (keyword_hash) {
2205 if (extract_kwarg(keyword, values[i])) {
2206 continue;
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);
2216 j = i;
2217 if (optional && keyword_hash) {
2218 for (i = 0; i < optional; i++) {
2219 if (extract_kwarg(ID2SYM(table[required+i]), values[required+i])) {
2220 j++;
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++) {
2231 values[i] = Qundef;
2234 return j;
2235 #undef extract_kwarg
2238 struct rb_scan_args_t {
2239 int kw_flag;
2240 int n_lead;
2241 int n_opt;
2242 int n_trail;
2243 bool f_var;
2244 bool f_hash;
2245 bool f_block;
2248 static void
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;
2256 if (ISDIGIT(*p)) {
2257 arg->n_lead = *p - '0';
2258 p++;
2259 if (ISDIGIT(*p)) {
2260 arg->n_opt = *p - '0';
2261 p++;
2264 if (*p == '*') {
2265 arg->f_var = 1;
2266 p++;
2268 if (ISDIGIT(*p)) {
2269 arg->n_trail = *p - '0';
2270 p++;
2272 if (*p == ':') {
2273 arg->f_hash = 1;
2274 p++;
2276 if (*p == '&') {
2277 arg->f_block = 1;
2278 p++;
2280 if (*p != '\0') {
2281 rb_fatal("bad scan arg format: %s", fmt);
2285 static int
2286 rb_scan_args_assign(const struct rb_scan_args_t *arg, int argc, const VALUE *const argv, va_list vargs)
2288 int i, argi = 0;
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);
2305 argc--;
2309 if (argc < n_mand) {
2310 goto argc_error;
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];
2317 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];
2324 argi++;
2326 else {
2327 if (var) *var = Qnil;
2330 /* capture variable length arguments */
2331 if (f_var) {
2332 int n_var = argc - argi - n_trail;
2334 var = rb_scan_args_next_param();
2335 if (0 < n_var) {
2336 if (var) *var = rb_ary_new_from_values(n_var, &argv[argi]);
2337 argi += n_var;
2339 else {
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];
2347 argi++;
2349 /* capture an option hash - phase 2: assignment */
2350 if (f_hash) {
2351 var = rb_scan_args_next_param();
2352 if (var) *var = hash;
2354 /* capture iterator block */
2355 if (f_block) {
2356 var = rb_scan_args_next_param();
2357 if (rb_block_given_p()) {
2358 *var = rb_block_proc();
2360 else {
2361 *var = Qnil;
2365 if (argi == argc) {
2366 return argc;
2369 argc_error:
2370 return -(argc + 1);
2371 #undef rb_scan_args_next_param
2374 static int
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;
2383 if (argc >= 0) {
2384 return argc;
2387 argc = -argc - 1;
2388 rb_error_arity(argc, n_mand, f_var ? UNLIMITED_ARGUMENTS : n_mand + n_opt);
2389 UNREACHABLE_RETURN(-1);
2392 #undef rb_scan_args
2394 rb_scan_args(int argc, const VALUE *argv, const char *fmt, ...)
2396 va_list vargs;
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);
2401 va_end(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, ...)
2409 va_list vargs;
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);
2414 va_end(vargs);
2415 return rb_scan_args_result(&arg, argc);
2419 * \}