1 /**********************************************************************
2 
3   class.c -
4 
5   $Author: usa $
6   created at: Tue Aug 10 15:05:44 JST 1993
7 
8   Copyright (C) 1993-2007 Yukihiro Matsumoto
9 
10 **********************************************************************/
11 
12 /*!
13  * \defgroup class Classes and their hierarchy.
14  * \par Terminology
15  * - class: same as in Ruby.
16  * - singleton class: class for a particular object
17  * - eigenclass: = singleton class
18  * - metaclass: class of a class. metaclass is a kind of singleton class.
19  * - metametaclass: class of a metaclass.
20  * - meta^(n)-class: class of a meta^(n-1)-class.
21  * - attached object: A singleton class knows its unique instance.
22  *   The instance is called the attached object for the singleton class.
23  * \{
24  */
25 
26 #include "internal.h"
27 #include "ruby/st.h"
28 #include "constant.h"
29 #include "vm_core.h"
30 #include "id_table.h"
31 #include <ctype.h>
32 
33 #define id_attached id__attached__
34 
35 #define METACLASS_OF(k) RBASIC(k)->klass
36 #define SET_METACLASS_OF(k, cls) RBASIC_SET_CLASS(k, cls)
37 
38 void
rb_class_subclass_add(VALUE super,VALUE klass)39 rb_class_subclass_add(VALUE super, VALUE klass)
40 {
41     rb_subclass_entry_t *entry, *head;
42 
43     if (super && super != Qundef) {
44 	entry = ALLOC(rb_subclass_entry_t);
45 	entry->klass = klass;
46 	entry->next = NULL;
47 
48 	head = RCLASS_EXT(super)->subclasses;
49 	if (head) {
50 	    entry->next = head;
51 	    RCLASS_EXT(head->klass)->parent_subclasses = &entry->next;
52 	}
53 
54 	RCLASS_EXT(super)->subclasses = entry;
55 	RCLASS_EXT(klass)->parent_subclasses = &RCLASS_EXT(super)->subclasses;
56     }
57 }
58 
59 static void
rb_module_add_to_subclasses_list(VALUE module,VALUE iclass)60 rb_module_add_to_subclasses_list(VALUE module, VALUE iclass)
61 {
62     rb_subclass_entry_t *entry, *head;
63 
64     entry = ALLOC(rb_subclass_entry_t);
65     entry->klass = iclass;
66     entry->next = NULL;
67 
68     head = RCLASS_EXT(module)->subclasses;
69     if (head) {
70 	entry->next = head;
71 	RCLASS_EXT(head->klass)->module_subclasses = &entry->next;
72     }
73 
74     RCLASS_EXT(module)->subclasses = entry;
75     RCLASS_EXT(iclass)->module_subclasses = &RCLASS_EXT(module)->subclasses;
76 }
77 
78 void
rb_class_remove_from_super_subclasses(VALUE klass)79 rb_class_remove_from_super_subclasses(VALUE klass)
80 {
81     rb_subclass_entry_t *entry;
82 
83     if (RCLASS_EXT(klass)->parent_subclasses) {
84 	entry = *RCLASS_EXT(klass)->parent_subclasses;
85 
86 	*RCLASS_EXT(klass)->parent_subclasses = entry->next;
87 	if (entry->next) {
88 	    RCLASS_EXT(entry->next->klass)->parent_subclasses = RCLASS_EXT(klass)->parent_subclasses;
89 	}
90 	xfree(entry);
91     }
92 
93     RCLASS_EXT(klass)->parent_subclasses = NULL;
94 }
95 
96 void
rb_class_remove_from_module_subclasses(VALUE klass)97 rb_class_remove_from_module_subclasses(VALUE klass)
98 {
99     rb_subclass_entry_t *entry;
100 
101     if (RCLASS_EXT(klass)->module_subclasses) {
102 	entry = *RCLASS_EXT(klass)->module_subclasses;
103 	*RCLASS_EXT(klass)->module_subclasses = entry->next;
104 
105 	if (entry->next) {
106 	    RCLASS_EXT(entry->next->klass)->module_subclasses = RCLASS_EXT(klass)->module_subclasses;
107 	}
108 
109 	xfree(entry);
110     }
111 
112     RCLASS_EXT(klass)->module_subclasses = NULL;
113 }
114 
115 void
rb_class_foreach_subclass(VALUE klass,void (* f)(VALUE,VALUE),VALUE arg)116 rb_class_foreach_subclass(VALUE klass, void (*f)(VALUE, VALUE), VALUE arg)
117 {
118     rb_subclass_entry_t *cur = RCLASS_EXT(klass)->subclasses;
119 
120     /* do not be tempted to simplify this loop into a for loop, the order of
121        operations is important here if `f` modifies the linked list */
122     while (cur) {
123 	VALUE curklass = cur->klass;
124 	cur = cur->next;
125 	f(curklass, arg);
126     }
127 }
128 
129 static void
class_detach_subclasses(VALUE klass,VALUE arg)130 class_detach_subclasses(VALUE klass, VALUE arg)
131 {
132     rb_class_remove_from_super_subclasses(klass);
133 }
134 
135 void
rb_class_detach_subclasses(VALUE klass)136 rb_class_detach_subclasses(VALUE klass)
137 {
138     rb_class_foreach_subclass(klass, class_detach_subclasses, Qnil);
139 }
140 
141 static void
class_detach_module_subclasses(VALUE klass,VALUE arg)142 class_detach_module_subclasses(VALUE klass, VALUE arg)
143 {
144     rb_class_remove_from_module_subclasses(klass);
145 }
146 
147 void
rb_class_detach_module_subclasses(VALUE klass)148 rb_class_detach_module_subclasses(VALUE klass)
149 {
150     rb_class_foreach_subclass(klass, class_detach_module_subclasses, Qnil);
151 }
152 
153 /**
154  * Allocates a struct RClass for a new class.
155  *
156  * \param flags     initial value for basic.flags of the returned class.
157  * \param klass     the class of the returned class.
158  * \return          an uninitialized Class object.
159  * \pre  \p klass must refer \c Class class or an ancestor of Class.
160  * \pre  \code (flags | T_CLASS) != 0  \endcode
161  * \post the returned class can safely be \c #initialize 'd.
162  *
163  * \note this function is not Class#allocate.
164  */
165 static VALUE
class_alloc(VALUE flags,VALUE klass)166 class_alloc(VALUE flags, VALUE klass)
167 {
168     NEWOBJ_OF(obj, struct RClass, klass, (flags & T_MASK) | FL_PROMOTED1 /* start from age == 2 */ | (RGENGC_WB_PROTECTED_CLASS ? FL_WB_PROTECTED : 0));
169     obj->ptr = ZALLOC(rb_classext_t);
170     /* ZALLOC
171       RCLASS_IV_TBL(obj) = 0;
172       RCLASS_CONST_TBL(obj) = 0;
173       RCLASS_M_TBL(obj) = 0;
174       RCLASS_IV_INDEX_TBL(obj) = 0;
175       RCLASS_SET_SUPER((VALUE)obj, 0);
176       RCLASS_EXT(obj)->subclasses = NULL;
177       RCLASS_EXT(obj)->parent_subclasses = NULL;
178       RCLASS_EXT(obj)->module_subclasses = NULL;
179      */
180     RCLASS_SET_ORIGIN((VALUE)obj, (VALUE)obj);
181     RCLASS_SERIAL(obj) = rb_next_class_serial();
182     RCLASS_REFINED_CLASS(obj) = Qnil;
183     RCLASS_EXT(obj)->allocator = 0;
184 
185     return (VALUE)obj;
186 }
187 
188 static void
RCLASS_M_TBL_INIT(VALUE c)189 RCLASS_M_TBL_INIT(VALUE c)
190 {
191     RCLASS_M_TBL(c) = rb_id_table_create(0);
192 }
193 
194 /*!
195  * A utility function that wraps class_alloc.
196  *
197  * allocates a class and initializes safely.
198  * \param super     a class from which the new class derives.
199  * \return          a class object.
200  * \pre  \a super must be a class.
201  * \post the metaclass of the new class is Class.
202  */
203 VALUE
rb_class_boot(VALUE super)204 rb_class_boot(VALUE super)
205 {
206     VALUE klass = class_alloc(T_CLASS, rb_cClass);
207 
208     RCLASS_SET_SUPER(klass, super);
209     RCLASS_M_TBL_INIT(klass);
210 
211     OBJ_INFECT(klass, super);
212     return (VALUE)klass;
213 }
214 
215 
216 /*!
217  * Ensures a class can be derived from super.
218  *
219  * \param super a reference to an object.
220  * \exception TypeError if \a super is not a Class or \a super is a singleton class.
221  */
222 void
rb_check_inheritable(VALUE super)223 rb_check_inheritable(VALUE super)
224 {
225     if (!RB_TYPE_P(super, T_CLASS)) {
226 	rb_raise(rb_eTypeError, "superclass must be a Class (%"PRIsVALUE" given)",
227 		 rb_obj_class(super));
228     }
229     if (RBASIC(super)->flags & FL_SINGLETON) {
230 	rb_raise(rb_eTypeError, "can't make subclass of singleton class");
231     }
232     if (super == rb_cClass) {
233 	rb_raise(rb_eTypeError, "can't make subclass of Class");
234     }
235 }
236 
237 
238 /*!
239  * Creates a new class.
240  * \param super     a class from which the new class derives.
241  * \exception TypeError \a super is not inheritable.
242  * \exception TypeError \a super is the Class class.
243  */
244 VALUE
rb_class_new(VALUE super)245 rb_class_new(VALUE super)
246 {
247     Check_Type(super, T_CLASS);
248     rb_check_inheritable(super);
249     return rb_class_boot(super);
250 }
251 
252 static void
clone_method(VALUE old_klass,VALUE new_klass,ID mid,const rb_method_entry_t * me)253 clone_method(VALUE old_klass, VALUE new_klass, ID mid, const rb_method_entry_t *me)
254 {
255     if (me->def->type == VM_METHOD_TYPE_ISEQ) {
256 	rb_cref_t *new_cref;
257 	rb_vm_rewrite_cref(me->def->body.iseq.cref, old_klass, new_klass, &new_cref);
258 	rb_add_method_iseq(new_klass, mid, me->def->body.iseq.iseqptr, new_cref, METHOD_ENTRY_VISI(me));
259     }
260     else {
261 	rb_method_entry_set(new_klass, mid, me, METHOD_ENTRY_VISI(me));
262     }
263 }
264 
265 struct clone_method_arg {
266     VALUE new_klass;
267     VALUE old_klass;
268 };
269 
270 static enum rb_id_table_iterator_result
clone_method_i(ID key,VALUE value,void * data)271 clone_method_i(ID key, VALUE value, void *data)
272 {
273     const struct clone_method_arg *arg = (struct clone_method_arg *)data;
274     clone_method(arg->old_klass, arg->new_klass, key, (const rb_method_entry_t *)value);
275     return ID_TABLE_CONTINUE;
276 }
277 
278 struct clone_const_arg {
279     VALUE klass;
280     struct rb_id_table *tbl;
281 };
282 
283 static int
clone_const(ID key,const rb_const_entry_t * ce,struct clone_const_arg * arg)284 clone_const(ID key, const rb_const_entry_t *ce, struct clone_const_arg *arg)
285 {
286     rb_const_entry_t *nce = ALLOC(rb_const_entry_t);
287     MEMCPY(nce, ce, rb_const_entry_t, 1);
288     RB_OBJ_WRITTEN(arg->klass, Qundef, ce->value);
289     RB_OBJ_WRITTEN(arg->klass, Qundef, ce->file);
290 
291     rb_id_table_insert(arg->tbl, key, (VALUE)nce);
292     return ID_TABLE_CONTINUE;
293 }
294 
295 static enum rb_id_table_iterator_result
clone_const_i(ID key,VALUE value,void * data)296 clone_const_i(ID key, VALUE value, void *data)
297 {
298     return clone_const(key, (const rb_const_entry_t *)value, data);
299 }
300 
301 static void
class_init_copy_check(VALUE clone,VALUE orig)302 class_init_copy_check(VALUE clone, VALUE orig)
303 {
304     if (orig == rb_cBasicObject) {
305 	rb_raise(rb_eTypeError, "can't copy the root class");
306     }
307     if (RCLASS_SUPER(clone) != 0 || clone == rb_cBasicObject) {
308 	rb_raise(rb_eTypeError, "already initialized class");
309     }
310     if (FL_TEST(orig, FL_SINGLETON)) {
311 	rb_raise(rb_eTypeError, "can't copy singleton class");
312     }
313 }
314 
315 /* :nodoc: */
316 VALUE
rb_mod_init_copy(VALUE clone,VALUE orig)317 rb_mod_init_copy(VALUE clone, VALUE orig)
318 {
319     if (RB_TYPE_P(clone, T_CLASS)) {
320 	class_init_copy_check(clone, orig);
321     }
322     if (!OBJ_INIT_COPY(clone, orig)) return clone;
323     if (!FL_TEST(CLASS_OF(clone), FL_SINGLETON)) {
324 	RBASIC_SET_CLASS(clone, rb_singleton_class_clone(orig));
325 	rb_singleton_class_attached(RBASIC(clone)->klass, (VALUE)clone);
326     }
327     RCLASS_SET_SUPER(clone, RCLASS_SUPER(orig));
328     RCLASS_EXT(clone)->allocator = RCLASS_EXT(orig)->allocator;
329     if (RCLASS_IV_TBL(clone)) {
330 	st_free_table(RCLASS_IV_TBL(clone));
331 	RCLASS_IV_TBL(clone) = 0;
332     }
333     if (RCLASS_CONST_TBL(clone)) {
334 	rb_free_const_table(RCLASS_CONST_TBL(clone));
335 	RCLASS_CONST_TBL(clone) = 0;
336     }
337     RCLASS_M_TBL(clone) = 0;
338     if (RCLASS_IV_TBL(orig)) {
339 	st_data_t id;
340 
341 	RCLASS_IV_TBL(clone) = rb_st_copy(clone, RCLASS_IV_TBL(orig));
342 	CONST_ID(id, "__tmp_classpath__");
343 	st_delete(RCLASS_IV_TBL(clone), &id, 0);
344 	CONST_ID(id, "__classpath__");
345 	st_delete(RCLASS_IV_TBL(clone), &id, 0);
346 	CONST_ID(id, "__classid__");
347 	st_delete(RCLASS_IV_TBL(clone), &id, 0);
348     }
349     if (RCLASS_CONST_TBL(orig)) {
350 	struct clone_const_arg arg;
351 
352 	arg.tbl = RCLASS_CONST_TBL(clone) = rb_id_table_create(0);
353 	arg.klass = clone;
354 	rb_id_table_foreach(RCLASS_CONST_TBL(orig), clone_const_i, &arg);
355     }
356     if (RCLASS_M_TBL(orig)) {
357 	struct clone_method_arg arg;
358 	arg.old_klass = orig;
359 	arg.new_klass = clone;
360 	RCLASS_M_TBL_INIT(clone);
361 	rb_id_table_foreach(RCLASS_M_TBL(orig), clone_method_i, &arg);
362     }
363 
364     return clone;
365 }
366 
367 VALUE
rb_singleton_class_clone(VALUE obj)368 rb_singleton_class_clone(VALUE obj)
369 {
370     return rb_singleton_class_clone_and_attach(obj, Qundef);
371 }
372 
373 // Clone and return the singleton class of `obj` if it has been created and is attached to `obj`.
374 VALUE
rb_singleton_class_clone_and_attach(VALUE obj,VALUE attach)375 rb_singleton_class_clone_and_attach(VALUE obj, VALUE attach)
376 {
377     const VALUE klass = RBASIC(obj)->klass;
378 
379     // Note that `rb_singleton_class()` can create situations where `klass` is
380     // attached to an object other than `obj`. In which case `obj` does not have
381     // a material singleton class attached yet and there is no singleton class
382     // to clone.
383     if (!(FL_TEST(klass, FL_SINGLETON) && rb_attr_get(klass, id_attached) == obj)) {
384         // nothing to clone
385         return klass;
386     }
387     else {
388 	/* copy singleton(unnamed) class */
389         bool klass_of_clone_is_new;
390 	VALUE clone = class_alloc(RBASIC(klass)->flags, 0);
391 
392 	if (BUILTIN_TYPE(obj) == T_CLASS) {
393             klass_of_clone_is_new = true;
394 	    RBASIC_SET_CLASS(clone, clone);
395 	}
396 	else {
397             VALUE klass_metaclass_clone = rb_singleton_class_clone(klass);
398             // When `METACLASS_OF(klass) == klass_metaclass_clone`, it means the
399             // recursive call did not clone `METACLASS_OF(klass)`.
400             klass_of_clone_is_new = (METACLASS_OF(klass) != klass_metaclass_clone);
401             RBASIC_SET_CLASS(clone, klass_metaclass_clone);
402 	}
403 
404 	RCLASS_SET_SUPER(clone, RCLASS_SUPER(klass));
405 	RCLASS_EXT(clone)->allocator = RCLASS_EXT(klass)->allocator;
406 	if (RCLASS_IV_TBL(klass)) {
407 	    RCLASS_IV_TBL(clone) = rb_st_copy(clone, RCLASS_IV_TBL(klass));
408 	}
409 	if (RCLASS_CONST_TBL(klass)) {
410 	    struct clone_const_arg arg;
411 	    arg.tbl = RCLASS_CONST_TBL(clone) = rb_id_table_create(0);
412 	    arg.klass = clone;
413 	    rb_id_table_foreach(RCLASS_CONST_TBL(klass), clone_const_i, &arg);
414 	}
415 	if (attach != Qundef) {
416 	    rb_singleton_class_attached(clone, attach);
417 	}
418 	RCLASS_M_TBL_INIT(clone);
419 	{
420 	    struct clone_method_arg arg;
421 	    arg.old_klass = klass;
422 	    arg.new_klass = clone;
423 	    rb_id_table_foreach(RCLASS_M_TBL(klass), clone_method_i, &arg);
424 	}
425         if (klass_of_clone_is_new) {
426             rb_singleton_class_attached(RBASIC(clone)->klass, clone);
427         }
428 	FL_SET(clone, FL_SINGLETON);
429 
430 	return clone;
431     }
432 }
433 
434 /*!
435  * Attach a object to a singleton class.
436  * @pre \a klass is the singleton class of \a obj.
437  */
438 void
rb_singleton_class_attached(VALUE klass,VALUE obj)439 rb_singleton_class_attached(VALUE klass, VALUE obj)
440 {
441     if (FL_TEST(klass, FL_SINGLETON)) {
442 	if (!RCLASS_IV_TBL(klass)) {
443 	    RCLASS_IV_TBL(klass) = st_init_numtable();
444 	}
445 	rb_class_ivar_set(klass, id_attached, obj);
446     }
447 }
448 
449 /*!
450  * whether k is a meta^(n)-class of Class class
451  * @retval 1 if \a k is a meta^(n)-class of Class class (n >= 0)
452  * @retval 0 otherwise
453  */
454 #define META_CLASS_OF_CLASS_CLASS_P(k)  (METACLASS_OF(k) == (k))
455 
456 static int
rb_singleton_class_has_metaclass_p(VALUE sklass)457 rb_singleton_class_has_metaclass_p(VALUE sklass)
458 {
459     return rb_attr_get(METACLASS_OF(sklass), id_attached) == sklass;
460 }
461 
462 int
rb_singleton_class_internal_p(VALUE sklass)463 rb_singleton_class_internal_p(VALUE sklass)
464 {
465     return (RB_TYPE_P(rb_attr_get(sklass, id_attached), T_CLASS) &&
466 	    !rb_singleton_class_has_metaclass_p(sklass));
467 }
468 
469 /*!
470  * whether k has a metaclass
471  * @retval 1 if \a k has a metaclass
472  * @retval 0 otherwise
473  */
474 #define HAVE_METACLASS_P(k) \
475     (FL_TEST(METACLASS_OF(k), FL_SINGLETON) && \
476      rb_singleton_class_has_metaclass_p(k))
477 
478 /*!
479  * ensures \a klass belongs to its own eigenclass.
480  * @return the eigenclass of \a klass
481  * @post \a klass belongs to the returned eigenclass.
482  *       i.e. the attached object of the eigenclass is \a klass.
483  * @note this macro creates a new eigenclass if necessary.
484  */
485 #define ENSURE_EIGENCLASS(klass) \
486     (HAVE_METACLASS_P(klass) ? METACLASS_OF(klass) : make_metaclass(klass))
487 
488 
489 /*!
490  * Creates a metaclass of \a klass
491  * \param klass     a class
492  * \return          created metaclass for the class
493  * \pre \a klass is a Class object
494  * \pre \a klass has no singleton class.
495  * \post the class of \a klass is the returned class.
496  * \post the returned class is meta^(n+1)-class when \a klass is a meta^(n)-klass for n >= 0
497  */
498 static inline VALUE
make_metaclass(VALUE klass)499 make_metaclass(VALUE klass)
500 {
501     VALUE super;
502     VALUE metaclass = rb_class_boot(Qundef);
503 
504     FL_SET(metaclass, FL_SINGLETON);
505     rb_singleton_class_attached(metaclass, klass);
506 
507     if (META_CLASS_OF_CLASS_CLASS_P(klass)) {
508 	SET_METACLASS_OF(klass, metaclass);
509 	SET_METACLASS_OF(metaclass, metaclass);
510     }
511     else {
512 	VALUE tmp = METACLASS_OF(klass); /* for a meta^(n)-class klass, tmp is meta^(n)-class of Class class */
513 	SET_METACLASS_OF(klass, metaclass);
514 	SET_METACLASS_OF(metaclass, ENSURE_EIGENCLASS(tmp));
515     }
516 
517     super = RCLASS_SUPER(klass);
518     while (RB_TYPE_P(super, T_ICLASS)) super = RCLASS_SUPER(super);
519     RCLASS_SET_SUPER(metaclass, super ? ENSURE_EIGENCLASS(super) : rb_cClass);
520 
521     OBJ_INFECT(metaclass, RCLASS_SUPER(metaclass));
522 
523     return metaclass;
524 }
525 
526 /*!
527  * Creates a singleton class for \a obj.
528  * \pre \a obj must not a immediate nor a special const.
529  * \pre \a obj must not a Class object.
530  * \pre \a obj has no singleton class.
531  */
532 static inline VALUE
make_singleton_class(VALUE obj)533 make_singleton_class(VALUE obj)
534 {
535     VALUE orig_class = RBASIC(obj)->klass;
536     VALUE klass = rb_class_boot(orig_class);
537 
538     FL_SET(klass, FL_SINGLETON);
539     RBASIC_SET_CLASS(obj, klass);
540     rb_singleton_class_attached(klass, obj);
541 
542     SET_METACLASS_OF(klass, METACLASS_OF(rb_class_real(orig_class)));
543     return klass;
544 }
545 
546 
547 static VALUE
boot_defclass(const char * name,VALUE super)548 boot_defclass(const char *name, VALUE super)
549 {
550     VALUE obj = rb_class_boot(super);
551     ID id = rb_intern(name);
552 
553     rb_name_class(obj, id);
554     rb_const_set((rb_cObject ? rb_cObject : obj), id, obj);
555     return obj;
556 }
557 
558 void
Init_class_hierarchy(void)559 Init_class_hierarchy(void)
560 {
561     rb_cBasicObject = boot_defclass("BasicObject", 0);
562     rb_cObject = boot_defclass("Object", rb_cBasicObject);
563     rb_gc_register_mark_object(rb_cObject);
564 
565     /* resolve class name ASAP for order-independence */
566     rb_class_name(rb_cObject);
567 
568     rb_cModule = boot_defclass("Module", rb_cObject);
569     rb_cClass =  boot_defclass("Class",  rb_cModule);
570 
571     rb_const_set(rb_cObject, rb_intern_const("BasicObject"), rb_cBasicObject);
572     RBASIC_SET_CLASS(rb_cClass, rb_cClass);
573     RBASIC_SET_CLASS(rb_cModule, rb_cClass);
574     RBASIC_SET_CLASS(rb_cObject, rb_cClass);
575     RBASIC_SET_CLASS(rb_cBasicObject, rb_cClass);
576 }
577 
578 
579 /*!
580  * \internal
581  * Creates a new *singleton class* for an object.
582  *
583  * \pre \a obj has no singleton class.
584  * \note DO NOT USE the function in an extension libraries. Use \ref rb_singleton_class.
585  * \param obj     An object.
586  * \param unused  ignored.
587  * \return        The singleton class of the object.
588  */
589 VALUE
rb_make_metaclass(VALUE obj,VALUE unused)590 rb_make_metaclass(VALUE obj, VALUE unused)
591 {
592     if (BUILTIN_TYPE(obj) == T_CLASS) {
593 	return make_metaclass(obj);
594     }
595     else {
596 	return make_singleton_class(obj);
597     }
598 }
599 
600 
601 /*!
602  * Defines a new class.
603  * \param id     ignored
604  * \param super  A class from which the new class will derive. NULL means \c Object class.
605  * \return       the created class
606  * \throw TypeError if super is not a \c Class object.
607  *
608  * \note the returned class will not be associated with \a id.
609  *       You must explicitly set a class name if necessary.
610  */
611 VALUE
rb_define_class_id(ID id,VALUE super)612 rb_define_class_id(ID id, VALUE super)
613 {
614     VALUE klass;
615 
616     if (!super) super = rb_cObject;
617     klass = rb_class_new(super);
618     rb_make_metaclass(klass, RBASIC(super)->klass);
619 
620     return klass;
621 }
622 
623 
624 /*!
625  * Calls Class#inherited.
626  * \param super  A class which will be called #inherited.
627  *               NULL means Object class.
628  * \param klass  A Class object which derived from \a super
629  * \return the value \c Class#inherited's returns
630  * \pre Each of \a super and \a klass must be a \c Class object.
631  */
632 MJIT_FUNC_EXPORTED VALUE
rb_class_inherited(VALUE super,VALUE klass)633 rb_class_inherited(VALUE super, VALUE klass)
634 {
635     ID inherited;
636     if (!super) super = rb_cObject;
637     CONST_ID(inherited, "inherited");
638     return rb_funcall(super, inherited, 1, klass);
639 }
640 
641 
642 
643 /*!
644  * Defines a top-level class.
645  * \param name   name of the class
646  * \param super  a class from which the new class will derive.
647  * \return the created class
648  * \throw TypeError if the constant name \a name is already taken but
649  *                  the constant is not a \c Class.
650  * \throw TypeError if the class is already defined but the class can not
651  *                  be reopened because its superclass is not \a super.
652  * \throw ArgumentError if the \a super is NULL.
653  * \post top-level constant named \a name refers the returned class.
654  *
655  * \note if a class named \a name is already defined and its superclass is
656  *       \a super, the function just returns the defined class.
657  */
658 VALUE
rb_define_class(const char * name,VALUE super)659 rb_define_class(const char *name, VALUE super)
660 {
661     VALUE klass;
662     ID id;
663 
664     id = rb_intern(name);
665     if (rb_const_defined(rb_cObject, id)) {
666 	klass = rb_const_get(rb_cObject, id);
667 	if (!RB_TYPE_P(klass, T_CLASS)) {
668 	    rb_raise(rb_eTypeError, "%s is not a class (%"PRIsVALUE")",
669 		     name, rb_obj_class(klass));
670 	}
671 	if (rb_class_real(RCLASS_SUPER(klass)) != super) {
672 	    rb_raise(rb_eTypeError, "superclass mismatch for class %s", name);
673 	}
674 	return klass;
675     }
676     if (!super) {
677 	rb_raise(rb_eArgError, "no super class for `%s'", name);
678     }
679     klass = rb_define_class_id(id, super);
680     rb_vm_add_root_module(id, klass);
681     rb_name_class(klass, id);
682     rb_const_set(rb_cObject, id, klass);
683     rb_class_inherited(super, klass);
684 
685     return klass;
686 }
687 
688 
689 /*!
690  * Defines a class under the namespace of \a outer.
691  * \param outer  a class which contains the new class.
692  * \param name   name of the new class
693  * \param super  a class from which the new class will derive.
694  *               NULL means \c Object class.
695  * \return the created class
696  * \throw TypeError if the constant name \a name is already taken but
697  *                  the constant is not a \c Class.
698  * \throw TypeError if the class is already defined but the class can not
699  *                  be reopened because its superclass is not \a super.
700  * \post top-level constant named \a name refers the returned class.
701  *
702  * \note if a class named \a name is already defined and its superclass is
703  *       \a super, the function just returns the defined class.
704  */
705 VALUE
rb_define_class_under(VALUE outer,const char * name,VALUE super)706 rb_define_class_under(VALUE outer, const char *name, VALUE super)
707 {
708     return rb_define_class_id_under(outer, rb_intern(name), super);
709 }
710 
711 
712 /*!
713  * Defines a class under the namespace of \a outer.
714  * \param outer  a class which contains the new class.
715  * \param id     name of the new class
716  * \param super  a class from which the new class will derive.
717  *               NULL means \c Object class.
718  * \return the created class
719  * \throw TypeError if the constant name \a name is already taken but
720  *                  the constant is not a \c Class.
721  * \throw TypeError if the class is already defined but the class can not
722  *                  be reopened because its superclass is not \a super.
723  * \post top-level constant named \a name refers the returned class.
724  *
725  * \note if a class named \a name is already defined and its superclass is
726  *       \a super, the function just returns the defined class.
727  */
728 VALUE
rb_define_class_id_under(VALUE outer,ID id,VALUE super)729 rb_define_class_id_under(VALUE outer, ID id, VALUE super)
730 {
731     VALUE klass;
732 
733     if (rb_const_defined_at(outer, id)) {
734 	klass = rb_const_get_at(outer, id);
735 	if (!RB_TYPE_P(klass, T_CLASS)) {
736 	    rb_raise(rb_eTypeError, "%"PRIsVALUE"::%"PRIsVALUE" is not a class"
737 		     " (%"PRIsVALUE")",
738 		     outer, rb_id2str(id), rb_obj_class(klass));
739 	}
740 	if (rb_class_real(RCLASS_SUPER(klass)) != super) {
741 	    rb_raise(rb_eTypeError, "superclass mismatch for class "
742 		     "%"PRIsVALUE"::%"PRIsVALUE""
743 		     " (%"PRIsVALUE" is given but was %"PRIsVALUE")",
744 		     outer, rb_id2str(id), RCLASS_SUPER(klass), super);
745 	}
746 	return klass;
747     }
748     if (!super) {
749 	rb_raise(rb_eArgError, "no super class for `%"PRIsVALUE"::%"PRIsVALUE"'",
750 		 rb_class_path(outer), rb_id2str(id));
751     }
752     klass = rb_define_class_id(id, super);
753     rb_set_class_path_string(klass, outer, rb_id2str(id));
754     rb_const_set(outer, id, klass);
755     rb_class_inherited(super, klass);
756     rb_gc_register_mark_object(klass);
757 
758     return klass;
759 }
760 
761 VALUE
rb_module_new(void)762 rb_module_new(void)
763 {
764     VALUE mdl = class_alloc(T_MODULE, rb_cModule);
765     RCLASS_M_TBL_INIT(mdl);
766     return (VALUE)mdl;
767 }
768 
769 VALUE
rb_define_module_id(ID id)770 rb_define_module_id(ID id)
771 {
772     VALUE mdl;
773 
774     mdl = rb_module_new();
775     rb_name_class(mdl, id);
776 
777     return mdl;
778 }
779 
780 VALUE
rb_define_module(const char * name)781 rb_define_module(const char *name)
782 {
783     VALUE module;
784     ID id;
785 
786     id = rb_intern(name);
787     if (rb_const_defined(rb_cObject, id)) {
788 	module = rb_const_get(rb_cObject, id);
789 	if (!RB_TYPE_P(module, T_MODULE)) {
790 	    rb_raise(rb_eTypeError, "%s is not a module (%"PRIsVALUE")",
791 		     name, rb_obj_class(module));
792 	}
793 	return module;
794     }
795     module = rb_define_module_id(id);
796     rb_vm_add_root_module(id, module);
797     rb_const_set(rb_cObject, id, module);
798 
799     return module;
800 }
801 
802 VALUE
rb_define_module_under(VALUE outer,const char * name)803 rb_define_module_under(VALUE outer, const char *name)
804 {
805     return rb_define_module_id_under(outer, rb_intern(name));
806 }
807 
808 VALUE
rb_define_module_id_under(VALUE outer,ID id)809 rb_define_module_id_under(VALUE outer, ID id)
810 {
811     VALUE module;
812 
813     if (rb_const_defined_at(outer, id)) {
814 	module = rb_const_get_at(outer, id);
815 	if (!RB_TYPE_P(module, T_MODULE)) {
816 	    rb_raise(rb_eTypeError, "%"PRIsVALUE"::%"PRIsVALUE" is not a module"
817 		     " (%"PRIsVALUE")",
818 		     outer, rb_id2str(id), rb_obj_class(module));
819 	}
820 	return module;
821     }
822     module = rb_define_module_id(id);
823     rb_const_set(outer, id, module);
824     rb_set_class_path_string(module, outer, rb_id2str(id));
825     rb_gc_register_mark_object(module);
826 
827     return module;
828 }
829 
830 VALUE
rb_include_class_new(VALUE module,VALUE super)831 rb_include_class_new(VALUE module, VALUE super)
832 {
833     VALUE klass = class_alloc(T_ICLASS, rb_cClass);
834 
835     if (BUILTIN_TYPE(module) == T_ICLASS) {
836 	module = RBASIC(module)->klass;
837     }
838     if (!RCLASS_IV_TBL(module)) {
839 	RCLASS_IV_TBL(module) = st_init_numtable();
840     }
841     if (!RCLASS_CONST_TBL(module)) {
842 	RCLASS_CONST_TBL(module) = rb_id_table_create(0);
843     }
844     RCLASS_IV_TBL(klass) = RCLASS_IV_TBL(module);
845     RCLASS_CONST_TBL(klass) = RCLASS_CONST_TBL(module);
846 
847     RCLASS_M_TBL(OBJ_WB_UNPROTECT(klass)) =
848       RCLASS_M_TBL(OBJ_WB_UNPROTECT(RCLASS_ORIGIN(module))); /* TODO: unprotected? */
849 
850     RCLASS_SET_SUPER(klass, super);
851     if (RB_TYPE_P(module, T_ICLASS)) {
852 	RBASIC_SET_CLASS(klass, RBASIC(module)->klass);
853     }
854     else {
855 	RBASIC_SET_CLASS(klass, module);
856     }
857     OBJ_INFECT(klass, module);
858     OBJ_INFECT(klass, super);
859 
860     return (VALUE)klass;
861 }
862 
863 static int include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super);
864 
865 static void
ensure_includable(VALUE klass,VALUE module)866 ensure_includable(VALUE klass, VALUE module)
867 {
868     rb_class_modify_check(klass);
869     Check_Type(module, T_MODULE);
870     if (!NIL_P(rb_refinement_module_get_refined_class(module))) {
871 	rb_raise(rb_eArgError, "refinement module is not allowed");
872     }
873     OBJ_INFECT(klass, module);
874 }
875 
876 void
rb_include_module(VALUE klass,VALUE module)877 rb_include_module(VALUE klass, VALUE module)
878 {
879     int changed = 0;
880 
881     ensure_includable(klass, module);
882 
883     changed = include_modules_at(klass, RCLASS_ORIGIN(klass), module, TRUE);
884     if (changed < 0)
885 	rb_raise(rb_eArgError, "cyclic include detected");
886 }
887 
888 static enum rb_id_table_iterator_result
add_refined_method_entry_i(ID key,VALUE value,void * data)889 add_refined_method_entry_i(ID key, VALUE value, void *data)
890 {
891     rb_add_refined_method_entry((VALUE)data, key);
892     return ID_TABLE_CONTINUE;
893 }
894 
895 static int
include_modules_at(const VALUE klass,VALUE c,VALUE module,int search_super)896 include_modules_at(const VALUE klass, VALUE c, VALUE module, int search_super)
897 {
898     VALUE p, iclass;
899     int method_changed = 0, constant_changed = 0;
900     struct rb_id_table *const klass_m_tbl = RCLASS_M_TBL(RCLASS_ORIGIN(klass));
901 
902     while (module) {
903 	int superclass_seen = FALSE;
904 	struct rb_id_table *tbl;
905 
906 	if (RCLASS_ORIGIN(module) != module)
907 	    goto skip;
908 	if (klass_m_tbl && klass_m_tbl == RCLASS_M_TBL(module))
909 	    return -1;
910 	/* ignore if the module included already in superclasses */
911 	for (p = RCLASS_SUPER(klass); p; p = RCLASS_SUPER(p)) {
912 	    int type = BUILTIN_TYPE(p);
913 	    if (type == T_ICLASS) {
914 		if (RCLASS_M_TBL(p) == RCLASS_M_TBL(module)) {
915 		    if (!superclass_seen) {
916 			c = p;  /* move insertion point */
917 		    }
918 		    goto skip;
919 		}
920 	    }
921 	    else if (type == T_CLASS) {
922 		if (!search_super) break;
923 		superclass_seen = TRUE;
924 	    }
925 	}
926 	iclass = rb_include_class_new(module, RCLASS_SUPER(c));
927 	c = RCLASS_SET_SUPER(c, iclass);
928 
929 	{
930 	    VALUE m = module;
931 	    if (BUILTIN_TYPE(m) == T_ICLASS) m = RBASIC(m)->klass;
932 	    rb_module_add_to_subclasses_list(m, iclass);
933 	}
934 
935 	if (FL_TEST(klass, RMODULE_IS_REFINEMENT)) {
936 	    VALUE refined_class =
937 		rb_refinement_module_get_refined_class(klass);
938 
939 	    rb_id_table_foreach(RMODULE_M_TBL(module), add_refined_method_entry_i, (void *)refined_class);
940 	    FL_SET(c, RMODULE_INCLUDED_INTO_REFINEMENT);
941 	}
942 
943 	tbl = RMODULE_M_TBL(module);
944 	if (tbl && rb_id_table_size(tbl)) method_changed = 1;
945 
946 	tbl = RMODULE_CONST_TBL(module);
947 	if (tbl && rb_id_table_size(tbl)) constant_changed = 1;
948       skip:
949 	module = RCLASS_SUPER(module);
950     }
951 
952     if (method_changed) rb_clear_method_cache_by_class(klass);
953     if (constant_changed) rb_clear_constant_cache();
954 
955     return method_changed;
956 }
957 
958 static enum rb_id_table_iterator_result
move_refined_method(ID key,VALUE value,void * data)959 move_refined_method(ID key, VALUE value, void *data)
960 {
961     rb_method_entry_t *me = (rb_method_entry_t *) value;
962     VALUE klass = (VALUE)data;
963     struct rb_id_table *tbl = RCLASS_M_TBL(klass);
964 
965     if (me->def->type == VM_METHOD_TYPE_REFINED) {
966 	if (me->def->body.refined.orig_me) {
967 	    const rb_method_entry_t *orig_me = me->def->body.refined.orig_me, *new_me;
968 	    RB_OBJ_WRITE(me, &me->def->body.refined.orig_me, NULL);
969 	    new_me = rb_method_entry_clone(me);
970 	    rb_id_table_insert(tbl, key, (VALUE)new_me);
971 	    RB_OBJ_WRITTEN(klass, Qundef, new_me);
972 	    rb_method_entry_copy(me, orig_me);
973 	    return ID_TABLE_CONTINUE;
974 	}
975 	else {
976 	    rb_id_table_insert(tbl, key, (VALUE)me);
977 	    return ID_TABLE_DELETE;
978 	}
979     }
980     else {
981 	return ID_TABLE_CONTINUE;
982     }
983 }
984 
985 void
rb_prepend_module(VALUE klass,VALUE module)986 rb_prepend_module(VALUE klass, VALUE module)
987 {
988     VALUE origin;
989     int changed = 0;
990 
991     ensure_includable(klass, module);
992 
993     origin = RCLASS_ORIGIN(klass);
994     if (origin == klass) {
995 	origin = class_alloc(T_ICLASS, klass);
996 	OBJ_WB_UNPROTECT(origin); /* TODO: conservative shading. Need more survey. */
997 	RCLASS_SET_SUPER(origin, RCLASS_SUPER(klass));
998 	RCLASS_SET_SUPER(klass, origin);
999 	RCLASS_SET_ORIGIN(klass, origin);
1000 	RCLASS_M_TBL(origin) = RCLASS_M_TBL(klass);
1001 	RCLASS_M_TBL_INIT(klass);
1002 	rb_id_table_foreach(RCLASS_M_TBL(origin), move_refined_method, (void *)klass);
1003     }
1004     changed = include_modules_at(klass, klass, module, FALSE);
1005     if (changed < 0)
1006 	rb_raise(rb_eArgError, "cyclic prepend detected");
1007     if (changed) {
1008 	rb_vm_check_redefinition_by_prepend(klass);
1009     }
1010 }
1011 
1012 /*
1013  *  call-seq:
1014  *     mod.included_modules -> array
1015  *
1016  *  Returns the list of modules included in <i>mod</i>.
1017  *
1018  *     module Mixin
1019  *     end
1020  *
1021  *     module Outer
1022  *       include Mixin
1023  *     end
1024  *
1025  *     Mixin.included_modules   #=> []
1026  *     Outer.included_modules   #=> [Mixin]
1027  */
1028 
1029 VALUE
rb_mod_included_modules(VALUE mod)1030 rb_mod_included_modules(VALUE mod)
1031 {
1032     VALUE ary = rb_ary_new();
1033     VALUE p;
1034     VALUE origin = RCLASS_ORIGIN(mod);
1035 
1036     for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
1037 	if (p != origin && BUILTIN_TYPE(p) == T_ICLASS) {
1038 	    VALUE m = RBASIC(p)->klass;
1039 	    if (RB_TYPE_P(m, T_MODULE))
1040 		rb_ary_push(ary, m);
1041 	}
1042     }
1043     return ary;
1044 }
1045 
1046 /*
1047  *  call-seq:
1048  *     mod.include?(module)    -> true or false
1049  *
1050  *  Returns <code>true</code> if <i>module</i> is included in
1051  *  <i>mod</i> or one of <i>mod</i>'s ancestors.
1052  *
1053  *     module A
1054  *     end
1055  *     class B
1056  *       include A
1057  *     end
1058  *     class C < B
1059  *     end
1060  *     B.include?(A)   #=> true
1061  *     C.include?(A)   #=> true
1062  *     A.include?(A)   #=> false
1063  */
1064 
1065 VALUE
rb_mod_include_p(VALUE mod,VALUE mod2)1066 rb_mod_include_p(VALUE mod, VALUE mod2)
1067 {
1068     VALUE p;
1069 
1070     Check_Type(mod2, T_MODULE);
1071     for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
1072 	if (BUILTIN_TYPE(p) == T_ICLASS) {
1073 	    if (RBASIC(p)->klass == mod2) return Qtrue;
1074 	}
1075     }
1076     return Qfalse;
1077 }
1078 
1079 /*
1080  *  call-seq:
1081  *     mod.ancestors -> array
1082  *
1083  *  Returns a list of modules included/prepended in <i>mod</i>
1084  *  (including <i>mod</i> itself).
1085  *
1086  *     module Mod
1087  *       include Math
1088  *       include Comparable
1089  *       prepend Enumerable
1090  *     end
1091  *
1092  *     Mod.ancestors        #=> [Enumerable, Mod, Comparable, Math]
1093  *     Math.ancestors       #=> [Math]
1094  *     Enumerable.ancestors #=> [Enumerable]
1095  */
1096 
1097 VALUE
rb_mod_ancestors(VALUE mod)1098 rb_mod_ancestors(VALUE mod)
1099 {
1100     VALUE p, ary = rb_ary_new();
1101 
1102     for (p = mod; p; p = RCLASS_SUPER(p)) {
1103 	if (BUILTIN_TYPE(p) == T_ICLASS) {
1104 	    rb_ary_push(ary, RBASIC(p)->klass);
1105 	}
1106 	else if (p == RCLASS_ORIGIN(p)) {
1107 	    rb_ary_push(ary, p);
1108 	}
1109     }
1110     return ary;
1111 }
1112 
1113 static void
ins_methods_push(st_data_t name,st_data_t ary)1114 ins_methods_push(st_data_t name, st_data_t ary)
1115 {
1116     rb_ary_push((VALUE)ary, ID2SYM((ID)name));
1117 }
1118 
1119 static int
ins_methods_i(st_data_t name,st_data_t type,st_data_t ary)1120 ins_methods_i(st_data_t name, st_data_t type, st_data_t ary)
1121 {
1122     switch ((rb_method_visibility_t)type) {
1123       case METHOD_VISI_UNDEF:
1124       case METHOD_VISI_PRIVATE:
1125 	break;
1126       default: /* everything but private */
1127 	ins_methods_push(name, ary);
1128 	break;
1129     }
1130     return ST_CONTINUE;
1131 }
1132 
1133 static int
ins_methods_prot_i(st_data_t name,st_data_t type,st_data_t ary)1134 ins_methods_prot_i(st_data_t name, st_data_t type, st_data_t ary)
1135 {
1136     if ((rb_method_visibility_t)type == METHOD_VISI_PROTECTED) {
1137 	ins_methods_push(name, ary);
1138     }
1139     return ST_CONTINUE;
1140 }
1141 
1142 static int
ins_methods_priv_i(st_data_t name,st_data_t type,st_data_t ary)1143 ins_methods_priv_i(st_data_t name, st_data_t type, st_data_t ary)
1144 {
1145     if ((rb_method_visibility_t)type == METHOD_VISI_PRIVATE) {
1146 	ins_methods_push(name, ary);
1147     }
1148     return ST_CONTINUE;
1149 }
1150 
1151 static int
ins_methods_pub_i(st_data_t name,st_data_t type,st_data_t ary)1152 ins_methods_pub_i(st_data_t name, st_data_t type, st_data_t ary)
1153 {
1154     if ((rb_method_visibility_t)type == METHOD_VISI_PUBLIC) {
1155 	ins_methods_push(name, ary);
1156     }
1157     return ST_CONTINUE;
1158 }
1159 
1160 struct method_entry_arg {
1161     st_table *list;
1162     int recur;
1163 };
1164 
1165 static enum rb_id_table_iterator_result
method_entry_i(ID key,VALUE value,void * data)1166 method_entry_i(ID key, VALUE value, void *data)
1167 {
1168     const rb_method_entry_t *me = (const rb_method_entry_t *)value;
1169     struct method_entry_arg *arg = (struct method_entry_arg *)data;
1170     rb_method_visibility_t type;
1171 
1172     if (me->def->type == VM_METHOD_TYPE_REFINED) {
1173 	VALUE owner = me->owner;
1174 	me = rb_resolve_refined_method(Qnil, me);
1175 	if (!me) return ID_TABLE_CONTINUE;
1176 	if (!arg->recur && me->owner != owner) return ID_TABLE_CONTINUE;
1177     }
1178     if (!st_lookup(arg->list, key, 0)) {
1179 	if (UNDEFINED_METHOD_ENTRY_P(me)) {
1180 	    type = METHOD_VISI_UNDEF; /* none */
1181 	}
1182 	else {
1183 	    type = METHOD_ENTRY_VISI(me);
1184 	}
1185 	st_add_direct(arg->list, key, (st_data_t)type);
1186     }
1187     return ID_TABLE_CONTINUE;
1188 }
1189 
1190 static VALUE
class_instance_method_list(int argc,const VALUE * argv,VALUE mod,int obj,int (* func)(st_data_t,st_data_t,st_data_t))1191 class_instance_method_list(int argc, const VALUE *argv, VALUE mod, int obj, int (*func) (st_data_t, st_data_t, st_data_t))
1192 {
1193     VALUE ary;
1194     int recur = TRUE, prepended = 0;
1195     struct method_entry_arg me_arg;
1196 
1197     if (rb_check_arity(argc, 0, 1)) recur = RTEST(argv[0]);
1198 
1199     if (!recur && RCLASS_ORIGIN(mod) != mod) {
1200 	mod = RCLASS_ORIGIN(mod);
1201 	prepended = 1;
1202     }
1203 
1204     me_arg.list = st_init_numtable();
1205     me_arg.recur = recur;
1206     for (; mod; mod = RCLASS_SUPER(mod)) {
1207 	if (RCLASS_M_TBL(mod)) rb_id_table_foreach(RCLASS_M_TBL(mod), method_entry_i, &me_arg);
1208 	if (BUILTIN_TYPE(mod) == T_ICLASS && !prepended) continue;
1209 	if (obj && FL_TEST(mod, FL_SINGLETON)) continue;
1210 	if (!recur) break;
1211     }
1212     ary = rb_ary_new();
1213     st_foreach(me_arg.list, func, ary);
1214     st_free_table(me_arg.list);
1215 
1216     return ary;
1217 }
1218 
1219 /*
1220  *  call-seq:
1221  *     mod.instance_methods(include_super=true)   -> array
1222  *
1223  *  Returns an array containing the names of the public and protected instance
1224  *  methods in the receiver. For a module, these are the public and protected methods;
1225  *  for a class, they are the instance (not singleton) methods. If the optional
1226  *  parameter is <code>false</code>, the methods of any ancestors are not included.
1227  *
1228  *     module A
1229  *       def method1()  end
1230  *     end
1231  *     class B
1232  *       include A
1233  *       def method2()  end
1234  *     end
1235  *     class C < B
1236  *       def method3()  end
1237  *     end
1238  *
1239  *     A.instance_methods(false)                   #=> [:method1]
1240  *     B.instance_methods(false)                   #=> [:method2]
1241  *     B.instance_methods(true).include?(:method1) #=> true
1242  *     C.instance_methods(false)                   #=> [:method3]
1243  *     C.instance_methods.include?(:method2)       #=> true
1244  */
1245 
1246 VALUE
rb_class_instance_methods(int argc,const VALUE * argv,VALUE mod)1247 rb_class_instance_methods(int argc, const VALUE *argv, VALUE mod)
1248 {
1249     return class_instance_method_list(argc, argv, mod, 0, ins_methods_i);
1250 }
1251 
1252 /*
1253  *  call-seq:
1254  *     mod.protected_instance_methods(include_super=true)   -> array
1255  *
1256  *  Returns a list of the protected instance methods defined in
1257  *  <i>mod</i>. If the optional parameter is <code>false</code>, the
1258  *  methods of any ancestors are not included.
1259  */
1260 
1261 VALUE
rb_class_protected_instance_methods(int argc,const VALUE * argv,VALUE mod)1262 rb_class_protected_instance_methods(int argc, const VALUE *argv, VALUE mod)
1263 {
1264     return class_instance_method_list(argc, argv, mod, 0, ins_methods_prot_i);
1265 }
1266 
1267 /*
1268  *  call-seq:
1269  *     mod.private_instance_methods(include_super=true)    -> array
1270  *
1271  *  Returns a list of the private instance methods defined in
1272  *  <i>mod</i>. If the optional parameter is <code>false</code>, the
1273  *  methods of any ancestors are not included.
1274  *
1275  *     module Mod
1276  *       def method1()  end
1277  *       private :method1
1278  *       def method2()  end
1279  *     end
1280  *     Mod.instance_methods           #=> [:method2]
1281  *     Mod.private_instance_methods   #=> [:method1]
1282  */
1283 
1284 VALUE
rb_class_private_instance_methods(int argc,const VALUE * argv,VALUE mod)1285 rb_class_private_instance_methods(int argc, const VALUE *argv, VALUE mod)
1286 {
1287     return class_instance_method_list(argc, argv, mod, 0, ins_methods_priv_i);
1288 }
1289 
1290 /*
1291  *  call-seq:
1292  *     mod.public_instance_methods(include_super=true)   -> array
1293  *
1294  *  Returns a list of the public instance methods defined in <i>mod</i>.
1295  *  If the optional parameter is <code>false</code>, the methods of
1296  *  any ancestors are not included.
1297  */
1298 
1299 VALUE
rb_class_public_instance_methods(int argc,const VALUE * argv,VALUE mod)1300 rb_class_public_instance_methods(int argc, const VALUE *argv, VALUE mod)
1301 {
1302     return class_instance_method_list(argc, argv, mod, 0, ins_methods_pub_i);
1303 }
1304 
1305 /*
1306  *  call-seq:
1307  *     obj.methods(regular=true)    -> array
1308  *
1309  *  Returns a list of the names of public and protected methods of
1310  *  <i>obj</i>. This will include all the methods accessible in
1311  *  <i>obj</i>'s ancestors.
1312  *  If the optional parameter is <code>false</code>, it
1313  *  returns an array of <i>obj<i>'s public and protected singleton methods,
1314  *  the array will not include methods in modules included in <i>obj</i>.
1315  *
1316  *     class Klass
1317  *       def klass_method()
1318  *       end
1319  *     end
1320  *     k = Klass.new
1321  *     k.methods[0..9]    #=> [:klass_method, :nil?, :===,
1322  *                        #    :==~, :!, :eql?
1323  *                        #    :hash, :<=>, :class, :singleton_class]
1324  *     k.methods.length   #=> 56
1325  *
1326  *     k.methods(false)   #=> []
1327  *     def k.singleton_method; end
1328  *     k.methods(false)   #=> [:singleton_method]
1329  *
1330  *     module M123; def m123; end end
1331  *     k.extend M123
1332  *     k.methods(false)   #=> [:singleton_method]
1333  */
1334 
1335 VALUE
rb_obj_methods(int argc,const VALUE * argv,VALUE obj)1336 rb_obj_methods(int argc, const VALUE *argv, VALUE obj)
1337 {
1338     rb_check_arity(argc, 0, 1);
1339     if (argc > 0 && !RTEST(argv[0])) {
1340 	return rb_obj_singleton_methods(argc, argv, obj);
1341     }
1342     return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_i);
1343 }
1344 
1345 /*
1346  *  call-seq:
1347  *     obj.protected_methods(all=true)   -> array
1348  *
1349  *  Returns the list of protected methods accessible to <i>obj</i>. If
1350  *  the <i>all</i> parameter is set to <code>false</code>, only those methods
1351  *  in the receiver will be listed.
1352  */
1353 
1354 VALUE
rb_obj_protected_methods(int argc,const VALUE * argv,VALUE obj)1355 rb_obj_protected_methods(int argc, const VALUE *argv, VALUE obj)
1356 {
1357     return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_prot_i);
1358 }
1359 
1360 /*
1361  *  call-seq:
1362  *     obj.private_methods(all=true)   -> array
1363  *
1364  *  Returns the list of private methods accessible to <i>obj</i>. If
1365  *  the <i>all</i> parameter is set to <code>false</code>, only those methods
1366  *  in the receiver will be listed.
1367  */
1368 
1369 VALUE
rb_obj_private_methods(int argc,const VALUE * argv,VALUE obj)1370 rb_obj_private_methods(int argc, const VALUE *argv, VALUE obj)
1371 {
1372     return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_priv_i);
1373 }
1374 
1375 /*
1376  *  call-seq:
1377  *     obj.public_methods(all=true)   -> array
1378  *
1379  *  Returns the list of public methods accessible to <i>obj</i>. If
1380  *  the <i>all</i> parameter is set to <code>false</code>, only those methods
1381  *  in the receiver will be listed.
1382  */
1383 
1384 VALUE
rb_obj_public_methods(int argc,const VALUE * argv,VALUE obj)1385 rb_obj_public_methods(int argc, const VALUE *argv, VALUE obj)
1386 {
1387     return class_instance_method_list(argc, argv, CLASS_OF(obj), 1, ins_methods_pub_i);
1388 }
1389 
1390 /*
1391  *  call-seq:
1392  *     obj.singleton_methods(all=true)    -> array
1393  *
1394  *  Returns an array of the names of singleton methods for <i>obj</i>.
1395  *  If the optional <i>all</i> parameter is true, the list will include
1396  *  methods in modules included in <i>obj</i>.
1397  *  Only public and protected singleton methods are returned.
1398  *
1399  *     module Other
1400  *       def three() end
1401  *     end
1402  *
1403  *     class Single
1404  *       def Single.four() end
1405  *     end
1406  *
1407  *     a = Single.new
1408  *
1409  *     def a.one()
1410  *     end
1411  *
1412  *     class << a
1413  *       include Other
1414  *       def two()
1415  *       end
1416  *     end
1417  *
1418  *     Single.singleton_methods    #=> [:four]
1419  *     a.singleton_methods(false)  #=> [:two, :one]
1420  *     a.singleton_methods         #=> [:two, :one, :three]
1421  */
1422 
1423 VALUE
rb_obj_singleton_methods(int argc,const VALUE * argv,VALUE obj)1424 rb_obj_singleton_methods(int argc, const VALUE *argv, VALUE obj)
1425 {
1426     VALUE ary, klass, origin;
1427     struct method_entry_arg me_arg;
1428     struct rb_id_table *mtbl;
1429     int recur = TRUE;
1430 
1431     if (rb_check_arity(argc, 0, 1)) recur = RTEST(argv[0]);
1432     klass = CLASS_OF(obj);
1433     origin = RCLASS_ORIGIN(klass);
1434     me_arg.list = st_init_numtable();
1435     me_arg.recur = recur;
1436     if (klass && FL_TEST(klass, FL_SINGLETON)) {
1437 	if ((mtbl = RCLASS_M_TBL(origin)) != 0) rb_id_table_foreach(mtbl, method_entry_i, &me_arg);
1438 	klass = RCLASS_SUPER(klass);
1439     }
1440     if (recur) {
1441 	while (klass && (FL_TEST(klass, FL_SINGLETON) || RB_TYPE_P(klass, T_ICLASS))) {
1442 	    if (klass != origin && (mtbl = RCLASS_M_TBL(klass)) != 0) rb_id_table_foreach(mtbl, method_entry_i, &me_arg);
1443 	    klass = RCLASS_SUPER(klass);
1444 	}
1445     }
1446     ary = rb_ary_new();
1447     st_foreach(me_arg.list, ins_methods_i, ary);
1448     st_free_table(me_arg.list);
1449 
1450     return ary;
1451 }
1452 
1453 /*!
1454  * \}
1455  */
1456 /*!
1457  * \defgroup defmethod Defining methods
1458  * There are some APIs to define a method from C.
1459  * These API takes a C function as a method body.
1460  *
1461  * \par Method body functions
1462  * Method body functions must return a VALUE and
1463  * can be one of the following form:
1464  * <dl>
1465  * <dt>Fixed number of parameters</dt>
1466  * <dd>
1467  *     This form is a normal C function, excepting it takes
1468  *     a receiver object as the first argument.
1469  *
1470  *     \code
1471  *     static VALUE my_method(VALUE self, VALUE x, VALUE y);
1472  *     \endcode
1473  * </dd>
1474  * <dt>argc and argv style</dt>
1475  * <dd>
1476  *     This form takes three parameters: \a argc, \a argv and \a self.
1477  *     \a self is the receiver. \a argc is the number of arguments.
1478  *     \a argv is a pointer to an array of the arguments.
1479  *
1480  *     \code
1481  *     static VALUE my_method(int argc, VALUE *argv, VALUE self);
1482  *     \endcode
1483  * </dd>
1484  * <dt>Ruby array style</dt>
1485  * <dd>
1486  *     This form takes two parameters: self and args.
1487  *     \a self is the receiver. \a args is an Array object which
1488  *     contains the arguments.
1489  *
1490  *     \code
1491  *     static VALUE my_method(VALUE self, VALUE args);
1492  *     \endcode
1493  * </dd>
1494  *
1495  * \par Number of parameters
1496  * Method defining APIs takes the number of parameters which the
1497  * method will takes. This number is called \a argc.
1498  * \a argc can be:
1499  * <dl>
1500  * <dt>zero or positive number</dt>
1501  * <dd>This means the method body function takes a fixed number of parameters</dd>
1502  * <dt>-1</dt>
1503  * <dd>This means the method body function is "argc and argv" style.</dd>
1504  * <dt>-2</dt>
1505  * <dd>This means the method body function is "self and args" style.</dd>
1506  * </dl>
1507  * \{
1508  */
1509 
1510 void
rb_define_method_id(VALUE klass,ID mid,VALUE (* func)(ANYARGS),int argc)1511 rb_define_method_id(VALUE klass, ID mid, VALUE (*func)(ANYARGS), int argc)
1512 {
1513     rb_add_method_cfunc(klass, mid, func, argc, METHOD_VISI_PUBLIC);
1514 }
1515 
1516 void
rb_define_method(VALUE klass,const char * name,VALUE (* func)(ANYARGS),int argc)1517 rb_define_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc)
1518 {
1519     rb_add_method_cfunc(klass, rb_intern(name), func, argc, METHOD_VISI_PUBLIC);
1520 }
1521 
1522 void
rb_define_protected_method(VALUE klass,const char * name,VALUE (* func)(ANYARGS),int argc)1523 rb_define_protected_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc)
1524 {
1525     rb_add_method_cfunc(klass, rb_intern(name), func, argc, METHOD_VISI_PROTECTED);
1526 }
1527 
1528 void
rb_define_private_method(VALUE klass,const char * name,VALUE (* func)(ANYARGS),int argc)1529 rb_define_private_method(VALUE klass, const char *name, VALUE (*func)(ANYARGS), int argc)
1530 {
1531     rb_add_method_cfunc(klass, rb_intern(name), func, argc, METHOD_VISI_PRIVATE);
1532 }
1533 
1534 void
rb_undef_method(VALUE klass,const char * name)1535 rb_undef_method(VALUE klass, const char *name)
1536 {
1537     rb_add_method(klass, rb_intern(name), VM_METHOD_TYPE_UNDEF, 0, METHOD_VISI_UNDEF);
1538 }
1539 
1540 static enum rb_id_table_iterator_result
undef_method_i(ID name,VALUE value,void * data)1541 undef_method_i(ID name, VALUE value, void *data)
1542 {
1543     VALUE klass = (VALUE)data;
1544     rb_add_method(klass, name, VM_METHOD_TYPE_UNDEF, 0, METHOD_VISI_UNDEF);
1545     return ID_TABLE_CONTINUE;
1546 }
1547 
1548 void
rb_undef_methods_from(VALUE klass,VALUE super)1549 rb_undef_methods_from(VALUE klass, VALUE super)
1550 {
1551     struct rb_id_table *mtbl = RCLASS_M_TBL(super);
1552     if (mtbl) {
1553 	rb_id_table_foreach(mtbl, undef_method_i, (void *)klass);
1554     }
1555 }
1556 
1557 /*!
1558  * \}
1559  */
1560 /*!
1561  * \addtogroup class
1562  * \{
1563  */
1564 
1565 #define SPECIAL_SINGLETON(x,c) do {\
1566     if (obj == (x)) {\
1567 	return (c);\
1568     }\
1569 } while (0)
1570 
1571 static inline VALUE
special_singleton_class_of(VALUE obj)1572 special_singleton_class_of(VALUE obj)
1573 {
1574     SPECIAL_SINGLETON(Qnil, rb_cNilClass);
1575     SPECIAL_SINGLETON(Qfalse, rb_cFalseClass);
1576     SPECIAL_SINGLETON(Qtrue, rb_cTrueClass);
1577     return Qnil;
1578 }
1579 
1580 VALUE
rb_special_singleton_class(VALUE obj)1581 rb_special_singleton_class(VALUE obj)
1582 {
1583     return special_singleton_class_of(obj);
1584 }
1585 
1586 /*!
1587  * \internal
1588  * Returns the singleton class of \a obj. Creates it if necessary.
1589  *
1590  * \note DO NOT expose the returned singleton class to
1591  *       outside of class.c.
1592  *       Use \ref rb_singleton_class instead for
1593  *       consistency of the metaclass hierarchy.
1594  */
1595 static VALUE
singleton_class_of(VALUE obj)1596 singleton_class_of(VALUE obj)
1597 {
1598     VALUE klass;
1599 
1600     if (FIXNUM_P(obj) || FLONUM_P(obj) || STATIC_SYM_P(obj)) {
1601       no_singleton:
1602 	rb_raise(rb_eTypeError, "can't define singleton");
1603     }
1604     if (SPECIAL_CONST_P(obj)) {
1605 	klass = special_singleton_class_of(obj);
1606 	if (NIL_P(klass))
1607 	    rb_bug("unknown immediate %p", (void *)obj);
1608 	return klass;
1609     }
1610     else {
1611 	switch (BUILTIN_TYPE(obj)) {
1612 	  case T_FLOAT: case T_BIGNUM: case T_SYMBOL:
1613 	    goto no_singleton;
1614 	  case T_STRING:
1615 	    if (FL_TEST_RAW(obj, RSTRING_FSTR)) goto no_singleton;
1616 	    break;
1617 	}
1618     }
1619 
1620     klass = RBASIC(obj)->klass;
1621     if (!(FL_TEST(klass, FL_SINGLETON) &&
1622 	  rb_ivar_get(klass, id_attached) == obj)) {
1623 	rb_serial_t serial = RCLASS_SERIAL(klass);
1624 	klass = rb_make_metaclass(obj, klass);
1625 	RCLASS_SERIAL(klass) = serial;
1626     }
1627 
1628     if (OBJ_TAINTED(obj)) {
1629 	OBJ_TAINT(klass);
1630     }
1631     else {
1632 	FL_UNSET(klass, FL_TAINT);
1633     }
1634     RB_FL_SET_RAW(klass, RB_OBJ_FROZEN_RAW(obj));
1635 
1636     return klass;
1637 }
1638 
1639 void
rb_freeze_singleton_class(VALUE x)1640 rb_freeze_singleton_class(VALUE x)
1641 {
1642     /* should not propagate to meta-meta-class, and so on */
1643     if (!(RBASIC(x)->flags & FL_SINGLETON)) {
1644 	VALUE klass = RBASIC_CLASS(x);
1645 	if (klass && (klass = RCLASS_ORIGIN(klass)) != 0 &&
1646 	    FL_TEST(klass, (FL_SINGLETON|FL_FREEZE)) == FL_SINGLETON) {
1647 	    OBJ_FREEZE_RAW(klass);
1648 	}
1649     }
1650 }
1651 
1652 /*!
1653  * Returns the singleton class of \a obj, or nil if obj is not a
1654  * singleton object.
1655  *
1656  * \param obj an arbitrary object.
1657  * \return the singleton class or nil.
1658  */
1659 VALUE
rb_singleton_class_get(VALUE obj)1660 rb_singleton_class_get(VALUE obj)
1661 {
1662     VALUE klass;
1663 
1664     if (SPECIAL_CONST_P(obj)) {
1665 	return rb_special_singleton_class(obj);
1666     }
1667     klass = RBASIC(obj)->klass;
1668     if (!FL_TEST(klass, FL_SINGLETON)) return Qnil;
1669     if (rb_ivar_get(klass, id_attached) != obj) return Qnil;
1670     return klass;
1671 }
1672 
1673 /*!
1674  * Returns the singleton class of \a obj. Creates it if necessary.
1675  *
1676  * \param obj an arbitrary object.
1677  * \throw TypeError if \a obj is a Integer or a Symbol.
1678  * \return the singleton class.
1679  *
1680  * \post \a obj has its own singleton class.
1681  * \post if \a obj is a class,
1682  *       the returned singleton class also has its own
1683  *       singleton class in order to keep consistency of the
1684  *       inheritance structure of metaclasses.
1685  * \note a new singleton class will be created
1686  *       if \a obj does not have it.
1687  * \note the singleton classes for nil, true and false are:
1688  *       NilClass, TrueClass and FalseClass.
1689  */
1690 VALUE
rb_singleton_class(VALUE obj)1691 rb_singleton_class(VALUE obj)
1692 {
1693     VALUE klass = singleton_class_of(obj);
1694 
1695     /* ensures an exposed class belongs to its own eigenclass */
1696     if (RB_TYPE_P(obj, T_CLASS)) (void)ENSURE_EIGENCLASS(klass);
1697 
1698     return klass;
1699 }
1700 
1701 /*!
1702  * \}
1703  */
1704 
1705 /*!
1706  * \addtogroup defmethod
1707  * \{
1708  */
1709 
1710 /*!
1711  * Defines a singleton method for \a obj.
1712  * \param obj    an arbitrary object
1713  * \param name   name of the singleton method
1714  * \param func   the method body
1715  * \param argc   the number of parameters, or -1 or -2. see \ref defmethod.
1716  */
1717 void
rb_define_singleton_method(VALUE obj,const char * name,VALUE (* func)(ANYARGS),int argc)1718 rb_define_singleton_method(VALUE obj, const char *name, VALUE (*func)(ANYARGS), int argc)
1719 {
1720     rb_define_method(singleton_class_of(obj), name, func, argc);
1721 }
1722 
1723 
1724 
1725 /*!
1726  * Defines a module function for \a module.
1727  * \param module  an module or a class.
1728  * \param name    name of the function
1729  * \param func    the method body
1730  * \param argc    the number of parameters, or -1 or -2. see \ref defmethod.
1731  */
1732 void
rb_define_module_function(VALUE module,const char * name,VALUE (* func)(ANYARGS),int argc)1733 rb_define_module_function(VALUE module, const char *name, VALUE (*func)(ANYARGS), int argc)
1734 {
1735     rb_define_private_method(module, name, func, argc);
1736     rb_define_singleton_method(module, name, func, argc);
1737 }
1738 
1739 
1740 /*!
1741  * Defines a global function
1742  * \param name    name of the function
1743  * \param func    the method body
1744  * \param argc    the number of parameters, or -1 or -2. see \ref defmethod.
1745  */
1746 void
rb_define_global_function(const char * name,VALUE (* func)(ANYARGS),int argc)1747 rb_define_global_function(const char *name, VALUE (*func)(ANYARGS), int argc)
1748 {
1749     rb_define_module_function(rb_mKernel, name, func, argc);
1750 }
1751 
1752 
1753 /*!
1754  * Defines an alias of a method.
1755  * \param klass  the class which the original method belongs to
1756  * \param name1  a new name for the method
1757  * \param name2  the original name of the method
1758  */
1759 void
rb_define_alias(VALUE klass,const char * name1,const char * name2)1760 rb_define_alias(VALUE klass, const char *name1, const char *name2)
1761 {
1762     rb_alias(klass, rb_intern(name1), rb_intern(name2));
1763 }
1764 
1765 /*!
1766  * Defines (a) public accessor method(s) for an attribute.
1767  * \param klass  the class which the attribute will belongs to
1768  * \param name   name of the attribute
1769  * \param read   a getter method for the attribute will be defined if \a read is non-zero.
1770  * \param write  a setter method for the attribute will be defined if \a write is non-zero.
1771  */
1772 void
rb_define_attr(VALUE klass,const char * name,int read,int write)1773 rb_define_attr(VALUE klass, const char *name, int read, int write)
1774 {
1775     rb_attr(klass, rb_intern(name), read, write, FALSE);
1776 }
1777 
1778 MJIT_FUNC_EXPORTED VALUE
rb_keyword_error_new(const char * error,VALUE keys)1779 rb_keyword_error_new(const char *error, VALUE keys)
1780 {
1781     long i = 0, len = RARRAY_LEN(keys);
1782     VALUE error_message = rb_sprintf("%s keyword%.*s", error, len > 1, "s");
1783 
1784     if (len > 0) {
1785 	rb_str_cat_cstr(error_message, ": ");
1786 	while (1) {
1787             const VALUE k = RARRAY_AREF(keys, i);
1788 	    Check_Type(k, T_SYMBOL); /* wrong hash is given to rb_get_kwargs */
1789 	    rb_str_append(error_message, rb_sym2str(k));
1790 	    if (++i >= len) break;
1791 	    rb_str_cat_cstr(error_message, ", ");
1792 	}
1793     }
1794 
1795     return rb_exc_new_str(rb_eArgError, error_message);
1796 }
1797 
1798 NORETURN(static void rb_keyword_error(const char *error, VALUE keys));
1799 static void
rb_keyword_error(const char * error,VALUE keys)1800 rb_keyword_error(const char *error, VALUE keys)
1801 {
1802     rb_exc_raise(rb_keyword_error_new(error, keys));
1803 }
1804 
1805 NORETURN(static void unknown_keyword_error(VALUE hash, const ID *table, int keywords));
1806 static void
unknown_keyword_error(VALUE hash,const ID * table,int keywords)1807 unknown_keyword_error(VALUE hash, const ID *table, int keywords)
1808 {
1809     int i;
1810     for (i = 0; i < keywords; i++) {
1811 	st_data_t key = ID2SYM(table[i]);
1812         rb_hash_stlike_delete(hash, &key, NULL);
1813     }
1814     rb_keyword_error("unknown", rb_hash_keys(hash));
1815 }
1816 
1817 
1818 static int
separate_symbol(st_data_t key,st_data_t value,st_data_t arg)1819 separate_symbol(st_data_t key, st_data_t value, st_data_t arg)
1820 {
1821     VALUE *kwdhash = (VALUE *)arg;
1822     if (!SYMBOL_P(key)) kwdhash++;
1823     if (!*kwdhash) *kwdhash = rb_hash_new();
1824     rb_hash_aset(*kwdhash, (VALUE)key, (VALUE)value);
1825     return ST_CONTINUE;
1826 }
1827 
1828 VALUE
rb_extract_keywords(VALUE * orighash)1829 rb_extract_keywords(VALUE *orighash)
1830 {
1831     VALUE parthash[2] = {0, 0};
1832     VALUE hash = *orighash;
1833 
1834     if (RHASH_EMPTY_P(hash)) {
1835 	*orighash = 0;
1836 	return hash;
1837     }
1838     rb_hash_foreach(hash, separate_symbol, (st_data_t)&parthash);
1839     *orighash = parthash[1];
1840     if (parthash[1] && RBASIC_CLASS(hash) != rb_cHash) {
1841 	RBASIC_SET_CLASS(parthash[1], RBASIC_CLASS(hash));
1842     }
1843     return parthash[0];
1844 }
1845 
1846 int
rb_get_kwargs(VALUE keyword_hash,const ID * table,int required,int optional,VALUE * values)1847 rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
1848 {
1849     int i = 0, j;
1850     int rest = 0;
1851     VALUE missing = Qnil;
1852     st_data_t key;
1853 
1854 #define extract_kwarg(keyword, val) \
1855     (key = (st_data_t)(keyword), values ? \
1856      rb_hash_stlike_delete(keyword_hash, &key, (val)) : \
1857      rb_hash_stlike_lookup(keyword_hash, key, (val)))
1858 
1859     if (NIL_P(keyword_hash)) keyword_hash = 0;
1860 
1861     if (optional < 0) {
1862 	rest = 1;
1863 	optional = -1-optional;
1864     }
1865     if (values) {
1866 	for (j = 0; j < required + optional; j++) {
1867 	    values[j] = Qundef;
1868 	}
1869     }
1870     if (required) {
1871 	for (; i < required; i++) {
1872 	    VALUE keyword = ID2SYM(table[i]);
1873 	    if (keyword_hash) {
1874 		st_data_t val;
1875 		if (extract_kwarg(keyword, &val)) {
1876 		    if (values) values[i] = (VALUE)val;
1877 		    continue;
1878 		}
1879 	    }
1880 	    if (NIL_P(missing)) missing = rb_ary_tmp_new(1);
1881 	    rb_ary_push(missing, keyword);
1882 	}
1883 	if (!NIL_P(missing)) {
1884 	    rb_keyword_error("missing", missing);
1885 	}
1886     }
1887     j = i;
1888     if (optional && keyword_hash) {
1889 	for (i = 0; i < optional; i++) {
1890 	    st_data_t val;
1891 	    if (extract_kwarg(ID2SYM(table[required+i]), &val)) {
1892 		if (values) values[required+i] = (VALUE)val;
1893 		j++;
1894 	    }
1895 	}
1896     }
1897     if (!rest && keyword_hash) {
1898 	if (RHASH_SIZE(keyword_hash) > (unsigned int)(values ? 0 : j)) {
1899 	    unknown_keyword_error(keyword_hash, table, required+optional);
1900 	}
1901     }
1902     return j;
1903 #undef extract_kwarg
1904 }
1905 
1906 #undef rb_scan_args
1907 int
rb_scan_args(int argc,const VALUE * argv,const char * fmt,...)1908 rb_scan_args(int argc, const VALUE *argv, const char *fmt, ...)
1909 {
1910     int i;
1911     const char *p = fmt;
1912     VALUE *var;
1913     va_list vargs;
1914     int f_var = 0, f_hash = 0, f_block = 0;
1915     int n_lead = 0, n_opt = 0, n_trail = 0, n_mand;
1916     int argi = 0, last_idx = -1;
1917     VALUE hash = Qnil, last_hash = 0;
1918 
1919     if (ISDIGIT(*p)) {
1920 	n_lead = *p - '0';
1921 	p++;
1922 	if (ISDIGIT(*p)) {
1923 	    n_opt = *p - '0';
1924 	    p++;
1925 	}
1926     }
1927     if (*p == '*') {
1928 	f_var = 1;
1929 	p++;
1930     }
1931     if (ISDIGIT(*p)) {
1932 	n_trail = *p - '0';
1933 	p++;
1934     }
1935     if (*p == ':') {
1936 	f_hash = 1;
1937 	p++;
1938     }
1939     if (*p == '&') {
1940 	f_block = 1;
1941 	p++;
1942     }
1943     if (*p != '\0') {
1944 	rb_fatal("bad scan arg format: %s", fmt);
1945     }
1946     n_mand = n_lead + n_trail;
1947 
1948     if (argc < n_mand)
1949 	goto argc_error;
1950 
1951     va_start(vargs, fmt);
1952 
1953     /* capture an option hash - phase 1: pop */
1954     if (f_hash && n_mand < argc) {
1955 	VALUE last = argv[argc - 1];
1956 
1957 	if (NIL_P(last)) {
1958 	    /* nil is taken as an empty option hash only if it is not
1959 	       ambiguous; i.e. '*' is not specified and arguments are
1960 	       given more than sufficient */
1961 	    if (!f_var && n_mand + n_opt < argc)
1962 		argc--;
1963 	}
1964 	else {
1965 	    hash = rb_check_hash_type(last);
1966 	    if (!NIL_P(hash)) {
1967 		VALUE opts = rb_extract_keywords(&hash);
1968 		if (!(last_hash = hash)) argc--;
1969 		else last_idx = argc - 1;
1970 		hash = opts ? opts : Qnil;
1971 	    }
1972 	}
1973     }
1974     /* capture leading mandatory arguments */
1975     for (i = n_lead; i-- > 0; ) {
1976 	var = va_arg(vargs, VALUE *);
1977 	if (var) *var = (argi == last_idx) ? last_hash : argv[argi];
1978 	argi++;
1979     }
1980     /* capture optional arguments */
1981     for (i = n_opt; i-- > 0; ) {
1982 	var = va_arg(vargs, VALUE *);
1983 	if (argi < argc - n_trail) {
1984 	    if (var) *var = (argi == last_idx) ? last_hash : argv[argi];
1985 	    argi++;
1986 	}
1987 	else {
1988 	    if (var) *var = Qnil;
1989 	}
1990     }
1991     /* capture variable length arguments */
1992     if (f_var) {
1993 	int n_var = argc - argi - n_trail;
1994 
1995 	var = va_arg(vargs, VALUE *);
1996 	if (0 < n_var) {
1997 	    if (var) {
1998 		int f_last = (last_idx + 1 == argc - n_trail);
1999 		*var = rb_ary_new4(n_var-f_last, &argv[argi]);
2000 		if (f_last) rb_ary_push(*var, last_hash);
2001 	    }
2002 	    argi += n_var;
2003 	}
2004 	else {
2005 	    if (var) *var = rb_ary_new();
2006 	}
2007     }
2008     /* capture trailing mandatory arguments */
2009     for (i = n_trail; i-- > 0; ) {
2010 	var = va_arg(vargs, VALUE *);
2011 	if (var) *var = (argi == last_idx) ? last_hash : argv[argi];
2012 	argi++;
2013     }
2014     /* capture an option hash - phase 2: assignment */
2015     if (f_hash) {
2016 	var = va_arg(vargs, VALUE *);
2017 	if (var) *var = hash;
2018     }
2019     /* capture iterator block */
2020     if (f_block) {
2021 	var = va_arg(vargs, VALUE *);
2022 	if (rb_block_given_p()) {
2023 	    *var = rb_block_proc();
2024 	}
2025 	else {
2026 	    *var = Qnil;
2027 	}
2028     }
2029     va_end(vargs);
2030 
2031     if (argi < argc) {
2032       argc_error:
2033 	rb_error_arity(argc, n_mand, f_var ? UNLIMITED_ARGUMENTS : n_mand + n_opt);
2034     }
2035 
2036     return argc;
2037 }
2038 
2039 int
rb_class_has_methods(VALUE c)2040 rb_class_has_methods(VALUE c)
2041 {
2042     return rb_id_table_size(RCLASS_M_TBL(c)) == 0 ? FALSE : TRUE;
2043 }
2044 
2045 /*!
2046  * \}
2047  */
2048