1 /**********************************************************************
6 created at: Thu Jul 15 12:01:24 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
12 **********************************************************************/
14 #include "ruby/internal/config.h"
25 #include "internal/array.h"
26 #include "internal/class.h"
27 #include "internal/error.h"
28 #include "internal/eval.h"
29 #include "internal/inits.h"
30 #include "internal/numeric.h"
31 #include "internal/object.h"
32 #include "internal/struct.h"
33 #include "internal/string.h"
34 #include "internal/st.h"
35 #include "internal/symbol.h"
36 #include "internal/variable.h"
39 #include "ruby/encoding.h"
41 #include "ruby/util.h"
42 #include "ruby/assert.h"
50 * The object has its instance variables embedded (the array of
51 * instance variables directly follow the object, rather than being
52 * on a separately allocated buffer).
53 * if !SHAPE_IN_BASIC_FLAGS
54 * 4-19: SHAPE_FLAG_MASK
55 * Shape ID for the object.
64 VALUE rb_cBasicObject
;
75 static VALUE rb_cNilClass_to_s
;
76 static VALUE rb_cTrueClass_to_s
;
77 static VALUE rb_cFalseClass_to_s
;
79 /*! \cond INTERNAL_MACRO */
83 #define id_match idEqTilde
84 #define id_inspect idInspect
85 #define id_init_copy idInitialize_copy
86 #define id_init_clone idInitialize_clone
87 #define id_init_dup idInitialize_dup
88 #define id_const_missing idConst_missing
89 #define id_to_f idTo_f
91 #define CLASS_OR_MODULE_P(obj) \
92 (!SPECIAL_CONST_P(obj) && \
93 (BUILTIN_TYPE(obj) == T_CLASS || BUILTIN_TYPE(obj) == T_MODULE))
98 rb_obj_embedded_size(uint32_t numiv
)
100 return offsetof(struct RObject
, as
.ary
) + (sizeof(VALUE
) * numiv
);
104 rb_obj_hide(VALUE obj
)
106 if (!SPECIAL_CONST_P(obj
)) {
107 RBASIC_CLEAR_CLASS(obj
);
113 rb_obj_reveal(VALUE obj
, VALUE klass
)
115 if (!SPECIAL_CONST_P(obj
)) {
116 RBASIC_SET_CLASS(obj
, klass
);
122 rb_class_allocate_instance(VALUE klass
)
124 uint32_t index_tbl_num_entries
= RCLASS_EXT(klass
)->max_iv_count
;
126 size_t size
= rb_obj_embedded_size(index_tbl_num_entries
);
127 if (!rb_gc_size_allocatable_p(size
)) {
128 size
= sizeof(struct RObject
);
131 NEWOBJ_OF(o
, struct RObject
, klass
,
132 T_OBJECT
| ROBJECT_EMBED
| (RGENGC_WB_PROTECTED_OBJECT
? FL_WB_PROTECTED
: 0), size
, 0);
133 VALUE obj
= (VALUE
)o
;
135 RUBY_ASSERT(rb_shape_get_shape(obj
)->type
== SHAPE_ROOT
);
137 // Set the shape to the specific T_OBJECT shape.
138 ROBJECT_SET_SHAPE_ID(obj
, (shape_id_t
)(rb_gc_size_pool_id_for_size(size
) + FIRST_T_OBJECT_SHAPE_ID
));
141 RUBY_ASSERT(!rb_shape_obj_too_complex(obj
));
142 VALUE
*ptr
= ROBJECT_IVPTR(obj
);
143 for (size_t i
= 0; i
< ROBJECT_IV_CAPACITY(obj
); i
++) {
152 rb_obj_setup(VALUE obj
, VALUE klass
, VALUE type
)
154 VALUE ignored_flags
= RUBY_FL_PROMOTED
| RUBY_FL_SEEN_OBJ_ID
;
155 RBASIC(obj
)->flags
= (type
& ~ignored_flags
) | (RBASIC(obj
)->flags
& ignored_flags
);
156 RBASIC_SET_CLASS(obj
, klass
);
162 * true === other -> true or false
163 * false === other -> true or false
164 * nil === other -> true or false
166 * Returns +true+ or +false+.
168 * Like Object#==, if +object+ is an instance of Object
169 * (and not an instance of one of its many subclasses).
171 * This method is commonly overridden by those subclasses,
172 * to provide meaningful semantics in +case+ statements.
174 #define case_equal rb_equal
175 /* The default implementation of #=== is
176 * to call #== with the rb_equal() optimization. */
179 rb_equal(VALUE obj1
, VALUE obj2
)
183 if (obj1
== obj2
) return Qtrue
;
184 result
= rb_equal_opt(obj1
, obj2
);
185 if (UNDEF_P(result
)) {
186 result
= rb_funcall(obj1
, id_eq
, 1, obj2
);
188 return RBOOL(RTEST(result
));
192 rb_eql(VALUE obj1
, VALUE obj2
)
196 if (obj1
== obj2
) return TRUE
;
197 result
= rb_eql_opt(obj1
, obj2
);
198 if (UNDEF_P(result
)) {
199 result
= rb_funcall(obj1
, id_eql
, 1, obj2
);
201 return RTEST(result
);
206 * obj == other -> true or false
207 * obj.equal?(other) -> true or false
208 * obj.eql?(other) -> true or false
210 * Equality --- At the Object level, #== returns <code>true</code>
211 * only if +obj+ and +other+ are the same object. Typically, this
212 * method is overridden in descendant classes to provide
213 * class-specific meaning.
215 * Unlike #==, the #equal? method should never be overridden by
216 * subclasses as it is used to determine object identity (that is,
217 * <code>a.equal?(b)</code> if and only if <code>a</code> is the same
218 * object as <code>b</code>):
223 * obj == other #=> true
224 * obj.equal? other #=> false
225 * obj.equal? obj #=> true
227 * The #eql? method returns <code>true</code> if +obj+ and +other+
228 * refer to the same hash key. This is used by Hash to test members
229 * for equality. For any pair of objects where #eql? returns +true+,
230 * the #hash value of both objects must be equal. So any subclass
231 * that overrides #eql? should also override #hash appropriately.
233 * For objects of class Object, #eql? is synonymous
234 * with #==. Subclasses normally continue this tradition by aliasing
235 * #eql? to their overridden #== method, but there are exceptions.
236 * Numeric types, for example, perform type conversion across #==,
237 * but not across #eql?, so:
240 * 1.eql? 1.0 #=> false
246 rb_obj_equal(VALUE obj1
, VALUE obj2
)
248 return RBOOL(obj1
== obj2
);
251 VALUE
rb_obj_hash(VALUE obj
);
255 * !obj -> true or false
264 rb_obj_not(VALUE obj
)
266 return RBOOL(!RTEST(obj
));
271 * obj != other -> true or false
273 * Returns true if two objects are not-equal, otherwise false.
280 rb_obj_not_equal(VALUE obj1
, VALUE obj2
)
282 VALUE result
= rb_funcall(obj1
, id_eq
, 1, obj2
);
283 return rb_obj_not(result
);
287 rb_class_real(VALUE cl
)
290 (RCLASS_SINGLETON_P(cl
) || BUILTIN_TYPE(cl
) == T_ICLASS
)) {
291 cl
= RCLASS_SUPER(cl
);
297 rb_obj_class(VALUE obj
)
299 return rb_class_real(CLASS_OF(obj
));
304 * obj.singleton_class -> class
306 * Returns the singleton class of <i>obj</i>. This method creates
307 * a new singleton class if <i>obj</i> does not have one.
309 * If <i>obj</i> is <code>nil</code>, <code>true</code>, or
310 * <code>false</code>, it returns NilClass, TrueClass, or FalseClass,
312 * If <i>obj</i> is an Integer, a Float or a Symbol, it raises a TypeError.
314 * Object.new.singleton_class #=> #<Class:#<Object:0xb7ce1e24>>
315 * String.singleton_class #=> #<Class:String>
316 * nil.singleton_class #=> NilClass
320 rb_obj_singleton_class(VALUE obj
)
322 return rb_singleton_class(obj
);
327 rb_obj_copy_ivar(VALUE dest
, VALUE obj
)
329 RUBY_ASSERT(!RB_TYPE_P(obj
, T_CLASS
) && !RB_TYPE_P(obj
, T_MODULE
));
331 RUBY_ASSERT(BUILTIN_TYPE(dest
) == BUILTIN_TYPE(obj
));
332 rb_shape_t
* src_shape
= rb_shape_get_shape(obj
);
334 if (rb_shape_obj_too_complex(obj
)) {
335 // obj is TOO_COMPLEX so we can copy its iv_hash
336 st_table
*table
= st_copy(ROBJECT_IV_HASH(obj
));
337 rb_obj_convert_to_too_complex(dest
, table
);
342 uint32_t src_num_ivs
= RBASIC_IV_COUNT(obj
);
343 rb_shape_t
* shape_to_set_on_dest
= src_shape
;
351 // The copy should be mutable, so we don't want the frozen shape
352 if (rb_shape_frozen_shape_p(src_shape
)) {
353 shape_to_set_on_dest
= rb_shape_get_parent(src_shape
);
356 src_buf
= ROBJECT_IVPTR(obj
);
357 dest_buf
= ROBJECT_IVPTR(dest
);
359 rb_shape_t
* initial_shape
= rb_shape_get_shape(dest
);
361 if (initial_shape
->size_pool_index
!= src_shape
->size_pool_index
) {
362 RUBY_ASSERT(initial_shape
->type
== SHAPE_T_OBJECT
);
364 shape_to_set_on_dest
= rb_shape_rebuild_shape(initial_shape
, src_shape
);
365 if (UNLIKELY(rb_shape_id(shape_to_set_on_dest
) == OBJ_TOO_COMPLEX_SHAPE_ID
)) {
366 st_table
* table
= rb_st_init_numtable_with_size(src_num_ivs
);
367 rb_obj_copy_ivs_to_hash_table(obj
, table
);
368 rb_obj_convert_to_too_complex(dest
, table
);
374 RUBY_ASSERT(src_num_ivs
<= shape_to_set_on_dest
->capacity
|| rb_shape_id(shape_to_set_on_dest
) == OBJ_TOO_COMPLEX_SHAPE_ID
);
375 if (initial_shape
->capacity
< shape_to_set_on_dest
->capacity
) {
376 rb_ensure_iv_list_size(dest
, initial_shape
->capacity
, shape_to_set_on_dest
->capacity
);
377 dest_buf
= ROBJECT_IVPTR(dest
);
380 MEMCPY(dest_buf
, src_buf
, VALUE
, src_num_ivs
);
382 // Fire write barriers
383 for (uint32_t i
= 0; i
< src_num_ivs
; i
++) {
384 RB_OBJ_WRITTEN(dest
, Qundef
, dest_buf
[i
]);
387 rb_shape_set_shape(dest
, shape_to_set_on_dest
);
391 init_copy(VALUE dest
, VALUE obj
)
393 if (OBJ_FROZEN(dest
)) {
394 rb_raise(rb_eTypeError
, "[bug] frozen object (%s) allocated", rb_obj_classname(dest
));
396 RBASIC(dest
)->flags
&= ~(T_MASK
|FL_EXIVAR
);
397 // Copies the shape id from obj to dest
398 RBASIC(dest
)->flags
|= RBASIC(obj
)->flags
& (T_MASK
|FL_EXIVAR
);
399 rb_gc_copy_attributes(dest
, obj
);
400 rb_copy_generic_ivar(dest
, obj
);
401 if (RB_TYPE_P(obj
, T_OBJECT
)) {
402 rb_obj_copy_ivar(dest
, obj
);
406 static VALUE
immutable_obj_clone(VALUE obj
, VALUE kwfreeze
);
407 static VALUE
mutable_obj_clone(VALUE obj
, VALUE kwfreeze
);
408 PUREFUNC(static inline int special_object_p(VALUE obj
)); /*!< \private */
410 special_object_p(VALUE obj
)
412 if (SPECIAL_CONST_P(obj
)) return TRUE
;
413 switch (BUILTIN_TYPE(obj
)) {
419 /* not a comprehensive list */
427 obj_freeze_opt(VALUE freeze
)
435 rb_raise(rb_eArgError
, "unexpected value for freeze: %"PRIsVALUE
, rb_obj_class(freeze
));
442 rb_obj_clone2(rb_execution_context_t
*ec
, VALUE obj
, VALUE freeze
)
444 VALUE kwfreeze
= obj_freeze_opt(freeze
);
445 if (!special_object_p(obj
))
446 return mutable_obj_clone(obj
, kwfreeze
);
447 return immutable_obj_clone(obj
, kwfreeze
);
452 rb_immutable_obj_clone(int argc
, VALUE
*argv
, VALUE obj
)
454 VALUE kwfreeze
= rb_get_freeze_opt(argc
, argv
);
455 return immutable_obj_clone(obj
, kwfreeze
);
459 rb_get_freeze_opt(int argc
, VALUE
*argv
)
461 static ID keyword_ids
[1];
463 VALUE kwfreeze
= Qnil
;
465 if (!keyword_ids
[0]) {
466 CONST_ID(keyword_ids
[0], "freeze");
468 rb_scan_args(argc
, argv
, "0:", &opt
);
470 rb_get_kwargs(opt
, keyword_ids
, 0, 1, &kwfreeze
);
471 if (!UNDEF_P(kwfreeze
))
472 kwfreeze
= obj_freeze_opt(kwfreeze
);
478 immutable_obj_clone(VALUE obj
, VALUE kwfreeze
)
480 if (kwfreeze
== Qfalse
)
481 rb_raise(rb_eArgError
, "can't unfreeze %"PRIsVALUE
,
487 rb_obj_clone_setup(VALUE obj
, VALUE clone
, VALUE kwfreeze
)
491 VALUE singleton
= rb_singleton_class_clone_and_attach(obj
, clone
);
492 RBASIC_SET_CLASS(clone
, singleton
);
493 if (RCLASS_SINGLETON_P(singleton
)) {
494 rb_singleton_class_attached(singleton
, clone
);
497 init_copy(clone
, obj
);
501 rb_funcall(clone
, id_init_clone
, 1, obj
);
502 RBASIC(clone
)->flags
|= RBASIC(obj
)->flags
& FL_FREEZE
;
503 if (CHILLED_STRING_P(obj
)) {
504 STR_CHILL_RAW(clone
);
506 else if (RB_OBJ_FROZEN(obj
)) {
507 rb_shape_t
* next_shape
= rb_shape_transition_shape_frozen(clone
);
508 if (!rb_shape_obj_too_complex(clone
) && next_shape
->type
== SHAPE_OBJ_TOO_COMPLEX
) {
509 rb_evict_ivars_to_hash(clone
);
512 rb_shape_set_shape(clone
, next_shape
);
517 static VALUE freeze_true_hash
;
518 if (!freeze_true_hash
) {
519 freeze_true_hash
= rb_hash_new();
520 rb_vm_register_global_object(freeze_true_hash
);
521 rb_hash_aset(freeze_true_hash
, ID2SYM(idFreeze
), Qtrue
);
522 rb_obj_freeze(freeze_true_hash
);
526 argv
[1] = freeze_true_hash
;
527 rb_funcallv_kw(clone
, id_init_clone
, 2, argv
, RB_PASS_KEYWORDS
);
528 RBASIC(clone
)->flags
|= FL_FREEZE
;
529 rb_shape_t
* next_shape
= rb_shape_transition_shape_frozen(clone
);
530 // If we're out of shapes, but we want to freeze, then we need to
531 // evacuate this clone to a hash
532 if (!rb_shape_obj_too_complex(clone
) && next_shape
->type
== SHAPE_OBJ_TOO_COMPLEX
) {
533 rb_evict_ivars_to_hash(clone
);
536 rb_shape_set_shape(clone
, next_shape
);
541 static VALUE freeze_false_hash
;
542 if (!freeze_false_hash
) {
543 freeze_false_hash
= rb_hash_new();
544 rb_vm_register_global_object(freeze_false_hash
);
545 rb_hash_aset(freeze_false_hash
, ID2SYM(idFreeze
), Qfalse
);
546 rb_obj_freeze(freeze_false_hash
);
550 argv
[1] = freeze_false_hash
;
551 rb_funcallv_kw(clone
, id_init_clone
, 2, argv
, RB_PASS_KEYWORDS
);
555 rb_bug("invalid kwfreeze passed to mutable_obj_clone");
562 mutable_obj_clone(VALUE obj
, VALUE kwfreeze
)
564 VALUE clone
= rb_obj_alloc(rb_obj_class(obj
));
565 return rb_obj_clone_setup(obj
, clone
, kwfreeze
);
569 rb_obj_clone(VALUE obj
)
571 if (special_object_p(obj
)) return obj
;
572 return mutable_obj_clone(obj
, Qnil
);
576 rb_obj_dup_setup(VALUE obj
, VALUE dup
)
579 rb_funcall(dup
, id_init_dup
, 1, obj
);
586 * obj.dup -> an_object
588 * Produces a shallow copy of <i>obj</i>---the instance variables of
589 * <i>obj</i> are copied, but not the objects they reference.
591 * This method may have class-specific behavior. If so, that
592 * behavior will be documented under the #+initialize_copy+ method of
595 * === on dup vs clone
597 * In general, #clone and #dup may have different semantics in
598 * descendant classes. While #clone is used to duplicate an object,
599 * including its internal state, #dup typically uses the class of the
600 * descendant object to create the new instance.
602 * When using #dup, any modules that the object has been extended with will not
610 * def foo; 'foo'; end
613 * s1 = Klass.new #=> #<Klass:0x401b3a38>
614 * s1.extend(Foo) #=> #<Klass:0x401b3a38>
617 * s2 = s1.clone #=> #<Klass:0x401be280>
620 * s3 = s1.dup #=> #<Klass:0x401c1084>
621 * s3.foo #=> NoMethodError: undefined method `foo' for #<Klass:0x401c1084>
624 rb_obj_dup(VALUE obj
)
628 if (special_object_p(obj
)) {
631 dup
= rb_obj_alloc(rb_obj_class(obj
));
632 return rb_obj_dup_setup(obj
, dup
);
639 * Returns the receiver.
641 * string = "my string"
642 * string.itself.object_id == string.object_id #=> true
647 rb_obj_itself(VALUE obj
)
653 rb_obj_size(VALUE self
, VALUE args
, VALUE obj
)
661 * Default implementation of `#initialize_copy`
662 * @param[in,out] obj the receiver being initialized
663 * @param[in] orig the object to be copied from.
667 rb_obj_init_copy(VALUE obj
, VALUE orig
)
669 if (obj
== orig
) return obj
;
670 rb_check_frozen(obj
);
671 if (TYPE(obj
) != TYPE(orig
) || rb_obj_class(obj
) != rb_obj_class(orig
)) {
672 rb_raise(rb_eTypeError
, "initialize_copy should take same class object");
680 * Default implementation of `#initialize_dup`
682 * @param[in,out] obj the receiver being initialized
683 * @param[in] orig the object to be dup from.
687 rb_obj_init_dup_clone(VALUE obj
, VALUE orig
)
689 rb_funcall(obj
, id_init_copy
, 1, orig
);
696 * Default implementation of `#initialize_clone`
698 * @param[in] The number of arguments
699 * @param[in] The array of arguments
700 * @param[in] obj the receiver being initialized
704 rb_obj_init_clone(int argc
, VALUE
*argv
, VALUE obj
)
707 if (rb_scan_args(argc
, argv
, "1:", &orig
, &opts
) < argc
) {
708 /* Ignore a freeze keyword */
709 rb_get_freeze_opt(1, &opts
);
711 rb_funcall(obj
, id_init_copy
, 1, orig
);
719 * Returns a string representing <i>obj</i>. The default #to_s prints
720 * the object's class and an encoding of the object id. As a special
721 * case, the top-level object that is the initial execution context
722 * of Ruby programs returns ``main''.
726 rb_any_to_s(VALUE obj
)
729 VALUE cname
= rb_class_name(CLASS_OF(obj
));
731 str
= rb_sprintf("#<%"PRIsVALUE
":%p>", cname
, (void*)obj
);
737 rb_inspect(VALUE obj
)
739 VALUE str
= rb_obj_as_string(rb_funcallv(obj
, id_inspect
, 0, 0));
741 rb_encoding
*enc
= rb_default_internal_encoding();
742 if (enc
== NULL
) enc
= rb_default_external_encoding();
743 if (!rb_enc_asciicompat(enc
)) {
744 if (!rb_enc_str_asciionly_p(str
))
745 return rb_str_escape(str
);
748 if (rb_enc_get(str
) != enc
&& !rb_enc_str_asciionly_p(str
))
749 return rb_str_escape(str
);
754 inspect_i(ID id
, VALUE value
, st_data_t a
)
756 VALUE str
= (VALUE
)a
;
758 /* need not to show internal data */
759 if (CLASS_OF(value
) == 0) return ST_CONTINUE
;
760 if (!rb_is_instance_id(id
)) return ST_CONTINUE
;
761 if (RSTRING_PTR(str
)[0] == '-') { /* first element */
762 RSTRING_PTR(str
)[0] = '#';
763 rb_str_cat2(str
, " ");
766 rb_str_cat2(str
, ", ");
768 rb_str_catf(str
, "%"PRIsVALUE
"=", rb_id2str(id
));
769 rb_str_buf_append(str
, rb_inspect(value
));
775 inspect_obj(VALUE obj
, VALUE str
, int recur
)
778 rb_str_cat2(str
, " ...");
781 rb_ivar_foreach(obj
, inspect_i
, str
);
783 rb_str_cat2(str
, ">");
784 RSTRING_PTR(str
)[0] = '#';
791 * obj.inspect -> string
793 * Returns a string containing a human-readable representation of <i>obj</i>.
794 * The default #inspect shows the object's class name, an encoding of
795 * its memory address, and a list of the instance variables and their
796 * values (by calling #inspect on each of them). User defined classes
797 * should override this method to provide a better representation of
798 * <i>obj</i>. When overriding this method, it should return a string
799 * whose encoding is compatible with the default external encoding.
801 * [ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]"
802 * Time.new.inspect #=> "2008-03-08 19:43:39 +0900"
806 * Foo.new.inspect #=> "#<Foo:0x0300c868>"
813 * Bar.new.inspect #=> "#<Bar:0x0300c868 @bar=1>"
817 rb_obj_inspect(VALUE obj
)
819 if (rb_ivar_count(obj
) > 0) {
821 VALUE c
= rb_class_name(CLASS_OF(obj
));
823 str
= rb_sprintf("-<%"PRIsVALUE
":%p", c
, (void*)obj
);
824 return rb_exec_recursive(inspect_obj
, obj
, str
);
827 return rb_any_to_s(obj
);
832 class_or_module_required(VALUE c
)
834 switch (OBJ_BUILTIN_TYPE(c
)) {
841 rb_raise(rb_eTypeError
, "class or module required");
846 static VALUE
class_search_ancestor(VALUE cl
, VALUE c
);
850 * obj.instance_of?(class) -> true or false
852 * Returns <code>true</code> if <i>obj</i> is an instance of the given
853 * class. See also Object#kind_of?.
860 * b.instance_of? A #=> false
861 * b.instance_of? B #=> true
862 * b.instance_of? C #=> false
866 rb_obj_is_instance_of(VALUE obj
, VALUE c
)
868 c
= class_or_module_required(c
);
869 return RBOOL(rb_obj_class(obj
) == c
);
872 // Returns whether c is a proper (c != cl) superclass of cl
873 // Both c and cl must be T_CLASS
875 class_search_class_ancestor(VALUE cl
, VALUE c
)
877 RUBY_ASSERT(RB_TYPE_P(c
, T_CLASS
));
878 RUBY_ASSERT(RB_TYPE_P(cl
, T_CLASS
));
880 size_t c_depth
= RCLASS_SUPERCLASS_DEPTH(c
);
881 size_t cl_depth
= RCLASS_SUPERCLASS_DEPTH(cl
);
882 VALUE
*classes
= RCLASS_SUPERCLASSES(cl
);
884 // If c's inheritance chain is longer, it cannot be an ancestor
885 // We are checking for a proper superclass so don't check if they are equal
886 if (cl_depth
<= c_depth
)
889 // Otherwise check that c is in cl's inheritance chain
890 return RBOOL(classes
[c_depth
] == c
);
895 * obj.is_a?(class) -> true or false
896 * obj.kind_of?(class) -> true or false
898 * Returns <code>true</code> if <i>class</i> is the class of
899 * <i>obj</i>, or if <i>class</i> is one of the superclasses of
900 * <i>obj</i> or modules included in <i>obj</i>.
912 * b.is_a? C #=> false
915 * b.kind_of? A #=> true
916 * b.kind_of? B #=> true
917 * b.kind_of? C #=> false
918 * b.kind_of? M #=> true
922 rb_obj_is_kind_of(VALUE obj
, VALUE c
)
924 VALUE cl
= CLASS_OF(obj
);
926 RUBY_ASSERT(RB_TYPE_P(cl
, T_CLASS
));
928 // Fastest path: If the object's class is an exact match we know `c` is a
929 // class without checking type and can return immediately.
930 if (cl
== c
) return Qtrue
;
932 // Note: YJIT needs this function to never allocate and never raise when
933 // `c` is a class or a module.
935 if (LIKELY(RB_TYPE_P(c
, T_CLASS
))) {
936 // Fast path: Both are T_CLASS
937 return class_search_class_ancestor(cl
, c
);
939 else if (RB_TYPE_P(c
, T_ICLASS
)) {
940 // First check if we inherit the includer
941 // If we do we can return true immediately
942 VALUE includer
= RCLASS_INCLUDER(c
);
943 if (cl
== includer
) return Qtrue
;
945 // Usually includer is a T_CLASS here, except when including into an
946 // already included Module.
947 // If it is a class, attempt the fast class-to-class check and return
948 // true if there is a match.
949 if (RB_TYPE_P(includer
, T_CLASS
) && class_search_class_ancestor(cl
, includer
))
952 // We don't include the ICLASS directly, so must check if we inherit
953 // the module via another include
954 return RBOOL(class_search_ancestor(cl
, RCLASS_ORIGIN(c
)));
956 else if (RB_TYPE_P(c
, T_MODULE
)) {
957 // Slow path: check each ancestor in the linked list and its method table
958 return RBOOL(class_search_ancestor(cl
, RCLASS_ORIGIN(c
)));
961 rb_raise(rb_eTypeError
, "class or module required");
962 UNREACHABLE_RETURN(Qfalse
);
968 class_search_ancestor(VALUE cl
, VALUE c
)
971 if (cl
== c
|| RCLASS_M_TBL(cl
) == RCLASS_M_TBL(c
))
973 cl
= RCLASS_SUPER(cl
);
980 rb_class_search_ancestor(VALUE cl
, VALUE c
)
982 cl
= class_or_module_required(cl
);
983 c
= class_or_module_required(c
);
984 return class_search_ancestor(cl
, RCLASS_ORIGIN(c
));
989 * Document-method: inherited
992 * inherited(subclass)
994 * Callback invoked whenever a subclass of the current class is created.
999 * def self.inherited(subclass)
1000 * puts "New subclass: #{subclass}"
1010 * <em>produces:</em>
1015 #define rb_obj_class_inherited rb_obj_dummy1
1017 /* Document-method: method_added
1020 * method_added(method_name)
1022 * Invoked as a callback whenever an instance method is added to the
1026 * def self.method_added(method_name)
1027 * puts "Adding #{method_name.inspect}"
1029 * def self.some_class_method() end
1030 * def some_instance_method() end
1033 * <em>produces:</em>
1035 * Adding :some_instance_method
1038 #define rb_obj_mod_method_added rb_obj_dummy1
1040 /* Document-method: method_removed
1043 * method_removed(method_name)
1045 * Invoked as a callback whenever an instance method is removed from the
1049 * def self.method_removed(method_name)
1050 * puts "Removing #{method_name.inspect}"
1052 * def self.some_class_method() end
1053 * def some_instance_method() end
1055 * remove_method :some_class_method
1057 * remove_method :some_instance_method
1060 * <em>produces:</em>
1062 * Removing :some_instance_method
1065 #define rb_obj_mod_method_removed rb_obj_dummy1
1067 /* Document-method: method_undefined
1070 * method_undefined(method_name)
1072 * Invoked as a callback whenever an instance method is undefined from the
1076 * def self.method_undefined(method_name)
1077 * puts "Undefining #{method_name.inspect}"
1079 * def self.some_class_method() end
1080 * def some_instance_method() end
1082 * undef_method :some_class_method
1084 * undef_method :some_instance_method
1087 * <em>produces:</em>
1089 * Undefining :some_instance_method
1092 #define rb_obj_mod_method_undefined rb_obj_dummy1
1095 * Document-method: singleton_method_added
1098 * singleton_method_added(symbol)
1100 * Invoked as a callback whenever a singleton method is added to the
1104 * def Chatty.singleton_method_added(id)
1105 * puts "Adding #{id.id2name}"
1107 * def self.one() end
1109 * def Chatty.three() end
1112 * <em>produces:</em>
1114 * Adding singleton_method_added
1119 #define rb_obj_singleton_method_added rb_obj_dummy1
1122 * Document-method: singleton_method_removed
1125 * singleton_method_removed(symbol)
1127 * Invoked as a callback whenever a singleton method is removed from
1131 * def Chatty.singleton_method_removed(id)
1132 * puts "Removing #{id.id2name}"
1134 * def self.one() end
1136 * def Chatty.three() end
1138 * remove_method :three
1139 * remove_method :one
1143 * <em>produces:</em>
1148 #define rb_obj_singleton_method_removed rb_obj_dummy1
1151 * Document-method: singleton_method_undefined
1154 * singleton_method_undefined(symbol)
1156 * Invoked as a callback whenever a singleton method is undefined in
1160 * def Chatty.singleton_method_undefined(id)
1161 * puts "Undefining #{id.id2name}"
1163 * def Chatty.one() end
1165 * undef_method(:one)
1169 * <em>produces:</em>
1173 #define rb_obj_singleton_method_undefined rb_obj_dummy1
1175 /* Document-method: const_added
1178 * const_added(const_name)
1180 * Invoked as a callback whenever a constant is assigned on the receiver
1183 * def self.const_added(const_name)
1185 * puts "Added #{const_name.inspect}"
1190 * <em>produces:</em>
1195 #define rb_obj_mod_const_added rb_obj_dummy1
1198 * Document-method: extended
1201 * extended(othermod)
1203 * The equivalent of <tt>included</tt>, but for extended modules.
1206 * def self.extended(mod)
1207 * puts "#{self} extended in #{mod}"
1213 * # => prints "A extended in Enumerable"
1215 #define rb_obj_mod_extended rb_obj_dummy1
1218 * Document-method: included
1221 * included(othermod)
1223 * Callback invoked whenever the receiver is included in another
1224 * module or class. This should be used in preference to
1225 * <tt>Module.append_features</tt> if your code wants to perform some
1226 * action when a module is included in another.
1229 * def A.included(mod)
1230 * puts "#{self} included in #{mod}"
1236 * # => prints "A included in Enumerable"
1238 #define rb_obj_mod_included rb_obj_dummy1
1241 * Document-method: prepended
1244 * prepended(othermod)
1246 * The equivalent of <tt>included</tt>, but for prepended modules.
1249 * def self.prepended(mod)
1250 * puts "#{self} prepended to #{mod}"
1256 * # => prints "A prepended to Enumerable"
1258 #define rb_obj_mod_prepended rb_obj_dummy1
1261 * Document-method: initialize
1266 * Returns a new BasicObject.
1268 #define rb_obj_initialize rb_obj_dummy0
1281 rb_obj_dummy0(VALUE _
)
1283 return rb_obj_dummy();
1287 rb_obj_dummy1(VALUE _x
, VALUE _y
)
1289 return rb_obj_dummy();
1296 * Prevents further modifications to <i>obj</i>. A
1297 * FrozenError will be raised if modification is attempted.
1298 * There is no way to unfreeze a frozen object. See also
1301 * This method returns self.
1303 * a = [ "a", "b", "c" ]
1307 * <em>produces:</em>
1309 * prog.rb:3:in `<<': can't modify frozen Array (FrozenError)
1312 * Objects of the following classes are always frozen: Integer,
1317 rb_obj_freeze(VALUE obj
)
1319 if (!OBJ_FROZEN(obj
)) {
1321 if (SPECIAL_CONST_P(obj
)) {
1322 rb_bug("special consts should be frozen.");
1329 rb_obj_frozen_p(VALUE obj
)
1331 return RBOOL(OBJ_FROZEN(obj
));
1336 * Document-class: NilClass
1338 * The class of the singleton object +nil+.
1340 * Several of its methods act as operators:
1348 * Others act as converters, carrying the concept of _nullity_
1358 * Another method provides inspection:
1362 * Finally, there is this query method:
1372 * Returns an empty String:
1379 rb_nil_to_s(VALUE obj
)
1381 return rb_cNilClass_to_s
;
1385 * Document-method: to_a
1390 * Returns an empty Array.
1399 return rb_ary_new2(0);
1403 * Document-method: to_h
1408 * Returns an empty Hash.
1417 return rb_hash_new();
1424 * Returns string <tt>'nil'</tt>:
1426 * nil.inspect # => "nil"
1431 nil_inspect(VALUE obj
)
1433 return rb_usascii_str_new2("nil");
1438 * nil =~ object -> nil
1442 * This method makes it useful to write:
1444 * while gets =~ /re/
1451 nil_match(VALUE obj1
, VALUE obj2
)
1457 * Document-class: TrueClass
1459 * The class of the singleton object +true+.
1461 * Several of its methods act as operators:
1470 * - #to_s and its alias #inspect.
1477 * true.to_s -> 'true'
1479 * Returns string <tt>'true'</tt>:
1481 * true.to_s # => "true"
1483 * TrueClass#inspect is an alias for TrueClass#to_s.
1488 rb_true_to_s(VALUE obj
)
1490 return rb_cTrueClass_to_s
;
1496 * true & object -> true or false
1498 * Returns +false+ if +object+ is +false+ or +nil+, +true+ otherwise:
1500 * true & Object.new # => true
1501 * true & false # => false
1502 * true & nil # => false
1507 true_and(VALUE obj
, VALUE obj2
)
1509 return RBOOL(RTEST(obj2
));
1514 * true | object -> true
1518 * true | Object.new # => true
1519 * true | false # => true
1520 * true | nil # => true
1522 * Argument +object+ is evaluated.
1523 * This is different from +true+ with the short-circuit operator,
1524 * whose operand is evaluated only if necessary:
1526 * true | raise # => Raises RuntimeError.
1527 * true || raise # => true
1532 true_or(VALUE obj
, VALUE obj2
)
1540 * true ^ object -> !object
1542 * Returns +true+ if +object+ is +false+ or +nil+, +false+ otherwise:
1544 * true ^ Object.new # => false
1545 * true ^ false # => true
1546 * true ^ nil # => true
1551 true_xor(VALUE obj
, VALUE obj2
)
1553 return rb_obj_not(obj2
);
1558 * Document-class: FalseClass
1560 * The global value <code>false</code> is the only instance of class
1561 * FalseClass and represents a logically false value in
1562 * boolean expressions. The class provides operators allowing
1563 * <code>false</code> to participate correctly in logical expressions.
1569 * false.to_s -> "false"
1571 * The string representation of <code>false</code> is "false".
1575 rb_false_to_s(VALUE obj
)
1577 return rb_cFalseClass_to_s
;
1582 * false & object -> false
1583 * nil & object -> false
1587 * false & true # => false
1588 * false & Object.new # => false
1590 * Argument +object+ is evaluated:
1592 * false & raise # Raises RuntimeError.
1596 false_and(VALUE obj
, VALUE obj2
)
1604 * false | object -> true or false
1605 * nil | object -> true or false
1607 * Returns +false+ if +object+ is +nil+ or +false+, +true+ otherwise:
1609 * nil | nil # => false
1610 * nil | false # => false
1611 * nil | Object.new # => true
1615 #define false_or true_and
1619 * false ^ object -> true or false
1620 * nil ^ object -> true or false
1622 * Returns +false+ if +object+ is +nil+ or +false+, +true+ otherwise:
1624 * nil ^ nil # => false
1625 * nil ^ false # => false
1626 * nil ^ Object.new # => true
1630 #define false_xor true_and
1637 * For all other objects, method <tt>nil?</tt> returns +false+.
1648 * obj.nil? -> true or false
1650 * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1652 * Object.new.nil? #=> false
1665 * obj !~ other -> true or false
1667 * Returns true if two objects do not match (using the <i>=~</i>
1668 * method), otherwise false.
1672 rb_obj_not_match(VALUE obj1
, VALUE obj2
)
1674 VALUE result
= rb_funcall(obj1
, id_match
, 1, obj2
);
1675 return rb_obj_not(result
);
1681 * obj <=> other -> 0 or nil
1683 * Returns 0 if +obj+ and +other+ are the same object
1684 * or <code>obj == other</code>, otherwise nil.
1686 * The #<=> is used by various methods to compare objects, for example
1687 * Enumerable#sort, Enumerable#max etc.
1689 * Your implementation of #<=> should return one of the following values: -1, 0,
1690 * 1 or nil. -1 means self is smaller than other. 0 means self is equal to other.
1691 * 1 means self is bigger than other. Nil means the two values could not be
1694 * When you define #<=>, you can include Comparable to gain the
1695 * methods #<=, #<, #==, #>=, #> and #between?.
1698 rb_obj_cmp(VALUE obj1
, VALUE obj2
)
1700 if (rb_equal(obj1
, obj2
))
1705 /***********************************************************************
1707 * Document-class: Module
1709 * A Module is a collection of methods and constants. The
1710 * methods in a module may be instance methods or module methods.
1711 * Instance methods appear as methods in a class when the module is
1712 * included, module methods do not. Conversely, module methods may be
1713 * called without creating an encapsulating object, while instance
1714 * methods may not. (See Module#module_function.)
1716 * In the descriptions that follow, the parameter <i>sym</i> refers
1717 * to a symbol, which is either a quoted string or a
1718 * Symbol (such as <code>:name</code>).
1727 * Mod.class #=> Module
1728 * Mod.constants #=> [:CONST, :PI, :E]
1729 * Mod.instance_methods #=> [:meth]
1735 * mod.to_s -> string
1737 * Returns a string representing this module or class. For basic
1738 * classes and modules, this is the name. For singletons, we
1739 * show information on the thing we're attached to as well.
1743 rb_mod_to_s(VALUE klass
)
1746 VALUE refined_class
, defined_at
;
1748 if (RCLASS_SINGLETON_P(klass
)) {
1749 VALUE s
= rb_usascii_str_new2("#<Class:");
1750 VALUE v
= RCLASS_ATTACHED_OBJECT(klass
);
1752 if (CLASS_OR_MODULE_P(v
)) {
1753 rb_str_append(s
, rb_inspect(v
));
1756 rb_str_append(s
, rb_any_to_s(v
));
1758 rb_str_cat2(s
, ">");
1762 refined_class
= rb_refinement_module_get_refined_class(klass
);
1763 if (!NIL_P(refined_class
)) {
1764 VALUE s
= rb_usascii_str_new2("#<refinement:");
1766 rb_str_concat(s
, rb_inspect(refined_class
));
1767 rb_str_cat2(s
, "@");
1768 CONST_ID(id_defined_at
, "__defined_at__");
1769 defined_at
= rb_attr_get(klass
, id_defined_at
);
1770 rb_str_concat(s
, rb_inspect(defined_at
));
1771 rb_str_cat2(s
, ">");
1774 return rb_class_name(klass
);
1781 * Prevents further modifications to <i>mod</i>.
1783 * This method returns self.
1787 rb_mod_freeze(VALUE mod
)
1790 return rb_obj_freeze(mod
);
1795 * mod === obj -> true or false
1797 * Case Equality---Returns <code>true</code> if <i>obj</i> is an
1798 * instance of <i>mod</i> or an instance of one of <i>mod</i>'s descendants.
1799 * Of limited use for modules, but can be used in <code>case</code> statements
1800 * to classify objects by class.
1804 rb_mod_eqq(VALUE mod
, VALUE arg
)
1806 return rb_obj_is_kind_of(arg
, mod
);
1811 * mod <= other -> true, false, or nil
1813 * Returns true if <i>mod</i> is a subclass of <i>other</i> or
1814 * is the same as <i>other</i>. Returns
1815 * <code>nil</code> if there's no relationship between the two.
1816 * (Think of the relationship in terms of the class definition:
1817 * "class A < B" implies "A < B".)
1821 rb_class_inherited_p(VALUE mod
, VALUE arg
)
1823 if (mod
== arg
) return Qtrue
;
1825 if (RB_TYPE_P(arg
, T_CLASS
) && RB_TYPE_P(mod
, T_CLASS
)) {
1826 // comparison between classes
1827 size_t mod_depth
= RCLASS_SUPERCLASS_DEPTH(mod
);
1828 size_t arg_depth
= RCLASS_SUPERCLASS_DEPTH(arg
);
1829 if (arg_depth
< mod_depth
) {
1830 // check if mod < arg
1831 return RCLASS_SUPERCLASSES(mod
)[arg_depth
] == arg
?
1835 else if (arg_depth
> mod_depth
) {
1836 // check if mod > arg
1837 return RCLASS_SUPERCLASSES(arg
)[mod_depth
] == mod
?
1842 // Depths match, and we know they aren't equal: no relation
1847 if (!CLASS_OR_MODULE_P(arg
) && !RB_TYPE_P(arg
, T_ICLASS
)) {
1848 rb_raise(rb_eTypeError
, "compared with non class/module");
1850 if (class_search_ancestor(mod
, RCLASS_ORIGIN(arg
))) {
1853 /* not mod < arg; check if mod > arg */
1854 if (class_search_ancestor(arg
, mod
)) {
1863 * mod < other -> true, false, or nil
1865 * Returns true if <i>mod</i> is a subclass of <i>other</i>. Returns
1866 * <code>false</code> if <i>mod</i> is the same as <i>other</i>
1867 * or <i>mod</i> is an ancestor of <i>other</i>.
1868 * Returns <code>nil</code> if there's no relationship between the two.
1869 * (Think of the relationship in terms of the class definition:
1870 * "class A < B" implies "A < B".)
1875 rb_mod_lt(VALUE mod
, VALUE arg
)
1877 if (mod
== arg
) return Qfalse
;
1878 return rb_class_inherited_p(mod
, arg
);
1884 * mod >= other -> true, false, or nil
1886 * Returns true if <i>mod</i> is an ancestor of <i>other</i>, or the
1887 * two modules are the same. Returns
1888 * <code>nil</code> if there's no relationship between the two.
1889 * (Think of the relationship in terms of the class definition:
1890 * "class A < B" implies "B > A".)
1895 rb_mod_ge(VALUE mod
, VALUE arg
)
1897 if (!CLASS_OR_MODULE_P(arg
)) {
1898 rb_raise(rb_eTypeError
, "compared with non class/module");
1901 return rb_class_inherited_p(arg
, mod
);
1906 * mod > other -> true, false, or nil
1908 * Returns true if <i>mod</i> is an ancestor of <i>other</i>. Returns
1909 * <code>false</code> if <i>mod</i> is the same as <i>other</i>
1910 * or <i>mod</i> is a descendant of <i>other</i>.
1911 * Returns <code>nil</code> if there's no relationship between the two.
1912 * (Think of the relationship in terms of the class definition:
1913 * "class A < B" implies "B > A".)
1918 rb_mod_gt(VALUE mod
, VALUE arg
)
1920 if (mod
== arg
) return Qfalse
;
1921 return rb_mod_ge(mod
, arg
);
1926 * module <=> other_module -> -1, 0, +1, or nil
1928 * Comparison---Returns -1, 0, +1 or nil depending on whether +module+
1929 * includes +other_module+, they are the same, or if +module+ is included by
1932 * Returns +nil+ if +module+ has no relationship with +other_module+, if
1933 * +other_module+ is not a module, or if the two values are incomparable.
1937 rb_mod_cmp(VALUE mod
, VALUE arg
)
1941 if (mod
== arg
) return INT2FIX(0);
1942 if (!CLASS_OR_MODULE_P(arg
)) {
1946 cmp
= rb_class_inherited_p(mod
, arg
);
1947 if (NIL_P(cmp
)) return Qnil
;
1954 static VALUE
rb_mod_initialize_exec(VALUE module
);
1959 * Module.new {|mod| block } -> mod
1961 * Creates a new anonymous module. If a block is given, it is passed
1962 * the module object, and the block is evaluated in the context of this
1963 * module like #module_eval.
1965 * fred = Module.new do
1974 * a.extend(fred) #=> "my string"
1975 * a.meth1 #=> "hello"
1978 * Assign the module to a constant (name starting uppercase) if you
1979 * want to treat it like a regular module.
1983 rb_mod_initialize(VALUE module
)
1985 return rb_mod_initialize_exec(module
);
1989 rb_mod_initialize_exec(VALUE module
)
1991 if (rb_block_given_p()) {
1992 rb_mod_module_exec(1, &module
, module
);
1999 rb_mod_initialize_clone(int argc
, VALUE
* argv
, VALUE clone
)
2001 VALUE ret
, orig
, opts
;
2002 rb_scan_args(argc
, argv
, "1:", &orig
, &opts
);
2003 ret
= rb_obj_init_clone(argc
, argv
, clone
);
2004 if (OBJ_FROZEN(orig
))
2005 rb_class_name(clone
);
2011 * Class.new(super_class=Object) -> a_class
2012 * Class.new(super_class=Object) { |mod| ... } -> a_class
2014 * Creates a new anonymous (unnamed) class with the given superclass
2015 * (or Object if no parameter is given). You can give a
2016 * class a name by assigning the class object to a constant.
2018 * If a block is given, it is passed the class object, and the block
2019 * is evaluated in the context of this class like
2022 * fred = Class.new do
2031 * a = fred.new #=> #<#<Class:0x100381890>:0x100376b98>
2032 * a.meth1 #=> "hello"
2035 * Assign the class to a constant (name starting uppercase) if you
2036 * want to treat it like a regular class.
2040 rb_class_initialize(int argc
, VALUE
*argv
, VALUE klass
)
2044 if (RCLASS_SUPER(klass
) != 0 || klass
== rb_cBasicObject
) {
2045 rb_raise(rb_eTypeError
, "already initialized class");
2047 if (rb_check_arity(argc
, 0, 1) == 0) {
2052 rb_check_inheritable(super
);
2053 if (super
!= rb_cBasicObject
&& !RCLASS_SUPER(super
)) {
2054 rb_raise(rb_eTypeError
, "can't inherit uninitialized class");
2057 RCLASS_SET_SUPER(klass
, super
);
2058 rb_make_metaclass(klass
, RBASIC(super
)->klass
);
2059 rb_class_inherited(super
, klass
);
2060 rb_mod_initialize_exec(klass
);
2067 rb_undefined_alloc(VALUE klass
)
2069 rb_raise(rb_eTypeError
, "allocator undefined for %"PRIsVALUE
,
2073 static rb_alloc_func_t
class_get_alloc_func(VALUE klass
);
2074 static VALUE
class_call_alloc_func(rb_alloc_func_t allocator
, VALUE klass
);
2078 * class.allocate() -> obj
2080 * Allocates space for a new object of <i>class</i>'s class and does not
2081 * call initialize on the new instance. The returned object must be an
2082 * instance of <i>class</i>.
2084 * klass = Class.new do
2085 * def initialize(*args)
2086 * @initialized = true
2090 * @initialized || false
2094 * klass.allocate.initialized? #=> false
2099 rb_class_alloc_m(VALUE klass
)
2101 rb_alloc_func_t allocator
= class_get_alloc_func(klass
);
2102 if (!rb_obj_respond_to(klass
, rb_intern("allocate"), 1)) {
2103 rb_raise(rb_eTypeError
, "calling %"PRIsVALUE
".allocate is prohibited",
2106 return class_call_alloc_func(allocator
, klass
);
2110 rb_class_alloc(VALUE klass
)
2112 rb_alloc_func_t allocator
= class_get_alloc_func(klass
);
2113 return class_call_alloc_func(allocator
, klass
);
2116 static rb_alloc_func_t
2117 class_get_alloc_func(VALUE klass
)
2119 rb_alloc_func_t allocator
;
2121 if (RCLASS_SUPER(klass
) == 0 && klass
!= rb_cBasicObject
) {
2122 rb_raise(rb_eTypeError
, "can't instantiate uninitialized class");
2124 if (RCLASS_SINGLETON_P(klass
)) {
2125 rb_raise(rb_eTypeError
, "can't create instance of singleton class");
2127 allocator
= rb_get_alloc_func(klass
);
2129 rb_undefined_alloc(klass
);
2135 class_call_alloc_func(rb_alloc_func_t allocator
, VALUE klass
)
2139 RUBY_DTRACE_CREATE_HOOK(OBJECT
, rb_class2name(klass
));
2141 obj
= (*allocator
)(klass
);
2143 if (rb_obj_class(obj
) != rb_class_real(klass
)) {
2144 rb_raise(rb_eTypeError
, "wrong instance allocation");
2150 rb_obj_alloc(VALUE klass
)
2152 Check_Type(klass
, T_CLASS
);
2153 return rb_class_alloc(klass
);
2158 * class.new(args, ...) -> obj
2160 * Calls #allocate to create a new object of <i>class</i>'s class,
2161 * then invokes that object's #initialize method, passing it
2162 * <i>args</i>. This is the method that ends up getting called
2163 * whenever an object is constructed using <code>.new</code>.
2168 rb_class_new_instance_pass_kw(int argc
, const VALUE
*argv
, VALUE klass
)
2172 obj
= rb_class_alloc(klass
);
2173 rb_obj_call_init_kw(obj
, argc
, argv
, RB_PASS_CALLED_KEYWORDS
);
2179 rb_class_new_instance_kw(int argc
, const VALUE
*argv
, VALUE klass
, int kw_splat
)
2182 Check_Type(klass
, T_CLASS
);
2184 obj
= rb_class_alloc(klass
);
2185 rb_obj_call_init_kw(obj
, argc
, argv
, kw_splat
);
2191 rb_class_new_instance(int argc
, const VALUE
*argv
, VALUE klass
)
2193 return rb_class_new_instance_kw(argc
, argv
, klass
, RB_NO_KEYWORDS
);
2198 * class.superclass -> a_super_class or nil
2200 * Returns the superclass of <i>class</i>, or <code>nil</code>.
2202 * File.superclass #=> IO
2203 * IO.superclass #=> Object
2204 * Object.superclass #=> BasicObject
2206 * class Bar < Foo; end
2207 * Bar.superclass #=> Foo
2209 * Returns nil when the given class does not have a parent class:
2211 * BasicObject.superclass #=> nil
2214 * Returns the superclass of `klass`. Equivalent to `Class#superclass` in Ruby.
2217 * @param[in] klass a Class object
2218 * @return the superclass, or `Qnil` if `klass` does not have a parent class.
2219 * @sa rb_class_get_superclass
2224 rb_class_superclass(VALUE klass
)
2226 RUBY_ASSERT(RB_TYPE_P(klass
, T_CLASS
));
2228 VALUE super
= RCLASS_SUPER(klass
);
2231 if (klass
== rb_cBasicObject
) return Qnil
;
2232 rb_raise(rb_eTypeError
, "uninitialized class");
2235 if (!RCLASS_SUPERCLASS_DEPTH(klass
)) {
2239 super
= RCLASS_SUPERCLASSES(klass
)[RCLASS_SUPERCLASS_DEPTH(klass
) - 1];
2240 RUBY_ASSERT(RB_TYPE_P(klass
, T_CLASS
));
2246 rb_class_get_superclass(VALUE klass
)
2248 return RCLASS(klass
)->super
;
2251 static const char bad_instance_name
[] = "'%1$s' is not allowed as an instance variable name";
2252 static const char bad_class_name
[] = "'%1$s' is not allowed as a class variable name";
2253 static const char bad_const_name
[] = "wrong constant name %1$s";
2254 static const char bad_attr_name
[] = "invalid attribute name '%1$s'";
2255 #define wrong_constant_name bad_const_name
2258 #define id_for_var(obj, name, type) id_for_setter(obj, name, type, bad_##type##_name)
2260 #define id_for_setter(obj, name, type, message) \
2261 check_setter_id(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message))
2263 check_setter_id(VALUE obj
, VALUE
*pname
,
2264 int (*valid_id_p
)(ID
), int (*valid_name_p
)(VALUE
),
2265 const char *message
, size_t message_len
)
2267 ID id
= rb_check_id(pname
);
2268 VALUE name
= *pname
;
2270 if (id
? !valid_id_p(id
) : !valid_name_p(name
)) {
2271 rb_name_err_raise_str(rb_fstring_new(message
, message_len
),
2278 rb_is_attr_name(VALUE name
)
2280 return rb_is_local_name(name
) || rb_is_const_name(name
);
2284 rb_is_attr_id(ID id
)
2286 return rb_is_local_id(id
) || rb_is_const_id(id
);
2290 id_for_attr(VALUE obj
, VALUE name
)
2292 ID id
= id_for_var(obj
, name
, attr
);
2293 if (!id
) id
= rb_intern_str(name
);
2299 * attr_reader(symbol, ...) -> array
2300 * attr(symbol, ...) -> array
2301 * attr_reader(string, ...) -> array
2302 * attr(string, ...) -> array
2304 * Creates instance variables and corresponding methods that return the
2305 * value of each instance variable. Equivalent to calling
2306 * ``<code>attr</code><i>:name</i>'' on each name in turn.
2307 * String arguments are converted to symbols.
2308 * Returns an array of defined method names as symbols.
2312 rb_mod_attr_reader(int argc
, VALUE
*argv
, VALUE klass
)
2315 VALUE names
= rb_ary_new2(argc
);
2317 for (i
=0; i
<argc
; i
++) {
2318 ID id
= id_for_attr(klass
, argv
[i
]);
2319 rb_attr(klass
, id
, TRUE
, FALSE
, TRUE
);
2320 rb_ary_push(names
, ID2SYM(id
));
2327 * attr(name, ...) -> array
2328 * attr(name, true) -> array
2329 * attr(name, false) -> array
2331 * The first form is equivalent to #attr_reader.
2332 * The second form is equivalent to <code>attr_accessor(name)</code> but deprecated.
2333 * The last form is equivalent to <code>attr_reader(name)</code> but deprecated.
2334 * Returns an array of defined method names as symbols.
2337 * \todo can be static?
2341 rb_mod_attr(int argc
, VALUE
*argv
, VALUE klass
)
2343 if (argc
== 2 && (argv
[1] == Qtrue
|| argv
[1] == Qfalse
)) {
2344 ID id
= id_for_attr(klass
, argv
[0]);
2345 VALUE names
= rb_ary_new();
2347 rb_category_warning(RB_WARN_CATEGORY_DEPRECATED
, "optional boolean argument is obsoleted");
2348 rb_attr(klass
, id
, 1, RTEST(argv
[1]), TRUE
);
2349 rb_ary_push(names
, ID2SYM(id
));
2350 if (argv
[1] == Qtrue
) rb_ary_push(names
, ID2SYM(rb_id_attrset(id
)));
2353 return rb_mod_attr_reader(argc
, argv
, klass
);
2358 * attr_writer(symbol, ...) -> array
2359 * attr_writer(string, ...) -> array
2361 * Creates an accessor method to allow assignment to the attribute
2362 * <i>symbol</i><code>.id2name</code>.
2363 * String arguments are converted to symbols.
2364 * Returns an array of defined method names as symbols.
2368 rb_mod_attr_writer(int argc
, VALUE
*argv
, VALUE klass
)
2371 VALUE names
= rb_ary_new2(argc
);
2373 for (i
=0; i
<argc
; i
++) {
2374 ID id
= id_for_attr(klass
, argv
[i
]);
2375 rb_attr(klass
, id
, FALSE
, TRUE
, TRUE
);
2376 rb_ary_push(names
, ID2SYM(rb_id_attrset(id
)));
2383 * attr_accessor(symbol, ...) -> array
2384 * attr_accessor(string, ...) -> array
2386 * Defines a named attribute for this module, where the name is
2387 * <i>symbol.</i><code>id2name</code>, creating an instance variable
2388 * (<code>@name</code>) and a corresponding access method to read it.
2389 * Also creates a method called <code>name=</code> to set the attribute.
2390 * String arguments are converted to symbols.
2391 * Returns an array of defined method names as symbols.
2394 * attr_accessor(:one, :two) #=> [:one, :one=, :two, :two=]
2396 * Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
2400 rb_mod_attr_accessor(int argc
, VALUE
*argv
, VALUE klass
)
2403 VALUE names
= rb_ary_new2(argc
* 2);
2405 for (i
=0; i
<argc
; i
++) {
2406 ID id
= id_for_attr(klass
, argv
[i
]);
2408 rb_attr(klass
, id
, TRUE
, TRUE
, TRUE
);
2409 rb_ary_push(names
, ID2SYM(id
));
2410 rb_ary_push(names
, ID2SYM(rb_id_attrset(id
)));
2417 * mod.const_get(sym, inherit=true) -> obj
2418 * mod.const_get(str, inherit=true) -> obj
2420 * Checks for a constant with the given name in <i>mod</i>.
2421 * If +inherit+ is set, the lookup will also search
2422 * the ancestors (and +Object+ if <i>mod</i> is a +Module+).
2424 * The value of the constant is returned if a definition is found,
2425 * otherwise a +NameError+ is raised.
2427 * Math.const_get(:PI) #=> 3.14159265358979
2429 * This method will recursively look up constant names if a namespaced
2430 * class name is provided. For example:
2432 * module Foo; class Bar; end end
2433 * Object.const_get 'Foo::Bar'
2435 * The +inherit+ flag is respected on each lookup. For example:
2442 * class Baz < Bar; end
2445 * Object.const_get 'Foo::Baz::VAL' # => 10
2446 * Object.const_get 'Foo::Baz::VAL', false # => NameError
2448 * If the argument is not a valid constant name a +NameError+ will be
2449 * raised with a warning "wrong constant name".
2451 * Object.const_get 'foobar' #=> NameError: wrong constant name foobar
2456 rb_mod_const_get(int argc
, VALUE
*argv
, VALUE mod
)
2460 const char *pbeg
, *p
, *path
, *pend
;
2463 rb_check_arity(argc
, 1, 2);
2465 recur
= (argc
== 1) ? Qtrue
: argv
[1];
2467 if (SYMBOL_P(name
)) {
2468 if (!rb_is_const_sym(name
)) goto wrong_name
;
2469 id
= rb_check_id(&name
);
2470 if (!id
) return rb_const_missing(mod
, name
);
2471 return RTEST(recur
) ? rb_const_get(mod
, id
) : rb_const_get_at(mod
, id
);
2474 path
= StringValuePtr(name
);
2475 enc
= rb_enc_get(name
);
2477 if (!rb_enc_asciicompat(enc
)) {
2478 rb_raise(rb_eArgError
, "invalid class path encoding (non ASCII)");
2482 pend
= path
+ RSTRING_LEN(name
);
2484 if (p
>= pend
|| !*p
) {
2488 if (p
+ 2 < pend
&& p
[0] == ':' && p
[1] == ':') {
2498 while (p
< pend
&& *p
!= ':') p
++;
2500 if (pbeg
== p
) goto wrong_name
;
2502 id
= rb_check_id_cstr(pbeg
, len
= p
-pbeg
, enc
);
2505 if (p
< pend
&& p
[0] == ':') {
2506 if (p
+ 2 >= pend
|| p
[1] != ':') goto wrong_name
;
2511 if (!RB_TYPE_P(mod
, T_MODULE
) && !RB_TYPE_P(mod
, T_CLASS
)) {
2512 rb_raise(rb_eTypeError
, "%"PRIsVALUE
" does not refer to class/module",
2517 part
= rb_str_subseq(name
, beglen
, len
);
2519 if (!rb_is_const_name(part
)) {
2523 else if (!rb_method_basic_definition_p(CLASS_OF(mod
), id_const_missing
)) {
2524 part
= rb_str_intern(part
);
2525 mod
= rb_const_missing(mod
, part
);
2529 rb_mod_const_missing(mod
, part
);
2532 if (!rb_is_const_id(id
)) {
2537 mod
= rb_const_get_0(mod
, id
, beglen
> 0 || !RTEST(recur
), RTEST(recur
), FALSE
);
2539 if (!RTEST(recur
)) {
2540 mod
= rb_const_get_at(mod
, id
);
2542 else if (beglen
== 0) {
2543 mod
= rb_const_get(mod
, id
);
2546 mod
= rb_const_get_from(mod
, id
);
2554 rb_name_err_raise(wrong_constant_name
, mod
, name
);
2555 UNREACHABLE_RETURN(Qundef
);
2560 * mod.const_set(sym, obj) -> obj
2561 * mod.const_set(str, obj) -> obj
2563 * Sets the named constant to the given object, returning that object.
2564 * Creates a new constant if no constant with the given name previously
2567 * Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714
2568 * Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968
2570 * If +sym+ or +str+ is not a valid constant name a +NameError+ will be
2571 * raised with a warning "wrong constant name".
2573 * Object.const_set('foobar', 42) #=> NameError: wrong constant name foobar
2578 rb_mod_const_set(VALUE mod
, VALUE name
, VALUE value
)
2580 ID id
= id_for_var(mod
, name
, const);
2581 if (!id
) id
= rb_intern_str(name
);
2582 rb_const_set(mod
, id
, value
);
2589 * mod.const_defined?(sym, inherit=true) -> true or false
2590 * mod.const_defined?(str, inherit=true) -> true or false
2592 * Says whether _mod_ or its ancestors have a constant with the given name:
2594 * Float.const_defined?(:EPSILON) #=> true, found in Float itself
2595 * Float.const_defined?("String") #=> true, found in Object (ancestor)
2596 * BasicObject.const_defined?(:Hash) #=> false
2598 * If _mod_ is a +Module+, additionally +Object+ and its ancestors are checked:
2600 * Math.const_defined?(:String) #=> true, found in Object
2602 * In each of the checked classes or modules, if the constant is not present
2603 * but there is an autoload for it, +true+ is returned directly without
2607 * autoload :User, 'admin/user'
2609 * Admin.const_defined?(:User) #=> true
2611 * If the constant is not found the callback +const_missing+ is *not* called
2612 * and the method returns +false+.
2614 * If +inherit+ is false, the lookup only checks the constants in the receiver:
2616 * IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor)
2617 * IO.const_defined?(:SYNC, false) #=> false, not found in IO itself
2619 * In this case, the same logic for autoloading applies.
2621 * If the argument is not a valid constant name a +NameError+ is raised with the
2622 * message "wrong constant name _name_":
2624 * Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar
2629 rb_mod_const_defined(int argc
, VALUE
*argv
, VALUE mod
)
2633 const char *pbeg
, *p
, *path
, *pend
;
2636 rb_check_arity(argc
, 1, 2);
2638 recur
= (argc
== 1) ? Qtrue
: argv
[1];
2640 if (SYMBOL_P(name
)) {
2641 if (!rb_is_const_sym(name
)) goto wrong_name
;
2642 id
= rb_check_id(&name
);
2643 if (!id
) return Qfalse
;
2644 return RTEST(recur
) ? rb_const_defined(mod
, id
) : rb_const_defined_at(mod
, id
);
2647 path
= StringValuePtr(name
);
2648 enc
= rb_enc_get(name
);
2650 if (!rb_enc_asciicompat(enc
)) {
2651 rb_raise(rb_eArgError
, "invalid class path encoding (non ASCII)");
2655 pend
= path
+ RSTRING_LEN(name
);
2657 if (p
>= pend
|| !*p
) {
2661 if (p
+ 2 < pend
&& p
[0] == ':' && p
[1] == ':') {
2671 while (p
< pend
&& *p
!= ':') p
++;
2673 if (pbeg
== p
) goto wrong_name
;
2675 id
= rb_check_id_cstr(pbeg
, len
= p
-pbeg
, enc
);
2678 if (p
< pend
&& p
[0] == ':') {
2679 if (p
+ 2 >= pend
|| p
[1] != ':') goto wrong_name
;
2685 part
= rb_str_subseq(name
, beglen
, len
);
2687 if (!rb_is_const_name(part
)) {
2695 if (!rb_is_const_id(id
)) {
2701 mod
= rb_const_search(mod
, id
, beglen
> 0 || !RTEST(recur
), RTEST(recur
), FALSE
);
2702 if (UNDEF_P(mod
)) return Qfalse
;
2704 if (!RTEST(recur
)) {
2705 if (!rb_const_defined_at(mod
, id
))
2707 if (p
== pend
) return Qtrue
;
2708 mod
= rb_const_get_at(mod
, id
);
2710 else if (beglen
== 0) {
2711 if (!rb_const_defined(mod
, id
))
2713 if (p
== pend
) return Qtrue
;
2714 mod
= rb_const_get(mod
, id
);
2717 if (!rb_const_defined_from(mod
, id
))
2719 if (p
== pend
) return Qtrue
;
2720 mod
= rb_const_get_from(mod
, id
);
2724 if (p
< pend
&& !RB_TYPE_P(mod
, T_MODULE
) && !RB_TYPE_P(mod
, T_CLASS
)) {
2725 rb_raise(rb_eTypeError
, "%"PRIsVALUE
" does not refer to class/module",
2733 rb_name_err_raise(wrong_constant_name
, mod
, name
);
2734 UNREACHABLE_RETURN(Qundef
);
2739 * mod.const_source_location(sym, inherit=true) -> [String, Integer]
2740 * mod.const_source_location(str, inherit=true) -> [String, Integer]
2742 * Returns the Ruby source filename and line number containing the definition
2743 * of the constant specified. If the named constant is not found, +nil+ is returned.
2744 * If the constant is found, but its source location can not be extracted
2745 * (constant is defined in C code), empty array is returned.
2747 * _inherit_ specifies whether to lookup in <code>mod.ancestors</code> (+true+
2760 * class B < A # line 10
2765 * class A # continuation of A definition
2766 * C2 = 8 # constant redefinition; warned yet allowed
2769 * p B.const_source_location('C4') # => ["test.rb", 12]
2770 * p B.const_source_location('C3') # => ["test.rb", 7]
2771 * p B.const_source_location('C1') # => ["test.rb", 2]
2773 * p B.const_source_location('C3', false) # => nil -- don't lookup in ancestors
2775 * p A.const_source_location('C2') # => ["test.rb", 16] -- actual (last) definition place
2777 * p Object.const_source_location('B') # => ["test.rb", 10] -- top-level constant could be looked through Object
2778 * p Object.const_source_location('A') # => ["test.rb", 1] -- class reopening is NOT considered new definition
2780 * p B.const_source_location('A') # => ["test.rb", 1] -- because Object is in ancestors
2781 * p M.const_source_location('A') # => ["test.rb", 1] -- Object is not ancestor, but additionally checked for modules
2783 * p Object.const_source_location('A::C1') # => ["test.rb", 2] -- nesting is supported
2784 * p Object.const_source_location('String') # => [] -- constant is defined in C code
2789 rb_mod_const_source_location(int argc
, VALUE
*argv
, VALUE mod
)
2791 VALUE name
, recur
, loc
= Qnil
;
2793 const char *pbeg
, *p
, *path
, *pend
;
2796 rb_check_arity(argc
, 1, 2);
2798 recur
= (argc
== 1) ? Qtrue
: argv
[1];
2800 if (SYMBOL_P(name
)) {
2801 if (!rb_is_const_sym(name
)) goto wrong_name
;
2802 id
= rb_check_id(&name
);
2803 if (!id
) return Qnil
;
2804 return RTEST(recur
) ? rb_const_source_location(mod
, id
) : rb_const_source_location_at(mod
, id
);
2807 path
= StringValuePtr(name
);
2808 enc
= rb_enc_get(name
);
2810 if (!rb_enc_asciicompat(enc
)) {
2811 rb_raise(rb_eArgError
, "invalid class path encoding (non ASCII)");
2815 pend
= path
+ RSTRING_LEN(name
);
2817 if (p
>= pend
|| !*p
) {
2821 if (p
+ 2 < pend
&& p
[0] == ':' && p
[1] == ':') {
2831 while (p
< pend
&& *p
!= ':') p
++;
2833 if (pbeg
== p
) goto wrong_name
;
2835 id
= rb_check_id_cstr(pbeg
, len
= p
-pbeg
, enc
);
2838 if (p
< pend
&& p
[0] == ':') {
2839 if (p
+ 2 >= pend
|| p
[1] != ':') goto wrong_name
;
2845 part
= rb_str_subseq(name
, beglen
, len
);
2847 if (!rb_is_const_name(part
)) {
2855 if (!rb_is_const_id(id
)) {
2861 mod
= rb_const_get(mod
, id
);
2864 mod
= rb_const_get_at(mod
, id
);
2866 if (!RB_TYPE_P(mod
, T_MODULE
) && !RB_TYPE_P(mod
, T_CLASS
)) {
2867 rb_raise(rb_eTypeError
, "%"PRIsVALUE
" does not refer to class/module",
2873 loc
= rb_const_source_location(mod
, id
);
2876 loc
= rb_const_source_location_at(mod
, id
);
2886 rb_name_err_raise(wrong_constant_name
, mod
, name
);
2887 UNREACHABLE_RETURN(Qundef
);
2892 * obj.instance_variable_get(symbol) -> obj
2893 * obj.instance_variable_get(string) -> obj
2895 * Returns the value of the given instance variable, or nil if the
2896 * instance variable is not set. The <code>@</code> part of the
2897 * variable name should be included for regular instance
2898 * variables. Throws a NameError exception if the
2899 * supplied symbol is not valid as an instance variable name.
2900 * String arguments are converted to symbols.
2903 * def initialize(p1, p2)
2907 * fred = Fred.new('cat', 99)
2908 * fred.instance_variable_get(:@a) #=> "cat"
2909 * fred.instance_variable_get("@b") #=> 99
2913 rb_obj_ivar_get(VALUE obj
, VALUE iv
)
2915 ID id
= id_for_var(obj
, iv
, instance
);
2920 return rb_ivar_get(obj
, id
);
2925 * obj.instance_variable_set(symbol, obj) -> obj
2926 * obj.instance_variable_set(string, obj) -> obj
2928 * Sets the instance variable named by <i>symbol</i> to the given
2929 * object. This may circumvent the encapsulation intended by
2930 * the author of the class, so it should be used with care.
2931 * The variable does not have to exist prior to this call.
2932 * If the instance variable name is passed as a string, that string
2933 * is converted to a symbol.
2936 * def initialize(p1, p2)
2940 * fred = Fred.new('cat', 99)
2941 * fred.instance_variable_set(:@a, 'dog') #=> "dog"
2942 * fred.instance_variable_set(:@c, 'cat') #=> "cat"
2943 * fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
2947 rb_obj_ivar_set_m(VALUE obj
, VALUE iv
, VALUE val
)
2949 ID id
= id_for_var(obj
, iv
, instance
);
2950 if (!id
) id
= rb_intern_str(iv
);
2951 return rb_ivar_set(obj
, id
, val
);
2956 * obj.instance_variable_defined?(symbol) -> true or false
2957 * obj.instance_variable_defined?(string) -> true or false
2959 * Returns <code>true</code> if the given instance variable is
2960 * defined in <i>obj</i>.
2961 * String arguments are converted to symbols.
2964 * def initialize(p1, p2)
2968 * fred = Fred.new('cat', 99)
2969 * fred.instance_variable_defined?(:@a) #=> true
2970 * fred.instance_variable_defined?("@b") #=> true
2971 * fred.instance_variable_defined?("@c") #=> false
2975 rb_obj_ivar_defined(VALUE obj
, VALUE iv
)
2977 ID id
= id_for_var(obj
, iv
, instance
);
2982 return rb_ivar_defined(obj
, id
);
2987 * mod.class_variable_get(symbol) -> obj
2988 * mod.class_variable_get(string) -> obj
2990 * Returns the value of the given class variable (or throws a
2991 * NameError exception). The <code>@@</code> part of the
2992 * variable name should be included for regular class variables.
2993 * String arguments are converted to symbols.
2998 * Fred.class_variable_get(:@@foo) #=> 99
3002 rb_mod_cvar_get(VALUE obj
, VALUE iv
)
3004 ID id
= id_for_var(obj
, iv
, class);
3007 rb_name_err_raise("uninitialized class variable %1$s in %2$s",
3010 return rb_cvar_get(obj
, id
);
3015 * obj.class_variable_set(symbol, obj) -> obj
3016 * obj.class_variable_set(string, obj) -> obj
3018 * Sets the class variable named by <i>symbol</i> to the given
3020 * If the class variable name is passed as a string, that string
3021 * is converted to a symbol.
3029 * Fred.class_variable_set(:@@foo, 101) #=> 101
3030 * Fred.new.foo #=> 101
3034 rb_mod_cvar_set(VALUE obj
, VALUE iv
, VALUE val
)
3036 ID id
= id_for_var(obj
, iv
, class);
3037 if (!id
) id
= rb_intern_str(iv
);
3038 rb_cvar_set(obj
, id
, val
);
3044 * obj.class_variable_defined?(symbol) -> true or false
3045 * obj.class_variable_defined?(string) -> true or false
3047 * Returns <code>true</code> if the given class variable is defined
3049 * String arguments are converted to symbols.
3054 * Fred.class_variable_defined?(:@@foo) #=> true
3055 * Fred.class_variable_defined?(:@@bar) #=> false
3059 rb_mod_cvar_defined(VALUE obj
, VALUE iv
)
3061 ID id
= id_for_var(obj
, iv
, class);
3066 return rb_cvar_defined(obj
, id
);
3071 * mod.singleton_class? -> true or false
3073 * Returns <code>true</code> if <i>mod</i> is a singleton class or
3074 * <code>false</code> if it is an ordinary class or module.
3078 * C.singleton_class? #=> false
3079 * C.singleton_class.singleton_class? #=> true
3083 rb_mod_singleton_p(VALUE klass
)
3085 return RBOOL(RCLASS_SINGLETON_P(klass
));
3089 static const struct conv_method_tbl
{
3090 const char method
[6];
3092 } conv_method_names
[] = {
3093 #define M(n) {#n, (unsigned short)idTo_##n}
3108 #define IMPLICIT_CONVERSIONS 7
3111 conv_method_index(const char *method
)
3113 static const char prefix
[] = "to_";
3115 if (strncmp(prefix
, method
, sizeof(prefix
)-1) == 0) {
3116 const char *const meth
= &method
[sizeof(prefix
)-1];
3118 for (i
=0; i
< numberof(conv_method_names
); i
++) {
3119 if (conv_method_names
[i
].method
[0] == meth
[0] &&
3120 strcmp(conv_method_names
[i
].method
, meth
) == 0) {
3125 return numberof(conv_method_names
);
3129 convert_type_with_id(VALUE val
, const char *tname
, ID method
, int raise
, int index
)
3131 VALUE r
= rb_check_funcall(val
, method
, 0, 0);
3135 ((index
< 0 ? conv_method_index(rb_id2name(method
)) : index
)
3136 < IMPLICIT_CONVERSIONS
) ?
3137 "no implicit conversion of" : "can't convert";
3138 const char *cname
= NIL_P(val
) ? "nil" :
3139 val
== Qtrue
? "true" :
3140 val
== Qfalse
? "false" :
3143 rb_raise(rb_eTypeError
, "%s %s into %s", msg
, cname
, tname
);
3144 rb_raise(rb_eTypeError
, "%s %"PRIsVALUE
" into %s", msg
,
3154 convert_type(VALUE val
, const char *tname
, const char *method
, int raise
)
3156 int i
= conv_method_index(method
);
3157 ID m
= i
< numberof(conv_method_names
) ?
3158 conv_method_names
[i
].id
: rb_intern(method
);
3159 return convert_type_with_id(val
, tname
, m
, raise
, i
);
3163 NORETURN(static void conversion_mismatch(VALUE
, const char *, const char *, VALUE
));
3165 conversion_mismatch(VALUE val
, const char *tname
, const char *method
, VALUE result
)
3167 VALUE cname
= rb_obj_class(val
);
3168 rb_raise(rb_eTypeError
,
3169 "can't convert %"PRIsVALUE
" to %s (%"PRIsVALUE
"#%s gives %"PRIsVALUE
")",
3170 cname
, tname
, cname
, method
, rb_obj_class(result
));
3174 rb_convert_type(VALUE val
, int type
, const char *tname
, const char *method
)
3178 if (TYPE(val
) == type
) return val
;
3179 v
= convert_type(val
, tname
, method
, TRUE
);
3180 if (TYPE(v
) != type
) {
3181 conversion_mismatch(val
, tname
, method
, v
);
3188 rb_convert_type_with_id(VALUE val
, int type
, const char *tname
, ID method
)
3192 if (TYPE(val
) == type
) return val
;
3193 v
= convert_type_with_id(val
, tname
, method
, TRUE
, -1);
3194 if (TYPE(v
) != type
) {
3195 conversion_mismatch(val
, tname
, RSTRING_PTR(rb_id2str(method
)), v
);
3201 rb_check_convert_type(VALUE val
, int type
, const char *tname
, const char *method
)
3205 /* always convert T_DATA */
3206 if (TYPE(val
) == type
&& type
!= T_DATA
) return val
;
3207 v
= convert_type(val
, tname
, method
, FALSE
);
3208 if (NIL_P(v
)) return Qnil
;
3209 if (TYPE(v
) != type
) {
3210 conversion_mismatch(val
, tname
, method
, v
);
3217 rb_check_convert_type_with_id(VALUE val
, int type
, const char *tname
, ID method
)
3221 /* always convert T_DATA */
3222 if (TYPE(val
) == type
&& type
!= T_DATA
) return val
;
3223 v
= convert_type_with_id(val
, tname
, method
, FALSE
, -1);
3224 if (NIL_P(v
)) return Qnil
;
3225 if (TYPE(v
) != type
) {
3226 conversion_mismatch(val
, tname
, RSTRING_PTR(rb_id2str(method
)), v
);
3231 #define try_to_int(val, mid, raise) \
3232 convert_type_with_id(val, "Integer", mid, raise, -1)
3234 ALWAYS_INLINE(static VALUE
rb_to_integer_with_id_exception(VALUE val
, const char *method
, ID mid
, int raise
));
3235 /* Integer specific rb_check_convert_type_with_id */
3237 rb_to_integer_with_id_exception(VALUE val
, const char *method
, ID mid
, int raise
)
3239 // We need to pop the lazily pushed frame when not raising an exception.
3240 rb_control_frame_t
*current_cfp
;
3243 if (RB_INTEGER_TYPE_P(val
)) return val
;
3244 current_cfp
= GET_EC()->cfp
;
3245 rb_yjit_lazy_push_frame(GET_EC()->cfp
->pc
);
3246 v
= try_to_int(val
, mid
, raise
);
3247 if (!raise
&& NIL_P(v
)) {
3248 GET_EC()->cfp
= current_cfp
;
3251 if (!RB_INTEGER_TYPE_P(v
)) {
3252 conversion_mismatch(val
, "Integer", method
, v
);
3254 GET_EC()->cfp
= current_cfp
;
3257 #define rb_to_integer(val, method, mid) \
3258 rb_to_integer_with_id_exception(val, method, mid, TRUE)
3261 rb_check_to_integer(VALUE val
, const char *method
)
3265 if (RB_INTEGER_TYPE_P(val
)) return val
;
3266 v
= convert_type(val
, "Integer", method
, FALSE
);
3267 if (!RB_INTEGER_TYPE_P(v
)) {
3274 rb_to_int(VALUE val
)
3276 return rb_to_integer(val
, "to_int", idTo_int
);
3280 rb_check_to_int(VALUE val
)
3282 if (RB_INTEGER_TYPE_P(val
)) return val
;
3283 val
= try_to_int(val
, idTo_int
, FALSE
);
3284 if (RB_INTEGER_TYPE_P(val
)) return val
;
3289 rb_check_to_i(VALUE val
)
3291 if (RB_INTEGER_TYPE_P(val
)) return val
;
3292 val
= try_to_int(val
, idTo_i
, FALSE
);
3293 if (RB_INTEGER_TYPE_P(val
)) return val
;
3298 rb_convert_to_integer(VALUE val
, int base
, int raise_exception
)
3303 tmp
= rb_check_string_type(val
);
3308 else if (! raise_exception
) {
3312 rb_raise(rb_eArgError
, "base specified for non string value");
3315 if (RB_FLOAT_TYPE_P(val
)) {
3316 double f
= RFLOAT_VALUE(val
);
3317 if (!raise_exception
&& !isfinite(f
)) return Qnil
;
3318 if (FIXABLE(f
)) return LONG2FIX((long)f
);
3319 return rb_dbl2big(f
);
3321 else if (RB_INTEGER_TYPE_P(val
)) {
3324 else if (RB_TYPE_P(val
, T_STRING
)) {
3325 return rb_str_convert_to_inum(val
, base
, TRUE
, raise_exception
);
3327 else if (NIL_P(val
)) {
3328 if (!raise_exception
) return Qnil
;
3329 rb_raise(rb_eTypeError
, "can't convert nil into Integer");
3332 tmp
= rb_protect(rb_check_to_int
, val
, NULL
);
3333 if (RB_INTEGER_TYPE_P(tmp
)) return tmp
;
3334 rb_set_errinfo(Qnil
);
3335 if (!NIL_P(tmp
= rb_check_string_type(val
))) {
3336 return rb_str_convert_to_inum(tmp
, base
, TRUE
, raise_exception
);
3339 if (!raise_exception
) {
3340 VALUE result
= rb_protect(rb_check_to_i
, val
, NULL
);
3341 rb_set_errinfo(Qnil
);
3345 return rb_to_integer(val
, "to_i", idTo_i
);
3349 rb_Integer(VALUE val
)
3351 return rb_convert_to_integer(val
, 0, TRUE
);
3355 rb_check_integer_type(VALUE val
)
3357 return rb_to_integer_with_id_exception(val
, "to_int", idTo_int
, FALSE
);
3361 rb_bool_expected(VALUE obj
, const char *flagname
, int raise
)
3369 static const char message
[] = "expected true or false as %s: %+"PRIsVALUE
;
3371 rb_raise(rb_eArgError
, message
, flagname
, obj
);
3373 rb_warning(message
, flagname
, obj
);
3380 rb_opts_exception_p(VALUE opts
, int default_value
)
3382 static const ID kwds
[1] = {idException
};
3384 if (rb_get_kwargs(opts
, kwds
, 0, 1, &exception
))
3385 return rb_bool_expected(exception
, "exception", TRUE
);
3386 return default_value
;
3390 rb_f_integer1(rb_execution_context_t
*ec
, VALUE obj
, VALUE arg
)
3392 return rb_convert_to_integer(arg
, 0, TRUE
);
3396 rb_f_integer(rb_execution_context_t
*ec
, VALUE obj
, VALUE arg
, VALUE base
, VALUE exception
)
3398 int exc
= rb_bool_expected(exception
, "exception", TRUE
);
3399 return rb_convert_to_integer(arg
, NUM2INT(base
), exc
);
3403 rb_cstr_to_dbl_raise(const char *p
, int badcheck
, int raise
, int *error
)
3408 const char *ellipsis
= "";
3410 enum {max_width
= 20};
3411 #define OutOfRange() ((end - p > max_width) ? \
3412 (w = max_width, ellipsis = "...") : \
3413 (w = (int)(end - p), ellipsis = ""))
3417 while (ISSPACE(*p
)) p
++;
3419 if (!badcheck
&& p
[0] == '0' && (p
[1] == 'x' || p
[1] == 'X')) {
3423 d
= strtod(p
, &end
);
3424 if (errno
== ERANGE
) {
3426 rb_warning("Float %.*s%s out of range", w
, p
, ellipsis
);
3436 char buf
[DBL_DIG
* 4 + 10];
3438 char *const init_e
= buf
+ DBL_DIG
* 4;
3441 int dot_seen
= FALSE
;
3443 switch (*p
) {case '+': case '-': prev
= *n
++ = *p
++;}
3446 while (*++p
== '0');
3448 while (p
< end
&& n
< e
) prev
= *n
++ = *p
++;
3451 /* remove an underscore between digits */
3452 if (n
== buf
|| !ISDIGIT(prev
) || (++p
, !ISDIGIT(*p
))) {
3453 if (badcheck
) goto bad
;
3458 if (e
== init_e
&& (prev
== 'e' || prev
== 'E' || prev
== 'p' || prev
== 'P')) {
3459 e
= buf
+ sizeof(buf
) - 1;
3461 switch (*p
) {case '+': case '-': prev
= *n
++ = *p
++;}
3464 while (*++p
== '0');
3468 else if (ISSPACE(prev
)) {
3469 while (ISSPACE(*p
)) ++p
;
3471 if (badcheck
) goto bad
;
3475 else if (prev
== '.' ? dot_seen
++ : !ISDIGIT(prev
)) {
3476 if (badcheck
) goto bad
;
3479 if (n
< e
) *n
++ = prev
;
3484 if (!badcheck
&& p
[0] == '0' && (p
[1] == 'x' || p
[1] == 'X')) {
3488 d
= strtod(p
, &end
);
3489 if (errno
== ERANGE
) {
3491 rb_warning("Float %.*s%s out of range", w
, p
, ellipsis
);
3495 if (!end
|| p
== end
) goto bad
;
3496 while (*end
&& ISSPACE(*end
)) end
++;
3500 if (errno
== ERANGE
) {
3503 rb_raise(rb_eArgError
, "Float %.*s%s out of range", w
, q
, ellipsis
);
3509 rb_invalid_str(q
, "Float()");
3510 UNREACHABLE_RETURN(nan(""));
3513 if (error
) *error
= 1;
3519 rb_cstr_to_dbl(const char *p
, int badcheck
)
3521 return rb_cstr_to_dbl_raise(p
, badcheck
, TRUE
, NULL
);
3525 rb_str_to_dbl_raise(VALUE str
, int badcheck
, int raise
, int *error
)
3533 s
= RSTRING_PTR(str
);
3534 len
= RSTRING_LEN(str
);
3536 if (badcheck
&& memchr(s
, '\0', len
)) {
3538 rb_raise(rb_eArgError
, "string for Float contains null byte");
3540 if (error
) *error
= 1;
3544 if (s
[len
]) { /* no sentinel somehow */
3545 char *p
= ALLOCV(v
, (size_t)len
+ 1);
3546 MEMCPY(p
, s
, char, len
);
3551 ret
= rb_cstr_to_dbl_raise(s
, badcheck
, raise
, error
);
3557 FUNC_MINIMIZED(double rb_str_to_dbl(VALUE str
, int badcheck
));
3560 rb_str_to_dbl(VALUE str
, int badcheck
)
3562 return rb_str_to_dbl_raise(str
, badcheck
, TRUE
, NULL
);
3565 /*! \cond INTERNAL_MACRO */
3566 #define fix2dbl_without_to_f(x) (double)FIX2LONG(x)
3567 #define big2dbl_without_to_f(x) rb_big2dbl(x)
3568 #define int2dbl_without_to_f(x) \
3569 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : big2dbl_without_to_f(x))
3570 #define num2dbl_without_to_f(x) \
3571 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : \
3572 RB_BIGNUM_TYPE_P(x) ? big2dbl_without_to_f(x) : \
3573 (Check_Type(x, T_FLOAT), RFLOAT_VALUE(x)))
3574 static inline double
3575 rat2dbl_without_to_f(VALUE x
)
3577 VALUE num
= rb_rational_num(x
);
3578 VALUE den
= rb_rational_den(x
);
3579 return num2dbl_without_to_f(num
) / num2dbl_without_to_f(den
);
3582 #define special_const_to_float(val, pre, post) \
3585 rb_raise_static(rb_eTypeError, pre "nil" post); \
3587 rb_raise_static(rb_eTypeError, pre "true" post); \
3589 rb_raise_static(rb_eTypeError, pre "false" post); \
3594 conversion_to_float(VALUE val
)
3596 special_const_to_float(val
, "can't convert ", " into Float");
3600 implicit_conversion_to_float(VALUE val
)
3602 special_const_to_float(val
, "no implicit conversion to float from ", "");
3606 to_float(VALUE
*valp
, int raise_exception
)
3609 if (SPECIAL_CONST_P(val
)) {
3610 if (FIXNUM_P(val
)) {
3611 *valp
= DBL2NUM(fix2dbl_without_to_f(val
));
3614 else if (FLONUM_P(val
)) {
3617 else if (raise_exception
) {
3618 conversion_to_float(val
);
3622 int type
= BUILTIN_TYPE(val
);
3627 *valp
= DBL2NUM(big2dbl_without_to_f(val
));
3630 *valp
= DBL2NUM(rat2dbl_without_to_f(val
));
3640 convert_type_to_float_protected(VALUE val
)
3642 return rb_convert_type_with_id(val
, T_FLOAT
, "Float", id_to_f
);
3646 rb_convert_to_float(VALUE val
, int raise_exception
)
3648 switch (to_float(&val
, raise_exception
)) {
3652 if (!raise_exception
) {
3654 double x
= rb_str_to_dbl_raise(val
, TRUE
, raise_exception
, &e
);
3655 return e
? Qnil
: DBL2NUM(x
);
3657 return DBL2NUM(rb_str_to_dbl(val
, TRUE
));
3659 if (SPECIAL_CONST_P(val
) && !raise_exception
)
3663 if (!raise_exception
) {
3665 VALUE result
= rb_protect(convert_type_to_float_protected
, val
, &state
);
3666 if (state
) rb_set_errinfo(Qnil
);
3670 return rb_convert_type_with_id(val
, T_FLOAT
, "Float", id_to_f
);
3673 FUNC_MINIMIZED(VALUE
rb_Float(VALUE val
));
3678 return rb_convert_to_float(val
, TRUE
);
3682 rb_f_float1(rb_execution_context_t
*ec
, VALUE obj
, VALUE arg
)
3684 return rb_convert_to_float(arg
, TRUE
);
3688 rb_f_float(rb_execution_context_t
*ec
, VALUE obj
, VALUE arg
, VALUE opts
)
3690 int exception
= rb_bool_expected(opts
, "exception", TRUE
);
3691 return rb_convert_to_float(arg
, exception
);
3695 numeric_to_float(VALUE val
)
3697 if (!rb_obj_is_kind_of(val
, rb_cNumeric
)) {
3698 rb_raise(rb_eTypeError
, "can't convert %"PRIsVALUE
" into Float",
3701 return rb_convert_type_with_id(val
, T_FLOAT
, "Float", id_to_f
);
3705 rb_to_float(VALUE val
)
3707 switch (to_float(&val
, TRUE
)) {
3711 return numeric_to_float(val
);
3715 rb_check_to_float(VALUE val
)
3717 if (RB_FLOAT_TYPE_P(val
)) return val
;
3718 if (!rb_obj_is_kind_of(val
, rb_cNumeric
)) {
3721 return rb_check_convert_type_with_id(val
, T_FLOAT
, "Float", id_to_f
);
3725 basic_to_f_p(VALUE klass
)
3727 return rb_method_basic_definition_p(klass
, id_to_f
);
3732 rb_num_to_dbl(VALUE val
)
3734 if (SPECIAL_CONST_P(val
)) {
3735 if (FIXNUM_P(val
)) {
3736 if (basic_to_f_p(rb_cInteger
))
3737 return fix2dbl_without_to_f(val
);
3739 else if (FLONUM_P(val
)) {
3740 return rb_float_flonum_value(val
);
3743 conversion_to_float(val
);
3747 switch (BUILTIN_TYPE(val
)) {
3749 return rb_float_noflonum_value(val
);
3751 if (basic_to_f_p(rb_cInteger
))
3752 return big2dbl_without_to_f(val
);
3755 if (basic_to_f_p(rb_cRational
))
3756 return rat2dbl_without_to_f(val
);
3762 val
= numeric_to_float(val
);
3763 return RFLOAT_VALUE(val
);
3767 rb_num2dbl(VALUE val
)
3769 if (SPECIAL_CONST_P(val
)) {
3770 if (FIXNUM_P(val
)) {
3771 return fix2dbl_without_to_f(val
);
3773 else if (FLONUM_P(val
)) {
3774 return rb_float_flonum_value(val
);
3777 implicit_conversion_to_float(val
);
3781 switch (BUILTIN_TYPE(val
)) {
3783 return rb_float_noflonum_value(val
);
3785 return big2dbl_without_to_f(val
);
3787 return rat2dbl_without_to_f(val
);
3789 rb_raise(rb_eTypeError
, "no implicit conversion to float from string");
3794 val
= rb_convert_type_with_id(val
, T_FLOAT
, "Float", id_to_f
);
3795 return RFLOAT_VALUE(val
);
3799 rb_String(VALUE val
)
3801 VALUE tmp
= rb_check_string_type(val
);
3803 tmp
= rb_convert_type_with_id(val
, T_STRING
, "String", idTo_s
);
3810 * String(object) -> object or new_string
3812 * Returns a string converted from +object+.
3814 * Tries to convert +object+ to a string
3815 * using +to_str+ first and +to_s+ second:
3817 * String([0, 1, 2]) # => "[0, 1, 2]"
3818 * String(0..5) # => "0..5"
3819 * String({foo: 0, bar: 1}) # => "{:foo=>0, :bar=>1}"
3821 * Raises +TypeError+ if +object+ cannot be converted to a string.
3825 rb_f_string(VALUE obj
, VALUE arg
)
3827 return rb_String(arg
);
3833 VALUE tmp
= rb_check_array_type(val
);
3836 tmp
= rb_check_to_array(val
);
3838 return rb_ary_new3(1, val
);
3846 * Array(object) -> object or new_array
3848 * Returns an array converted from +object+.
3850 * Tries to convert +object+ to an array
3851 * using +to_ary+ first and +to_a+ second:
3853 * Array([0, 1, 2]) # => [0, 1, 2]
3854 * Array({foo: 0, bar: 1}) # => [[:foo, 0], [:bar, 1]]
3855 * Array(0..4) # => [0, 1, 2, 3, 4]
3857 * Returns +object+ in an array, <tt>[object]</tt>,
3858 * if +object+ cannot be converted:
3860 * Array(:foo) # => [:foo]
3865 rb_f_array(VALUE obj
, VALUE arg
)
3867 return rb_Array(arg
);
3871 * Equivalent to \c Kernel\#Hash in Ruby
3878 if (NIL_P(val
)) return rb_hash_new();
3879 tmp
= rb_check_hash_type(val
);
3881 if (RB_TYPE_P(val
, T_ARRAY
) && RARRAY_LEN(val
) == 0)
3882 return rb_hash_new();
3883 rb_raise(rb_eTypeError
, "can't convert %s into Hash", rb_obj_classname(val
));
3890 * Hash(object) -> object or new_hash
3892 * Returns a hash converted from +object+.
3896 * - A hash, returns +object+.
3897 * - An empty array or +nil+, returns an empty hash.
3899 * - Otherwise, if <tt>object.to_hash</tt> returns a hash, returns that hash.
3900 * - Otherwise, returns TypeError.
3904 * Hash({foo: 0, bar: 1}) # => {:foo=>0, :bar=>1}
3911 rb_f_hash(VALUE obj
, VALUE arg
)
3913 return rb_Hash(arg
);
3925 dig_basic_p(VALUE obj
, struct dig_method
*cache
)
3927 VALUE klass
= RBASIC_CLASS(obj
);
3928 if (klass
!= cache
->klass
) {
3929 cache
->klass
= klass
;
3930 cache
->basic
= rb_method_basic_definition_p(klass
, id_dig
);
3932 return cache
->basic
;
3936 no_dig_method(int found
, VALUE recv
, ID mid
, int argc
, const VALUE
*argv
, VALUE data
)
3939 rb_raise(rb_eTypeError
, "%"PRIsVALUE
" does not have #dig method",
3946 rb_obj_dig(int argc
, VALUE
*argv
, VALUE obj
, VALUE notfound
)
3948 struct dig_method hash
= {Qnil
}, ary
= {Qnil
}, strt
= {Qnil
};
3950 for (; argc
> 0; ++argv
, --argc
) {
3951 if (NIL_P(obj
)) return notfound
;
3952 if (!SPECIAL_CONST_P(obj
)) {
3953 switch (BUILTIN_TYPE(obj
)) {
3955 if (dig_basic_p(obj
, &hash
)) {
3956 obj
= rb_hash_aref(obj
, *argv
);
3961 if (dig_basic_p(obj
, &ary
)) {
3962 obj
= rb_ary_at(obj
, *argv
);
3967 if (dig_basic_p(obj
, &strt
)) {
3968 obj
= rb_struct_lookup(obj
, *argv
);
3976 return rb_check_funcall_with_hook_kw(obj
, id_dig
, argc
, argv
,
3985 * sprintf(format_string *objects) -> string
3987 * Returns the string resulting from formatting +objects+
3988 * into +format_string+.
3990 * For details on +format_string+, see
3991 * {Format Specifications}[rdoc-ref:format_specifications.rdoc].
3995 f_sprintf(int c
, const VALUE
*v
, VALUE _
)
3997 return rb_f_sprintf(c
, v
);
4001 rb_f_loop_size(VALUE self
, VALUE args
, VALUE eobj
)
4003 return DBL2NUM(HUGE_VAL
);
4007 * Document-class: Class
4009 * Classes in Ruby are first-class objects---each is an instance of
4012 * Typically, you create a new class by using:
4015 * # some code describing the class behavior
4018 * When a new class is created, an object of type Class is initialized and
4019 * assigned to a global constant (Name in this case).
4021 * When <code>Name.new</code> is called to create a new object, the
4022 * #new method in Class is run by default.
4023 * This can be demonstrated by overriding #new in Class:
4028 * print "Creating a new ", self.name, "\n"
4038 * <em>produces:</em>
4040 * Creating a new Name
4042 * Classes, modules, and objects are interrelated. In the diagram
4043 * that follows, the vertical arrows represent inheritance, and the
4044 * parentheses metaclasses. All metaclasses are instances
4045 * of the class `Class'.
4048 * BasicObject-----|-->(BasicObject)-------|-...
4051 * Object---------|----->(Object)---------|-...
4054 * +-------+ | +--------+ |
4056 * | Module-|---------|--->(Module)-|-...
4059 * | Class-|---------|---->(Class)-|-...
4063 * obj--->OtherClass---------->(OtherClass)-----------...
4068 /* Document-class: BasicObject
4070 * BasicObject is the parent class of all classes in Ruby. It's an explicit
4073 * BasicObject can be used for creating object hierarchies independent of
4074 * Ruby's object hierarchy, proxy objects like the Delegator class, or other
4075 * uses where namespace pollution from Ruby's methods and classes must be
4078 * To avoid polluting BasicObject for other users an appropriately named
4079 * subclass of BasicObject should be created instead of directly modifying
4082 * class MyObjectSystem < BasicObject
4085 * BasicObject does not include Kernel (for methods like +puts+) and
4086 * BasicObject is outside of the namespace of the standard library so common
4087 * classes will not be found without using a full class path.
4089 * A variety of strategies can be used to provide useful portions of the
4090 * standard library to subclasses of BasicObject. A subclass could
4091 * <code>include Kernel</code> to obtain +puts+, +exit+, etc. A custom
4092 * Kernel-like module could be created and included or delegation can be used
4093 * via #method_missing:
4095 * class MyObjectSystem < BasicObject
4096 * DELEGATE = [:puts, :p]
4098 * def method_missing(name, *args, &block)
4099 * return super unless DELEGATE.include? name
4100 * ::Kernel.send(name, *args, &block)
4103 * def respond_to_missing?(name, include_private = false)
4104 * DELEGATE.include?(name)
4108 * Access to classes and modules from the Ruby standard library can be
4109 * obtained in a BasicObject subclass by referencing the desired constant
4110 * from the root like <code>::File</code> or <code>::Enumerator</code>.
4111 * Like #method_missing, #const_missing can be used to delegate constant
4112 * lookup to +Object+:
4114 * class MyObjectSystem < BasicObject
4115 * def self.const_missing(name)
4116 * ::Object.const_get(name)
4122 * These are the methods defined for \BasicObject:
4124 * - ::new: Returns a new \BasicObject instance.
4125 * - #!: Returns the boolean negation of +self+: +true+ or +false+.
4126 * - #!=: Returns whether +self+ and the given object are _not_ equal.
4127 * - #==: Returns whether +self+ and the given object are equivalent.
4128 * - #__id__: Returns the integer object identifier for +self+.
4129 * - #__send__: Calls the method identified by the given symbol.
4130 * - #equal?: Returns whether +self+ and the given object are the same object.
4131 * - #instance_eval: Evaluates the given string or block in the context of +self+.
4132 * - #instance_exec: Executes the given block in the context of +self+,
4133 * passing the given arguments.
4137 /* Document-class: Object
4139 * Object is the default root of all Ruby objects. Object inherits from
4140 * BasicObject which allows creating alternate object hierarchies. Methods
4141 * on Object are available to all classes unless explicitly overridden.
4143 * Object mixes in the Kernel module, making the built-in kernel functions
4144 * globally accessible. Although the instance methods of Object are defined
4145 * by the Kernel module, we have chosen to document them here for clarity.
4147 * When referencing constants in classes inheriting from Object you do not
4148 * need to use the full namespace. For example, referencing +File+ inside
4149 * +YourClass+ will find the top-level File class.
4151 * In the descriptions of Object's methods, the parameter <i>symbol</i> refers
4152 * to a symbol, which is either a quoted string or a Symbol (such as
4153 * <code>:name</code>).
4157 * First, what's elsewhere. \Class \Object:
4159 * - Inherits from {class BasicObject}[rdoc-ref:BasicObject@What-27s+Here].
4160 * - Includes {module Kernel}[rdoc-ref:Kernel@What-27s+Here].
4162 * Here, class \Object provides methods for:
4164 * - {Querying}[rdoc-ref:Object@Querying]
4165 * - {Instance Variables}[rdoc-ref:Object@Instance+Variables]
4166 * - {Other}[rdoc-ref:Object@Other]
4170 * - #!~: Returns +true+ if +self+ does not match the given object,
4171 * otherwise +false+.
4172 * - #<=>: Returns 0 if +self+ and the given object +object+ are the same
4173 * object, or if <tt>self == object</tt>; otherwise returns +nil+.
4174 * - #===: Implements case equality, effectively the same as calling #==.
4175 * - #eql?: Implements hash equality, effectively the same as calling #==.
4176 * - #kind_of? (aliased as #is_a?): Returns whether given argument is an ancestor
4177 * of the singleton class of +self+.
4178 * - #instance_of?: Returns whether +self+ is an instance of the given class.
4179 * - #instance_variable_defined?: Returns whether the given instance variable
4180 * is defined in +self+.
4181 * - #method: Returns the Method object for the given method in +self+.
4182 * - #methods: Returns an array of symbol names of public and protected methods
4184 * - #nil?: Returns +false+. (Only +nil+ responds +true+ to method <tt>nil?</tt>.)
4185 * - #object_id: Returns an integer corresponding to +self+ that is unique
4186 * for the current process
4187 * - #private_methods: Returns an array of the symbol names
4188 * of the private methods in +self+.
4189 * - #protected_methods: Returns an array of the symbol names
4190 * of the protected methods in +self+.
4191 * - #public_method: Returns the Method object for the given public method in +self+.
4192 * - #public_methods: Returns an array of the symbol names
4193 * of the public methods in +self+.
4194 * - #respond_to?: Returns whether +self+ responds to the given method.
4195 * - #singleton_class: Returns the singleton class of +self+.
4196 * - #singleton_method: Returns the Method object for the given singleton method
4198 * - #singleton_methods: Returns an array of the symbol names
4199 * of the singleton methods in +self+.
4201 * - #define_singleton_method: Defines a singleton method in +self+
4202 * for the given symbol method-name and block or proc.
4203 * - #extend: Includes the given modules in the singleton class of +self+.
4204 * - #public_send: Calls the given public method in +self+ with the given argument.
4205 * - #send: Calls the given method in +self+ with the given argument.
4207 * === Instance Variables
4209 * - #instance_variable_get: Returns the value of the given instance variable
4210 * in +self+, or +nil+ if the instance variable is not set.
4211 * - #instance_variable_set: Sets the value of the given instance variable in +self+
4212 * to the given object.
4213 * - #instance_variables: Returns an array of the symbol names
4214 * of the instance variables in +self+.
4215 * - #remove_instance_variable: Removes the named instance variable from +self+.
4219 * - #clone: Returns a shallow copy of +self+, including singleton class
4221 * - #define_singleton_method: Defines a singleton method in +self+
4222 * for the given symbol method-name and block or proc.
4223 * - #display: Prints +self+ to the given IO stream or <tt>$stdout</tt>.
4224 * - #dup: Returns a shallow unfrozen copy of +self+.
4225 * - #enum_for (aliased as #to_enum): Returns an Enumerator for +self+
4226 * using the using the given method, arguments, and block.
4227 * - #extend: Includes the given modules in the singleton class of +self+.
4228 * - #freeze: Prevents further modifications to +self+.
4229 * - #hash: Returns the integer hash value for +self+.
4230 * - #inspect: Returns a human-readable string representation of +self+.
4231 * - #itself: Returns +self+.
4232 * - #method_missing: Method called when an undefined method is called on +self+.
4233 * - #public_send: Calls the given public method in +self+ with the given argument.
4234 * - #send: Calls the given method in +self+ with the given argument.
4235 * - #to_s: Returns a string representation of +self+.
4242 Init_class_hierarchy();
4245 // teach RDoc about these classes
4246 rb_cBasicObject
= rb_define_class("BasicObject", Qnil
);
4247 rb_cObject
= rb_define_class("Object", rb_cBasicObject
);
4248 rb_cModule
= rb_define_class("Module", rb_cObject
);
4249 rb_cClass
= rb_define_class("Class", rb_cModule
);
4250 rb_cRefinement
= rb_define_class("Refinement", rb_cModule
);
4253 rb_define_private_method(rb_cBasicObject
, "initialize", rb_obj_initialize
, 0);
4254 rb_define_alloc_func(rb_cBasicObject
, rb_class_allocate_instance
);
4255 rb_define_method(rb_cBasicObject
, "==", rb_obj_equal
, 1);
4256 rb_define_method(rb_cBasicObject
, "equal?", rb_obj_equal
, 1);
4257 rb_define_method(rb_cBasicObject
, "!", rb_obj_not
, 0);
4258 rb_define_method(rb_cBasicObject
, "!=", rb_obj_not_equal
, 1);
4260 rb_define_private_method(rb_cBasicObject
, "singleton_method_added", rb_obj_singleton_method_added
, 1);
4261 rb_define_private_method(rb_cBasicObject
, "singleton_method_removed", rb_obj_singleton_method_removed
, 1);
4262 rb_define_private_method(rb_cBasicObject
, "singleton_method_undefined", rb_obj_singleton_method_undefined
, 1);
4264 /* Document-module: Kernel
4266 * The Kernel module is included by class Object, so its methods are
4267 * available in every Ruby object.
4269 * The Kernel instance methods are documented in class Object while the
4270 * module methods are documented here. These methods are called without a
4271 * receiver and thus can be called in functional form:
4273 * sprintf "%.1f", 1.234 #=> "1.2"
4277 * \Module \Kernel provides methods that are useful for:
4279 * - {Converting}[rdoc-ref:Kernel@Converting]
4280 * - {Querying}[rdoc-ref:Kernel@Querying]
4281 * - {Exiting}[rdoc-ref:Kernel@Exiting]
4282 * - {Exceptions}[rdoc-ref:Kernel@Exceptions]
4283 * - {IO}[rdoc-ref:Kernel@IO]
4284 * - {Procs}[rdoc-ref:Kernel@Procs]
4285 * - {Tracing}[rdoc-ref:Kernel@Tracing]
4286 * - {Subprocesses}[rdoc-ref:Kernel@Subprocesses]
4287 * - {Loading}[rdoc-ref:Kernel@Loading]
4288 * - {Yielding}[rdoc-ref:Kernel@Yielding]
4289 * - {Random Values}[rdoc-ref:Kernel@Random+Values]
4290 * - {Other}[rdoc-ref:Kernel@Other]
4294 * - #Array: Returns an Array based on the given argument.
4295 * - #Complex: Returns a Complex based on the given arguments.
4296 * - #Float: Returns a Float based on the given arguments.
4297 * - #Hash: Returns a Hash based on the given argument.
4298 * - #Integer: Returns an Integer based on the given arguments.
4299 * - #Rational: Returns a Rational based on the given arguments.
4300 * - #String: Returns a String based on the given argument.
4304 * - #__callee__: Returns the called name of the current method as a symbol.
4305 * - #__dir__: Returns the path to the directory from which the current
4307 * - #__method__: Returns the name of the current method as a symbol.
4308 * - #autoload?: Returns the file to be loaded when the given module is referenced.
4309 * - #binding: Returns a Binding for the context at the point of call.
4310 * - #block_given?: Returns +true+ if a block was passed to the calling method.
4311 * - #caller: Returns the current execution stack as an array of strings.
4312 * - #caller_locations: Returns the current execution stack as an array
4313 * of Thread::Backtrace::Location objects.
4314 * - #class: Returns the class of +self+.
4315 * - #frozen?: Returns whether +self+ is frozen.
4316 * - #global_variables: Returns an array of global variables as symbols.
4317 * - #local_variables: Returns an array of local variables as symbols.
4318 * - #test: Performs specified tests on the given single file or pair of files.
4322 * - #abort: Exits the current process after printing the given arguments.
4323 * - #at_exit: Executes the given block when the process exits.
4324 * - #exit: Exits the current process after calling any registered
4325 * +at_exit+ handlers.
4326 * - #exit!: Exits the current process without calling any registered
4327 * +at_exit+ handlers.
4331 * - #catch: Executes the given block, possibly catching a thrown object.
4332 * - #raise (aliased as #fail): Raises an exception based on the given arguments.
4333 * - #throw: Returns from the active catch block waiting for the given tag.
4338 * - ::pp: Prints the given objects in pretty form.
4339 * - #gets: Returns and assigns to <tt>$_</tt> the next line from the current input.
4340 * - #open: Creates an IO object connected to the given stream, file, or subprocess.
4341 * - #p: Prints the given objects' inspect output to the standard output.
4342 * - #print: Prints the given objects to standard output without a newline.
4343 * - #printf: Prints the string resulting from applying the given format string
4344 * to any additional arguments.
4345 * - #putc: Equivalent to <tt.$stdout.putc(object)</tt> for the given object.
4346 * - #puts: Equivalent to <tt>$stdout.puts(*objects)</tt> for the given objects.
4347 * - #readline: Similar to #gets, but raises an exception at the end of file.
4348 * - #readlines: Returns an array of the remaining lines from the current input.
4349 * - #select: Same as IO.select.
4353 * - #lambda: Returns a lambda proc for the given block.
4354 * - #proc: Returns a new Proc; equivalent to Proc.new.
4358 * - #set_trace_func: Sets the given proc as the handler for tracing,
4359 * or disables tracing if given +nil+.
4360 * - #trace_var: Starts tracing assignments to the given global variable.
4361 * - #untrace_var: Disables tracing of assignments to the given global variable.
4365 * - {\`command`}[rdoc-ref:Kernel#`]: Returns the standard output of running
4366 * +command+ in a subshell.
4367 * - #exec: Replaces current process with a new process.
4368 * - #fork: Forks the current process into two processes.
4369 * - #spawn: Executes the given command and returns its pid without waiting
4371 * - #system: Executes the given command in a subshell.
4375 * - #autoload: Registers the given file to be loaded when the given constant
4376 * is first referenced.
4377 * - #load: Loads the given Ruby file.
4378 * - #require: Loads the given Ruby file unless it has already been loaded.
4379 * - #require_relative: Loads the Ruby file path relative to the calling file,
4380 * unless it has already been loaded.
4384 * - #tap: Yields +self+ to the given block; returns +self+.
4385 * - #then (aliased as #yield_self): Yields +self+ to the block
4386 * and returns the result of the block.
4388 * === \Random Values
4390 * - #rand: Returns a pseudo-random floating point number
4391 * strictly between 0.0 and 1.0.
4392 * - #srand: Seeds the pseudo-random number generator with the given number.
4396 * - #eval: Evaluates the given string as Ruby code.
4397 * - #loop: Repeatedly executes the given block.
4398 * - #sleep: Suspends the current thread for the given number of seconds.
4399 * - #sprintf (aliased as #format): Returns the string resulting from applying
4400 * the given format string to any additional arguments.
4401 * - #syscall: Runs an operating system call.
4402 * - #trap: Specifies the handling of system signals.
4403 * - #warn: Issue a warning based on the given messages and options.
4406 rb_mKernel
= rb_define_module("Kernel");
4407 rb_include_module(rb_cObject
, rb_mKernel
);
4408 rb_define_private_method(rb_cClass
, "inherited", rb_obj_class_inherited
, 1);
4409 rb_define_private_method(rb_cModule
, "included", rb_obj_mod_included
, 1);
4410 rb_define_private_method(rb_cModule
, "extended", rb_obj_mod_extended
, 1);
4411 rb_define_private_method(rb_cModule
, "prepended", rb_obj_mod_prepended
, 1);
4412 rb_define_private_method(rb_cModule
, "method_added", rb_obj_mod_method_added
, 1);
4413 rb_define_private_method(rb_cModule
, "const_added", rb_obj_mod_const_added
, 1);
4414 rb_define_private_method(rb_cModule
, "method_removed", rb_obj_mod_method_removed
, 1);
4415 rb_define_private_method(rb_cModule
, "method_undefined", rb_obj_mod_method_undefined
, 1);
4417 rb_define_method(rb_mKernel
, "nil?", rb_false
, 0);
4418 rb_define_method(rb_mKernel
, "===", case_equal
, 1);
4419 rb_define_method(rb_mKernel
, "!~", rb_obj_not_match
, 1);
4420 rb_define_method(rb_mKernel
, "eql?", rb_obj_equal
, 1);
4421 rb_define_method(rb_mKernel
, "hash", rb_obj_hash
, 0); /* in hash.c */
4422 rb_define_method(rb_mKernel
, "<=>", rb_obj_cmp
, 1);
4424 rb_define_method(rb_mKernel
, "singleton_class", rb_obj_singleton_class
, 0);
4425 rb_define_method(rb_mKernel
, "dup", rb_obj_dup
, 0);
4426 rb_define_method(rb_mKernel
, "itself", rb_obj_itself
, 0);
4427 rb_define_method(rb_mKernel
, "initialize_copy", rb_obj_init_copy
, 1);
4428 rb_define_method(rb_mKernel
, "initialize_dup", rb_obj_init_dup_clone
, 1);
4429 rb_define_method(rb_mKernel
, "initialize_clone", rb_obj_init_clone
, -1);
4431 rb_define_method(rb_mKernel
, "freeze", rb_obj_freeze
, 0);
4433 rb_define_method(rb_mKernel
, "to_s", rb_any_to_s
, 0);
4434 rb_define_method(rb_mKernel
, "inspect", rb_obj_inspect
, 0);
4435 rb_define_method(rb_mKernel
, "methods", rb_obj_methods
, -1); /* in class.c */
4436 rb_define_method(rb_mKernel
, "singleton_methods", rb_obj_singleton_methods
, -1); /* in class.c */
4437 rb_define_method(rb_mKernel
, "protected_methods", rb_obj_protected_methods
, -1); /* in class.c */
4438 rb_define_method(rb_mKernel
, "private_methods", rb_obj_private_methods
, -1); /* in class.c */
4439 rb_define_method(rb_mKernel
, "public_methods", rb_obj_public_methods
, -1); /* in class.c */
4440 rb_define_method(rb_mKernel
, "instance_variables", rb_obj_instance_variables
, 0); /* in variable.c */
4441 rb_define_method(rb_mKernel
, "instance_variable_get", rb_obj_ivar_get
, 1);
4442 rb_define_method(rb_mKernel
, "instance_variable_set", rb_obj_ivar_set_m
, 2);
4443 rb_define_method(rb_mKernel
, "instance_variable_defined?", rb_obj_ivar_defined
, 1);
4444 rb_define_method(rb_mKernel
, "remove_instance_variable",
4445 rb_obj_remove_instance_variable
, 1); /* in variable.c */
4447 rb_define_method(rb_mKernel
, "instance_of?", rb_obj_is_instance_of
, 1);
4448 rb_define_method(rb_mKernel
, "kind_of?", rb_obj_is_kind_of
, 1);
4449 rb_define_method(rb_mKernel
, "is_a?", rb_obj_is_kind_of
, 1);
4451 rb_define_global_function("sprintf", f_sprintf
, -1);
4452 rb_define_global_function("format", f_sprintf
, -1);
4454 rb_define_global_function("String", rb_f_string
, 1);
4455 rb_define_global_function("Array", rb_f_array
, 1);
4456 rb_define_global_function("Hash", rb_f_hash
, 1);
4458 rb_cNilClass
= rb_define_class("NilClass", rb_cObject
);
4459 rb_cNilClass_to_s
= rb_fstring_enc_lit("", rb_usascii_encoding());
4460 rb_vm_register_global_object(rb_cNilClass_to_s
);
4461 rb_define_method(rb_cNilClass
, "to_s", rb_nil_to_s
, 0);
4462 rb_define_method(rb_cNilClass
, "to_a", nil_to_a
, 0);
4463 rb_define_method(rb_cNilClass
, "to_h", nil_to_h
, 0);
4464 rb_define_method(rb_cNilClass
, "inspect", nil_inspect
, 0);
4465 rb_define_method(rb_cNilClass
, "=~", nil_match
, 1);
4466 rb_define_method(rb_cNilClass
, "&", false_and
, 1);
4467 rb_define_method(rb_cNilClass
, "|", false_or
, 1);
4468 rb_define_method(rb_cNilClass
, "^", false_xor
, 1);
4469 rb_define_method(rb_cNilClass
, "===", case_equal
, 1);
4471 rb_define_method(rb_cNilClass
, "nil?", rb_true
, 0);
4472 rb_undef_alloc_func(rb_cNilClass
);
4473 rb_undef_method(CLASS_OF(rb_cNilClass
), "new");
4475 rb_define_method(rb_cModule
, "freeze", rb_mod_freeze
, 0);
4476 rb_define_method(rb_cModule
, "===", rb_mod_eqq
, 1);
4477 rb_define_method(rb_cModule
, "==", rb_obj_equal
, 1);
4478 rb_define_method(rb_cModule
, "<=>", rb_mod_cmp
, 1);
4479 rb_define_method(rb_cModule
, "<", rb_mod_lt
, 1);
4480 rb_define_method(rb_cModule
, "<=", rb_class_inherited_p
, 1);
4481 rb_define_method(rb_cModule
, ">", rb_mod_gt
, 1);
4482 rb_define_method(rb_cModule
, ">=", rb_mod_ge
, 1);
4483 rb_define_method(rb_cModule
, "initialize_copy", rb_mod_init_copy
, 1); /* in class.c */
4484 rb_define_method(rb_cModule
, "to_s", rb_mod_to_s
, 0);
4485 rb_define_alias(rb_cModule
, "inspect", "to_s");
4486 rb_define_method(rb_cModule
, "included_modules", rb_mod_included_modules
, 0); /* in class.c */
4487 rb_define_method(rb_cModule
, "include?", rb_mod_include_p
, 1); /* in class.c */
4488 rb_define_method(rb_cModule
, "name", rb_mod_name
, 0); /* in variable.c */
4489 rb_define_method(rb_cModule
, "set_temporary_name", rb_mod_set_temporary_name
, 1); /* in variable.c */
4490 rb_define_method(rb_cModule
, "ancestors", rb_mod_ancestors
, 0); /* in class.c */
4492 rb_define_method(rb_cModule
, "attr", rb_mod_attr
, -1);
4493 rb_define_method(rb_cModule
, "attr_reader", rb_mod_attr_reader
, -1);
4494 rb_define_method(rb_cModule
, "attr_writer", rb_mod_attr_writer
, -1);
4495 rb_define_method(rb_cModule
, "attr_accessor", rb_mod_attr_accessor
, -1);
4497 rb_define_alloc_func(rb_cModule
, rb_module_s_alloc
);
4498 rb_undef_method(rb_singleton_class(rb_cModule
), "allocate");
4499 rb_define_method(rb_cModule
, "initialize", rb_mod_initialize
, 0);
4500 rb_define_method(rb_cModule
, "initialize_clone", rb_mod_initialize_clone
, -1);
4501 rb_define_method(rb_cModule
, "instance_methods", rb_class_instance_methods
, -1); /* in class.c */
4502 rb_define_method(rb_cModule
, "public_instance_methods",
4503 rb_class_public_instance_methods
, -1); /* in class.c */
4504 rb_define_method(rb_cModule
, "protected_instance_methods",
4505 rb_class_protected_instance_methods
, -1); /* in class.c */
4506 rb_define_method(rb_cModule
, "private_instance_methods",
4507 rb_class_private_instance_methods
, -1); /* in class.c */
4508 rb_define_method(rb_cModule
, "undefined_instance_methods",
4509 rb_class_undefined_instance_methods
, 0); /* in class.c */
4511 rb_define_method(rb_cModule
, "constants", rb_mod_constants
, -1); /* in variable.c */
4512 rb_define_method(rb_cModule
, "const_get", rb_mod_const_get
, -1);
4513 rb_define_method(rb_cModule
, "const_set", rb_mod_const_set
, 2);
4514 rb_define_method(rb_cModule
, "const_defined?", rb_mod_const_defined
, -1);
4515 rb_define_method(rb_cModule
, "const_source_location", rb_mod_const_source_location
, -1);
4516 rb_define_private_method(rb_cModule
, "remove_const",
4517 rb_mod_remove_const
, 1); /* in variable.c */
4518 rb_define_method(rb_cModule
, "const_missing",
4519 rb_mod_const_missing
, 1); /* in variable.c */
4520 rb_define_method(rb_cModule
, "class_variables",
4521 rb_mod_class_variables
, -1); /* in variable.c */
4522 rb_define_method(rb_cModule
, "remove_class_variable",
4523 rb_mod_remove_cvar
, 1); /* in variable.c */
4524 rb_define_method(rb_cModule
, "class_variable_get", rb_mod_cvar_get
, 1);
4525 rb_define_method(rb_cModule
, "class_variable_set", rb_mod_cvar_set
, 2);
4526 rb_define_method(rb_cModule
, "class_variable_defined?", rb_mod_cvar_defined
, 1);
4527 rb_define_method(rb_cModule
, "public_constant", rb_mod_public_constant
, -1); /* in variable.c */
4528 rb_define_method(rb_cModule
, "private_constant", rb_mod_private_constant
, -1); /* in variable.c */
4529 rb_define_method(rb_cModule
, "deprecate_constant", rb_mod_deprecate_constant
, -1); /* in variable.c */
4530 rb_define_method(rb_cModule
, "singleton_class?", rb_mod_singleton_p
, 0);
4532 rb_define_method(rb_singleton_class(rb_cClass
), "allocate", rb_class_alloc_m
, 0);
4533 rb_define_method(rb_cClass
, "allocate", rb_class_alloc_m
, 0);
4534 rb_define_method(rb_cClass
, "new", rb_class_new_instance_pass_kw
, -1);
4535 rb_define_method(rb_cClass
, "initialize", rb_class_initialize
, -1);
4536 rb_define_method(rb_cClass
, "superclass", rb_class_superclass
, 0);
4537 rb_define_method(rb_cClass
, "subclasses", rb_class_subclasses
, 0); /* in class.c */
4538 rb_define_method(rb_cClass
, "attached_object", rb_class_attached_object
, 0); /* in class.c */
4539 rb_define_alloc_func(rb_cClass
, rb_class_s_alloc
);
4540 rb_undef_method(rb_cClass
, "extend_object");
4541 rb_undef_method(rb_cClass
, "append_features");
4542 rb_undef_method(rb_cClass
, "prepend_features");
4544 rb_cTrueClass
= rb_define_class("TrueClass", rb_cObject
);
4545 rb_cTrueClass_to_s
= rb_fstring_enc_lit("true", rb_usascii_encoding());
4546 rb_vm_register_global_object(rb_cTrueClass_to_s
);
4547 rb_define_method(rb_cTrueClass
, "to_s", rb_true_to_s
, 0);
4548 rb_define_alias(rb_cTrueClass
, "inspect", "to_s");
4549 rb_define_method(rb_cTrueClass
, "&", true_and
, 1);
4550 rb_define_method(rb_cTrueClass
, "|", true_or
, 1);
4551 rb_define_method(rb_cTrueClass
, "^", true_xor
, 1);
4552 rb_define_method(rb_cTrueClass
, "===", case_equal
, 1);
4553 rb_undef_alloc_func(rb_cTrueClass
);
4554 rb_undef_method(CLASS_OF(rb_cTrueClass
), "new");
4556 rb_cFalseClass
= rb_define_class("FalseClass", rb_cObject
);
4557 rb_cFalseClass_to_s
= rb_fstring_enc_lit("false", rb_usascii_encoding());
4558 rb_vm_register_global_object(rb_cFalseClass_to_s
);
4559 rb_define_method(rb_cFalseClass
, "to_s", rb_false_to_s
, 0);
4560 rb_define_alias(rb_cFalseClass
, "inspect", "to_s");
4561 rb_define_method(rb_cFalseClass
, "&", false_and
, 1);
4562 rb_define_method(rb_cFalseClass
, "|", false_or
, 1);
4563 rb_define_method(rb_cFalseClass
, "^", false_xor
, 1);
4564 rb_define_method(rb_cFalseClass
, "===", case_equal
, 1);
4565 rb_undef_alloc_func(rb_cFalseClass
);
4566 rb_undef_method(CLASS_OF(rb_cFalseClass
), "new");
4569 #include "kernel.rbinc"
4570 #include "nilclass.rbinc"
4575 id_dig
= rb_intern_const("dig");