[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / object.c
blob0a8ce4dc0fab35b24254c27b41d00ed9962b1201
1 /**********************************************************************
3 object.c -
5 $Author$
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"
16 #include <ctype.h>
17 #include <errno.h>
18 #include <float.h>
19 #include <math.h>
20 #include <stdio.h>
22 #include "constant.h"
23 #include "id.h"
24 #include "internal.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"
37 #include "variable.h"
38 #include "probes.h"
39 #include "ruby/encoding.h"
40 #include "ruby/st.h"
41 #include "ruby/util.h"
42 #include "ruby/assert.h"
43 #include "builtin.h"
44 #include "shape.h"
45 #include "yjit.h"
47 /* Flags of RObject
49 * 1: ROBJECT_EMBED
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.
56 * endif
59 /*!
60 * \addtogroup object
61 * \{
64 VALUE rb_cBasicObject;
65 VALUE rb_mKernel;
66 VALUE rb_cObject;
67 VALUE rb_cModule;
68 VALUE rb_cClass;
69 VALUE rb_cRefinement;
71 VALUE rb_cNilClass;
72 VALUE rb_cTrueClass;
73 VALUE rb_cFalseClass;
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 */
81 #define id_eq idEq
82 #define id_eql idEqlP
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))
95 /*! \endcond */
97 size_t
98 rb_obj_embedded_size(uint32_t numiv)
100 return offsetof(struct RObject, as.ary) + (sizeof(VALUE) * numiv);
103 VALUE
104 rb_obj_hide(VALUE obj)
106 if (!SPECIAL_CONST_P(obj)) {
107 RBASIC_CLEAR_CLASS(obj);
109 return obj;
112 VALUE
113 rb_obj_reveal(VALUE obj, VALUE klass)
115 if (!SPECIAL_CONST_P(obj)) {
116 RBASIC_SET_CLASS(obj, klass);
118 return obj;
121 VALUE
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));
140 #if RUBY_DEBUG
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++) {
144 ptr[i] = Qundef;
146 #endif
148 return obj;
151 VALUE
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);
157 return obj;
161 * call-seq:
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. */
178 VALUE
179 rb_equal(VALUE obj1, VALUE obj2)
181 VALUE result;
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)
194 VALUE result;
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);
205 * call-seq:
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>):
220 * obj = "a"
221 * other = obj.dup
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:
239 * 1 == 1.0 #=> true
240 * 1.eql? 1.0 #=> false
242 * \private
245 VALUE
246 rb_obj_equal(VALUE obj1, VALUE obj2)
248 return RBOOL(obj1 == obj2);
251 VALUE rb_obj_hash(VALUE obj);
254 * call-seq:
255 * !obj -> true or false
257 * Boolean negate.
259 * \private
263 VALUE
264 rb_obj_not(VALUE obj)
266 return RBOOL(!RTEST(obj));
270 * call-seq:
271 * obj != other -> true or false
273 * Returns true if two objects are not-equal, otherwise false.
275 * \private
279 VALUE
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);
286 VALUE
287 rb_class_real(VALUE cl)
289 while (cl &&
290 (RCLASS_SINGLETON_P(cl) || BUILTIN_TYPE(cl) == T_ICLASS)) {
291 cl = RCLASS_SUPER(cl);
293 return cl;
296 VALUE
297 rb_obj_class(VALUE obj)
299 return rb_class_real(CLASS_OF(obj));
303 * call-seq:
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,
311 * respectively.
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
319 static VALUE
320 rb_obj_singleton_class(VALUE obj)
322 return rb_singleton_class(obj);
325 /*! \private */
326 void
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);
339 return;
342 uint32_t src_num_ivs = RBASIC_IV_COUNT(obj);
343 rb_shape_t * shape_to_set_on_dest = src_shape;
344 VALUE * src_buf;
345 VALUE * dest_buf;
347 if (!src_num_ivs) {
348 return;
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);
370 return;
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);
390 static void
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 */
409 static inline int
410 special_object_p(VALUE obj)
412 if (SPECIAL_CONST_P(obj)) return TRUE;
413 switch (BUILTIN_TYPE(obj)) {
414 case T_BIGNUM:
415 case T_FLOAT:
416 case T_SYMBOL:
417 case T_RATIONAL:
418 case T_COMPLEX:
419 /* not a comprehensive list */
420 return TRUE;
421 default:
422 return FALSE;
426 static VALUE
427 obj_freeze_opt(VALUE freeze)
429 switch (freeze) {
430 case Qfalse:
431 case Qtrue:
432 case Qnil:
433 break;
434 default:
435 rb_raise(rb_eArgError, "unexpected value for freeze: %"PRIsVALUE, rb_obj_class(freeze));
438 return freeze;
441 static VALUE
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);
450 /*! \private */
451 VALUE
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);
458 VALUE
459 rb_get_freeze_opt(int argc, VALUE *argv)
461 static ID keyword_ids[1];
462 VALUE opt;
463 VALUE kwfreeze = Qnil;
465 if (!keyword_ids[0]) {
466 CONST_ID(keyword_ids[0], "freeze");
468 rb_scan_args(argc, argv, "0:", &opt);
469 if (!NIL_P(opt)) {
470 rb_get_kwargs(opt, keyword_ids, 0, 1, &kwfreeze);
471 if (!UNDEF_P(kwfreeze))
472 kwfreeze = obj_freeze_opt(kwfreeze);
474 return kwfreeze;
477 static VALUE
478 immutable_obj_clone(VALUE obj, VALUE kwfreeze)
480 if (kwfreeze == Qfalse)
481 rb_raise(rb_eArgError, "can't unfreeze %"PRIsVALUE,
482 rb_obj_class(obj));
483 return obj;
486 VALUE
487 rb_obj_clone_setup(VALUE obj, VALUE clone, VALUE kwfreeze)
489 VALUE argv[2];
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);
499 switch (kwfreeze) {
500 case Qnil:
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);
511 else {
512 rb_shape_set_shape(clone, next_shape);
515 break;
516 case Qtrue: {
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);
525 argv[0] = obj;
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);
535 else {
536 rb_shape_set_shape(clone, next_shape);
538 break;
540 case Qfalse: {
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);
549 argv[0] = obj;
550 argv[1] = freeze_false_hash;
551 rb_funcallv_kw(clone, id_init_clone, 2, argv, RB_PASS_KEYWORDS);
552 break;
554 default:
555 rb_bug("invalid kwfreeze passed to mutable_obj_clone");
558 return clone;
561 static VALUE
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);
568 VALUE
569 rb_obj_clone(VALUE obj)
571 if (special_object_p(obj)) return obj;
572 return mutable_obj_clone(obj, Qnil);
575 VALUE
576 rb_obj_dup_setup(VALUE obj, VALUE dup)
578 init_copy(dup, obj);
579 rb_funcall(dup, id_init_dup, 1, obj);
581 return dup;
585 * call-seq:
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
593 * the class.
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
603 * be copied.
605 * class Klass
606 * attr_accessor :str
607 * end
609 * module Foo
610 * def foo; 'foo'; end
611 * end
613 * s1 = Klass.new #=> #<Klass:0x401b3a38>
614 * s1.extend(Foo) #=> #<Klass:0x401b3a38>
615 * s1.foo #=> "foo"
617 * s2 = s1.clone #=> #<Klass:0x401be280>
618 * s2.foo #=> "foo"
620 * s3 = s1.dup #=> #<Klass:0x401c1084>
621 * s3.foo #=> NoMethodError: undefined method `foo' for #<Klass:0x401c1084>
623 VALUE
624 rb_obj_dup(VALUE obj)
626 VALUE dup;
628 if (special_object_p(obj)) {
629 return obj;
631 dup = rb_obj_alloc(rb_obj_class(obj));
632 return rb_obj_dup_setup(obj, dup);
636 * call-seq:
637 * obj.itself -> obj
639 * Returns the receiver.
641 * string = "my string"
642 * string.itself.object_id == string.object_id #=> true
646 static VALUE
647 rb_obj_itself(VALUE obj)
649 return obj;
652 VALUE
653 rb_obj_size(VALUE self, VALUE args, VALUE obj)
655 return LONG2FIX(1);
659 * :nodoc:
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.
666 VALUE
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");
674 return obj;
678 * :nodoc:
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.
686 VALUE
687 rb_obj_init_dup_clone(VALUE obj, VALUE orig)
689 rb_funcall(obj, id_init_copy, 1, orig);
690 return obj;
694 * :nodoc:
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
703 static VALUE
704 rb_obj_init_clone(int argc, VALUE *argv, VALUE obj)
706 VALUE orig, opts;
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);
712 return obj;
716 * call-seq:
717 * obj.to_s -> string
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''.
725 VALUE
726 rb_any_to_s(VALUE obj)
728 VALUE str;
729 VALUE cname = rb_class_name(CLASS_OF(obj));
731 str = rb_sprintf("#<%"PRIsVALUE":%p>", cname, (void*)obj);
733 return str;
736 VALUE
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);
746 return str;
748 if (rb_enc_get(str) != enc && !rb_enc_str_asciionly_p(str))
749 return rb_str_escape(str);
750 return str;
753 static int
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, " ");
765 else {
766 rb_str_cat2(str, ", ");
768 rb_str_catf(str, "%"PRIsVALUE"=", rb_id2str(id));
769 rb_str_buf_append(str, rb_inspect(value));
771 return ST_CONTINUE;
774 static VALUE
775 inspect_obj(VALUE obj, VALUE str, int recur)
777 if (recur) {
778 rb_str_cat2(str, " ...");
780 else {
781 rb_ivar_foreach(obj, inspect_i, str);
783 rb_str_cat2(str, ">");
784 RSTRING_PTR(str)[0] = '#';
786 return str;
790 * call-seq:
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"
804 * class Foo
805 * end
806 * Foo.new.inspect #=> "#<Foo:0x0300c868>"
808 * class Bar
809 * def initialize
810 * @bar = 1
811 * end
812 * end
813 * Bar.new.inspect #=> "#<Bar:0x0300c868 @bar=1>"
816 static VALUE
817 rb_obj_inspect(VALUE obj)
819 if (rb_ivar_count(obj) > 0) {
820 VALUE str;
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);
826 else {
827 return rb_any_to_s(obj);
831 static VALUE
832 class_or_module_required(VALUE c)
834 switch (OBJ_BUILTIN_TYPE(c)) {
835 case T_MODULE:
836 case T_CLASS:
837 case T_ICLASS:
838 break;
840 default:
841 rb_raise(rb_eTypeError, "class or module required");
843 return c;
846 static VALUE class_search_ancestor(VALUE cl, VALUE c);
849 * call-seq:
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?.
855 * class A; end
856 * class B < A; end
857 * class C < B; end
859 * b = B.new
860 * b.instance_of? A #=> false
861 * b.instance_of? B #=> true
862 * b.instance_of? C #=> false
865 VALUE
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
874 static VALUE
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)
887 return Qfalse;
889 // Otherwise check that c is in cl's inheritance chain
890 return RBOOL(classes[c_depth] == c);
894 * call-seq:
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>.
902 * module M; end
903 * class A
904 * include M
905 * end
906 * class B < A; end
907 * class C < B; end
909 * b = B.new
910 * b.is_a? A #=> true
911 * b.is_a? B #=> true
912 * b.is_a? C #=> false
913 * b.is_a? M #=> true
915 * b.kind_of? A #=> true
916 * b.kind_of? B #=> true
917 * b.kind_of? C #=> false
918 * b.kind_of? M #=> true
921 VALUE
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))
950 return Qtrue;
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)));
960 else {
961 rb_raise(rb_eTypeError, "class or module required");
962 UNREACHABLE_RETURN(Qfalse);
967 static VALUE
968 class_search_ancestor(VALUE cl, VALUE c)
970 while (cl) {
971 if (cl == c || RCLASS_M_TBL(cl) == RCLASS_M_TBL(c))
972 return cl;
973 cl = RCLASS_SUPER(cl);
975 return 0;
978 /*! \private */
979 VALUE
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
991 * call-seq:
992 * inherited(subclass)
994 * Callback invoked whenever a subclass of the current class is created.
996 * Example:
998 * class Foo
999 * def self.inherited(subclass)
1000 * puts "New subclass: #{subclass}"
1001 * end
1002 * end
1004 * class Bar < Foo
1005 * end
1007 * class Baz < Bar
1008 * end
1010 * <em>produces:</em>
1012 * New subclass: Bar
1013 * New subclass: Baz
1015 #define rb_obj_class_inherited rb_obj_dummy1
1017 /* Document-method: method_added
1019 * call-seq:
1020 * method_added(method_name)
1022 * Invoked as a callback whenever an instance method is added to the
1023 * receiver.
1025 * module Chatty
1026 * def self.method_added(method_name)
1027 * puts "Adding #{method_name.inspect}"
1028 * end
1029 * def self.some_class_method() end
1030 * def some_instance_method() end
1031 * 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
1042 * call-seq:
1043 * method_removed(method_name)
1045 * Invoked as a callback whenever an instance method is removed from the
1046 * receiver.
1048 * module Chatty
1049 * def self.method_removed(method_name)
1050 * puts "Removing #{method_name.inspect}"
1051 * end
1052 * def self.some_class_method() end
1053 * def some_instance_method() end
1054 * class << self
1055 * remove_method :some_class_method
1056 * end
1057 * remove_method :some_instance_method
1058 * end
1060 * <em>produces:</em>
1062 * Removing :some_instance_method
1065 #define rb_obj_mod_method_removed rb_obj_dummy1
1067 /* Document-method: method_undefined
1069 * call-seq:
1070 * method_undefined(method_name)
1072 * Invoked as a callback whenever an instance method is undefined from the
1073 * receiver.
1075 * module Chatty
1076 * def self.method_undefined(method_name)
1077 * puts "Undefining #{method_name.inspect}"
1078 * end
1079 * def self.some_class_method() end
1080 * def some_instance_method() end
1081 * class << self
1082 * undef_method :some_class_method
1083 * end
1084 * undef_method :some_instance_method
1085 * end
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
1097 * call-seq:
1098 * singleton_method_added(symbol)
1100 * Invoked as a callback whenever a singleton method is added to the
1101 * receiver.
1103 * module Chatty
1104 * def Chatty.singleton_method_added(id)
1105 * puts "Adding #{id.id2name}"
1106 * end
1107 * def self.one() end
1108 * def two() end
1109 * def Chatty.three() end
1110 * end
1112 * <em>produces:</em>
1114 * Adding singleton_method_added
1115 * Adding one
1116 * Adding three
1119 #define rb_obj_singleton_method_added rb_obj_dummy1
1122 * Document-method: singleton_method_removed
1124 * call-seq:
1125 * singleton_method_removed(symbol)
1127 * Invoked as a callback whenever a singleton method is removed from
1128 * the receiver.
1130 * module Chatty
1131 * def Chatty.singleton_method_removed(id)
1132 * puts "Removing #{id.id2name}"
1133 * end
1134 * def self.one() end
1135 * def two() end
1136 * def Chatty.three() end
1137 * class << self
1138 * remove_method :three
1139 * remove_method :one
1140 * end
1141 * end
1143 * <em>produces:</em>
1145 * Removing three
1146 * Removing one
1148 #define rb_obj_singleton_method_removed rb_obj_dummy1
1151 * Document-method: singleton_method_undefined
1153 * call-seq:
1154 * singleton_method_undefined(symbol)
1156 * Invoked as a callback whenever a singleton method is undefined in
1157 * the receiver.
1159 * module Chatty
1160 * def Chatty.singleton_method_undefined(id)
1161 * puts "Undefining #{id.id2name}"
1162 * end
1163 * def Chatty.one() end
1164 * class << self
1165 * undef_method(:one)
1166 * end
1167 * end
1169 * <em>produces:</em>
1171 * Undefining one
1173 #define rb_obj_singleton_method_undefined rb_obj_dummy1
1175 /* Document-method: const_added
1177 * call-seq:
1178 * const_added(const_name)
1180 * Invoked as a callback whenever a constant is assigned on the receiver
1182 * module Chatty
1183 * def self.const_added(const_name)
1184 * super
1185 * puts "Added #{const_name.inspect}"
1186 * end
1187 * FOO = 1
1188 * end
1190 * <em>produces:</em>
1192 * Added :FOO
1195 #define rb_obj_mod_const_added rb_obj_dummy1
1198 * Document-method: extended
1200 * call-seq:
1201 * extended(othermod)
1203 * The equivalent of <tt>included</tt>, but for extended modules.
1205 * module A
1206 * def self.extended(mod)
1207 * puts "#{self} extended in #{mod}"
1208 * end
1209 * end
1210 * module Enumerable
1211 * extend A
1212 * end
1213 * # => prints "A extended in Enumerable"
1215 #define rb_obj_mod_extended rb_obj_dummy1
1218 * Document-method: included
1220 * call-seq:
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.
1228 * module A
1229 * def A.included(mod)
1230 * puts "#{self} included in #{mod}"
1231 * end
1232 * end
1233 * module Enumerable
1234 * include A
1235 * end
1236 * # => prints "A included in Enumerable"
1238 #define rb_obj_mod_included rb_obj_dummy1
1241 * Document-method: prepended
1243 * call-seq:
1244 * prepended(othermod)
1246 * The equivalent of <tt>included</tt>, but for prepended modules.
1248 * module A
1249 * def self.prepended(mod)
1250 * puts "#{self} prepended to #{mod}"
1251 * end
1252 * end
1253 * module Enumerable
1254 * prepend A
1255 * end
1256 * # => prints "A prepended to Enumerable"
1258 #define rb_obj_mod_prepended rb_obj_dummy1
1261 * Document-method: initialize
1263 * call-seq:
1264 * BasicObject.new
1266 * Returns a new BasicObject.
1268 #define rb_obj_initialize rb_obj_dummy0
1271 * Not documented
1274 static VALUE
1275 rb_obj_dummy(void)
1277 return Qnil;
1280 static VALUE
1281 rb_obj_dummy0(VALUE _)
1283 return rb_obj_dummy();
1286 static VALUE
1287 rb_obj_dummy1(VALUE _x, VALUE _y)
1289 return rb_obj_dummy();
1293 * call-seq:
1294 * obj.freeze -> obj
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
1299 * Object#frozen?.
1301 * This method returns self.
1303 * a = [ "a", "b", "c" ]
1304 * a.freeze
1305 * a << "z"
1307 * <em>produces:</em>
1309 * prog.rb:3:in `<<': can't modify frozen Array (FrozenError)
1310 * from prog.rb:3
1312 * Objects of the following classes are always frozen: Integer,
1313 * Float, Symbol.
1316 VALUE
1317 rb_obj_freeze(VALUE obj)
1319 if (!OBJ_FROZEN(obj)) {
1320 OBJ_FREEZE(obj);
1321 if (SPECIAL_CONST_P(obj)) {
1322 rb_bug("special consts should be frozen.");
1325 return obj;
1328 VALUE
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:
1342 * - #&
1343 * - #|
1344 * - #===
1345 * - #=~
1346 * - #^
1348 * Others act as converters, carrying the concept of _nullity_
1349 * to other classes:
1351 * - #rationalize
1352 * - #to_a
1353 * - #to_c
1354 * - #to_h
1355 * - #to_r
1356 * - #to_s
1358 * Another method provides inspection:
1360 * - #inspect
1362 * Finally, there is this query method:
1364 * - #nil?
1369 * call-seq:
1370 * to_s -> ''
1372 * Returns an empty String:
1374 * nil.to_s # => ""
1378 VALUE
1379 rb_nil_to_s(VALUE obj)
1381 return rb_cNilClass_to_s;
1385 * Document-method: to_a
1387 * call-seq:
1388 * to_a -> []
1390 * Returns an empty Array.
1392 * nil.to_a # => []
1396 static VALUE
1397 nil_to_a(VALUE obj)
1399 return rb_ary_new2(0);
1403 * Document-method: to_h
1405 * call-seq:
1406 * to_h -> {}
1408 * Returns an empty Hash.
1410 * nil.to_h #=> {}
1414 static VALUE
1415 nil_to_h(VALUE obj)
1417 return rb_hash_new();
1421 * call-seq:
1422 * inspect -> 'nil'
1424 * Returns string <tt>'nil'</tt>:
1426 * nil.inspect # => "nil"
1430 static VALUE
1431 nil_inspect(VALUE obj)
1433 return rb_usascii_str_new2("nil");
1437 * call-seq:
1438 * nil =~ object -> nil
1440 * Returns +nil+.
1442 * This method makes it useful to write:
1444 * while gets =~ /re/
1445 * # ...
1446 * end
1450 static VALUE
1451 nil_match(VALUE obj1, VALUE obj2)
1453 return Qnil;
1457 * Document-class: TrueClass
1459 * The class of the singleton object +true+.
1461 * Several of its methods act as operators:
1463 * - #&
1464 * - #|
1465 * - #===
1466 * - #^
1468 * One other method:
1470 * - #to_s and its alias #inspect.
1476 * call-seq:
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.
1487 VALUE
1488 rb_true_to_s(VALUE obj)
1490 return rb_cTrueClass_to_s;
1495 * call-seq:
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
1506 static VALUE
1507 true_and(VALUE obj, VALUE obj2)
1509 return RBOOL(RTEST(obj2));
1513 * call-seq:
1514 * true | object -> true
1516 * Returns +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
1531 static VALUE
1532 true_or(VALUE obj, VALUE obj2)
1534 return Qtrue;
1539 * call-seq:
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
1550 static VALUE
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.
1568 * call-seq:
1569 * false.to_s -> "false"
1571 * The string representation of <code>false</code> is "false".
1574 VALUE
1575 rb_false_to_s(VALUE obj)
1577 return rb_cFalseClass_to_s;
1581 * call-seq:
1582 * false & object -> false
1583 * nil & object -> false
1585 * Returns +false+:
1587 * false & true # => false
1588 * false & Object.new # => false
1590 * Argument +object+ is evaluated:
1592 * false & raise # Raises RuntimeError.
1595 static VALUE
1596 false_and(VALUE obj, VALUE obj2)
1598 return Qfalse;
1603 * call-seq:
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
1618 * call-seq:
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
1633 * call-seq:
1634 * nil.nil? -> true
1636 * Returns +true+.
1637 * For all other objects, method <tt>nil?</tt> returns +false+.
1640 static VALUE
1641 rb_true(VALUE obj)
1643 return Qtrue;
1647 * call-seq:
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
1653 * nil.nil? #=> true
1657 VALUE
1658 rb_false(VALUE obj)
1660 return Qfalse;
1664 * call-seq:
1665 * obj !~ other -> true or false
1667 * Returns true if two objects do not match (using the <i>=~</i>
1668 * method), otherwise false.
1671 static VALUE
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);
1680 * call-seq:
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
1692 * compared.
1694 * When you define #<=>, you can include Comparable to gain the
1695 * methods #<=, #<, #==, #>=, #> and #between?.
1697 static VALUE
1698 rb_obj_cmp(VALUE obj1, VALUE obj2)
1700 if (rb_equal(obj1, obj2))
1701 return INT2FIX(0);
1702 return Qnil;
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>).
1720 * module Mod
1721 * include Math
1722 * CONST = 1
1723 * def meth
1724 * # ...
1725 * end
1726 * end
1727 * Mod.class #=> Module
1728 * Mod.constants #=> [:CONST, :PI, :E]
1729 * Mod.instance_methods #=> [:meth]
1734 * call-seq:
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.
1742 VALUE
1743 rb_mod_to_s(VALUE klass)
1745 ID id_defined_at;
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));
1755 else {
1756 rb_str_append(s, rb_any_to_s(v));
1758 rb_str_cat2(s, ">");
1760 return 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, ">");
1772 return s;
1774 return rb_class_name(klass);
1778 * call-seq:
1779 * mod.freeze -> mod
1781 * Prevents further modifications to <i>mod</i>.
1783 * This method returns self.
1786 static VALUE
1787 rb_mod_freeze(VALUE mod)
1789 rb_class_name(mod);
1790 return rb_obj_freeze(mod);
1794 * call-seq:
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.
1803 static VALUE
1804 rb_mod_eqq(VALUE mod, VALUE arg)
1806 return rb_obj_is_kind_of(arg, mod);
1810 * call-seq:
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".)
1820 VALUE
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 ?
1832 Qtrue :
1833 Qnil;
1835 else if (arg_depth > mod_depth) {
1836 // check if mod > arg
1837 return RCLASS_SUPERCLASSES(arg)[mod_depth] == mod ?
1838 Qfalse :
1839 Qnil;
1841 else {
1842 // Depths match, and we know they aren't equal: no relation
1843 return Qnil;
1846 else {
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))) {
1851 return Qtrue;
1853 /* not mod < arg; check if mod > arg */
1854 if (class_search_ancestor(arg, mod)) {
1855 return Qfalse;
1857 return Qnil;
1862 * call-seq:
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".)
1874 static VALUE
1875 rb_mod_lt(VALUE mod, VALUE arg)
1877 if (mod == arg) return Qfalse;
1878 return rb_class_inherited_p(mod, arg);
1883 * call-seq:
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".)
1894 static VALUE
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);
1905 * call-seq:
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".)
1917 static VALUE
1918 rb_mod_gt(VALUE mod, VALUE arg)
1920 if (mod == arg) return Qfalse;
1921 return rb_mod_ge(mod, arg);
1925 * call-seq:
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
1930 * +other_module+.
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.
1936 static VALUE
1937 rb_mod_cmp(VALUE mod, VALUE arg)
1939 VALUE cmp;
1941 if (mod == arg) return INT2FIX(0);
1942 if (!CLASS_OR_MODULE_P(arg)) {
1943 return Qnil;
1946 cmp = rb_class_inherited_p(mod, arg);
1947 if (NIL_P(cmp)) return Qnil;
1948 if (cmp) {
1949 return INT2FIX(-1);
1951 return INT2FIX(1);
1954 static VALUE rb_mod_initialize_exec(VALUE module);
1957 * call-seq:
1958 * Module.new -> mod
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
1966 * def meth1
1967 * "hello"
1968 * end
1969 * def meth2
1970 * "bye"
1971 * end
1972 * end
1973 * a = "my string"
1974 * a.extend(fred) #=> "my string"
1975 * a.meth1 #=> "hello"
1976 * a.meth2 #=> "bye"
1978 * Assign the module to a constant (name starting uppercase) if you
1979 * want to treat it like a regular module.
1982 static VALUE
1983 rb_mod_initialize(VALUE module)
1985 return rb_mod_initialize_exec(module);
1988 static VALUE
1989 rb_mod_initialize_exec(VALUE module)
1991 if (rb_block_given_p()) {
1992 rb_mod_module_exec(1, &module, module);
1994 return Qnil;
1997 /* :nodoc: */
1998 static VALUE
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);
2006 return ret;
2010 * call-seq:
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
2020 * #class_eval.
2022 * fred = Class.new do
2023 * def meth1
2024 * "hello"
2025 * end
2026 * def meth2
2027 * "bye"
2028 * end
2029 * end
2031 * a = fred.new #=> #<#<Class:0x100381890>:0x100376b98>
2032 * a.meth1 #=> "hello"
2033 * a.meth2 #=> "bye"
2035 * Assign the class to a constant (name starting uppercase) if you
2036 * want to treat it like a regular class.
2039 static VALUE
2040 rb_class_initialize(int argc, VALUE *argv, VALUE klass)
2042 VALUE super;
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) {
2048 super = rb_cObject;
2050 else {
2051 super = argv[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);
2062 return klass;
2065 /*! \private */
2066 void
2067 rb_undefined_alloc(VALUE klass)
2069 rb_raise(rb_eTypeError, "allocator undefined for %"PRIsVALUE,
2070 klass);
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);
2077 * call-seq:
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
2087 * end
2089 * def initialized?
2090 * @initialized || false
2091 * end
2092 * end
2094 * klass.allocate.initialized? #=> false
2098 static VALUE
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",
2104 klass);
2106 return class_call_alloc_func(allocator, klass);
2109 static VALUE
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);
2128 if (!allocator) {
2129 rb_undefined_alloc(klass);
2131 return allocator;
2134 static VALUE
2135 class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass)
2137 VALUE obj;
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");
2146 return obj;
2149 VALUE
2150 rb_obj_alloc(VALUE klass)
2152 Check_Type(klass, T_CLASS);
2153 return rb_class_alloc(klass);
2157 * call-seq:
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>.
2167 VALUE
2168 rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass)
2170 VALUE obj;
2172 obj = rb_class_alloc(klass);
2173 rb_obj_call_init_kw(obj, argc, argv, RB_PASS_CALLED_KEYWORDS);
2175 return obj;
2178 VALUE
2179 rb_class_new_instance_kw(int argc, const VALUE *argv, VALUE klass, int kw_splat)
2181 VALUE obj;
2182 Check_Type(klass, T_CLASS);
2184 obj = rb_class_alloc(klass);
2185 rb_obj_call_init_kw(obj, argc, argv, kw_splat);
2187 return obj;
2190 VALUE
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);
2197 * call-seq:
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
2205 * class Foo; end
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.
2216 * It skips modules.
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
2223 VALUE
2224 rb_class_superclass(VALUE klass)
2226 RUBY_ASSERT(RB_TYPE_P(klass, T_CLASS));
2228 VALUE super = RCLASS_SUPER(klass);
2230 if (!super) {
2231 if (klass == rb_cBasicObject) return Qnil;
2232 rb_raise(rb_eTypeError, "uninitialized class");
2235 if (!RCLASS_SUPERCLASS_DEPTH(klass)) {
2236 return Qnil;
2238 else {
2239 super = RCLASS_SUPERCLASSES(klass)[RCLASS_SUPERCLASS_DEPTH(klass) - 1];
2240 RUBY_ASSERT(RB_TYPE_P(klass, T_CLASS));
2241 return super;
2245 VALUE
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
2257 /*! \private */
2258 #define id_for_var(obj, name, type) id_for_setter(obj, name, type, bad_##type##_name)
2259 /*! \private */
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))
2262 static ID
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),
2272 obj, name);
2274 return id;
2277 static int
2278 rb_is_attr_name(VALUE name)
2280 return rb_is_local_name(name) || rb_is_const_name(name);
2283 static int
2284 rb_is_attr_id(ID id)
2286 return rb_is_local_id(id) || rb_is_const_id(id);
2289 static 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);
2294 return id;
2298 * call-seq:
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.
2311 static VALUE
2312 rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass)
2314 int i;
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));
2322 return names;
2326 * call-seq:
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.
2336 * \private
2337 * \todo can be static?
2340 VALUE
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)));
2351 return names;
2353 return rb_mod_attr_reader(argc, argv, klass);
2357 * call-seq:
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.
2367 static VALUE
2368 rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass)
2370 int i;
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)));
2378 return names;
2382 * call-seq:
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.
2393 * module Mod
2394 * attr_accessor(:one, :two) #=> [:one, :one=, :two, :two=]
2395 * end
2396 * Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
2399 static VALUE
2400 rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass)
2402 int i;
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)));
2412 return names;
2416 * call-seq:
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:
2437 * module Foo
2438 * class Bar
2439 * VAL = 10
2440 * end
2442 * class Baz < Bar; end
2443 * 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
2455 static VALUE
2456 rb_mod_const_get(int argc, VALUE *argv, VALUE mod)
2458 VALUE name, recur;
2459 rb_encoding *enc;
2460 const char *pbeg, *p, *path, *pend;
2461 ID id;
2463 rb_check_arity(argc, 1, 2);
2464 name = argv[0];
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)");
2481 pbeg = p = path;
2482 pend = path + RSTRING_LEN(name);
2484 if (p >= pend || !*p) {
2485 goto wrong_name;
2488 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2489 mod = rb_cObject;
2490 p += 2;
2491 pbeg = p;
2494 while (p < pend) {
2495 VALUE part;
2496 long len, beglen;
2498 while (p < pend && *p != ':') p++;
2500 if (pbeg == p) goto wrong_name;
2502 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2503 beglen = pbeg-path;
2505 if (p < pend && p[0] == ':') {
2506 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2507 p += 2;
2508 pbeg = p;
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",
2513 QUOTE(name));
2516 if (!id) {
2517 part = rb_str_subseq(name, beglen, len);
2518 OBJ_FREEZE(part);
2519 if (!rb_is_const_name(part)) {
2520 name = part;
2521 goto wrong_name;
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);
2526 continue;
2528 else {
2529 rb_mod_const_missing(mod, part);
2532 if (!rb_is_const_id(id)) {
2533 name = ID2SYM(id);
2534 goto wrong_name;
2536 #if 0
2537 mod = rb_const_get_0(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2538 #else
2539 if (!RTEST(recur)) {
2540 mod = rb_const_get_at(mod, id);
2542 else if (beglen == 0) {
2543 mod = rb_const_get(mod, id);
2545 else {
2546 mod = rb_const_get_from(mod, id);
2548 #endif
2551 return mod;
2553 wrong_name:
2554 rb_name_err_raise(wrong_constant_name, mod, name);
2555 UNREACHABLE_RETURN(Qundef);
2559 * call-seq:
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
2565 * existed.
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
2577 static VALUE
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);
2584 return value;
2588 * call-seq:
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
2604 * autoloading:
2606 * module Admin
2607 * autoload :User, 'admin/user'
2608 * end
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
2628 static VALUE
2629 rb_mod_const_defined(int argc, VALUE *argv, VALUE mod)
2631 VALUE name, recur;
2632 rb_encoding *enc;
2633 const char *pbeg, *p, *path, *pend;
2634 ID id;
2636 rb_check_arity(argc, 1, 2);
2637 name = argv[0];
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)");
2654 pbeg = p = path;
2655 pend = path + RSTRING_LEN(name);
2657 if (p >= pend || !*p) {
2658 goto wrong_name;
2661 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2662 mod = rb_cObject;
2663 p += 2;
2664 pbeg = p;
2667 while (p < pend) {
2668 VALUE part;
2669 long len, beglen;
2671 while (p < pend && *p != ':') p++;
2673 if (pbeg == p) goto wrong_name;
2675 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2676 beglen = pbeg-path;
2678 if (p < pend && p[0] == ':') {
2679 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2680 p += 2;
2681 pbeg = p;
2684 if (!id) {
2685 part = rb_str_subseq(name, beglen, len);
2686 OBJ_FREEZE(part);
2687 if (!rb_is_const_name(part)) {
2688 name = part;
2689 goto wrong_name;
2691 else {
2692 return Qfalse;
2695 if (!rb_is_const_id(id)) {
2696 name = ID2SYM(id);
2697 goto wrong_name;
2700 #if 0
2701 mod = rb_const_search(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2702 if (UNDEF_P(mod)) return Qfalse;
2703 #else
2704 if (!RTEST(recur)) {
2705 if (!rb_const_defined_at(mod, id))
2706 return Qfalse;
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))
2712 return Qfalse;
2713 if (p == pend) return Qtrue;
2714 mod = rb_const_get(mod, id);
2716 else {
2717 if (!rb_const_defined_from(mod, id))
2718 return Qfalse;
2719 if (p == pend) return Qtrue;
2720 mod = rb_const_get_from(mod, id);
2722 #endif
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",
2726 QUOTE(name));
2730 return Qtrue;
2732 wrong_name:
2733 rb_name_err_raise(wrong_constant_name, mod, name);
2734 UNREACHABLE_RETURN(Qundef);
2738 * call-seq:
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+
2748 * by default).
2750 * # test.rb:
2751 * class A # line 1
2752 * C1 = 1
2753 * C2 = 2
2754 * end
2756 * module M # line 6
2757 * C3 = 3
2758 * end
2760 * class B < A # line 10
2761 * include M
2762 * C4 = 4
2763 * end
2765 * class A # continuation of A definition
2766 * C2 = 8 # constant redefinition; warned yet allowed
2767 * end
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
2788 static VALUE
2789 rb_mod_const_source_location(int argc, VALUE *argv, VALUE mod)
2791 VALUE name, recur, loc = Qnil;
2792 rb_encoding *enc;
2793 const char *pbeg, *p, *path, *pend;
2794 ID id;
2796 rb_check_arity(argc, 1, 2);
2797 name = argv[0];
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)");
2814 pbeg = p = path;
2815 pend = path + RSTRING_LEN(name);
2817 if (p >= pend || !*p) {
2818 goto wrong_name;
2821 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2822 mod = rb_cObject;
2823 p += 2;
2824 pbeg = p;
2827 while (p < pend) {
2828 VALUE part;
2829 long len, beglen;
2831 while (p < pend && *p != ':') p++;
2833 if (pbeg == p) goto wrong_name;
2835 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2836 beglen = pbeg-path;
2838 if (p < pend && p[0] == ':') {
2839 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2840 p += 2;
2841 pbeg = p;
2844 if (!id) {
2845 part = rb_str_subseq(name, beglen, len);
2846 OBJ_FREEZE(part);
2847 if (!rb_is_const_name(part)) {
2848 name = part;
2849 goto wrong_name;
2851 else {
2852 return Qnil;
2855 if (!rb_is_const_id(id)) {
2856 name = ID2SYM(id);
2857 goto wrong_name;
2859 if (p < pend) {
2860 if (RTEST(recur)) {
2861 mod = rb_const_get(mod, id);
2863 else {
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",
2868 QUOTE(name));
2871 else {
2872 if (RTEST(recur)) {
2873 loc = rb_const_source_location(mod, id);
2875 else {
2876 loc = rb_const_source_location_at(mod, id);
2878 break;
2880 recur = Qfalse;
2883 return loc;
2885 wrong_name:
2886 rb_name_err_raise(wrong_constant_name, mod, name);
2887 UNREACHABLE_RETURN(Qundef);
2891 * call-seq:
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.
2902 * class Fred
2903 * def initialize(p1, p2)
2904 * @a, @b = p1, p2
2905 * end
2906 * end
2907 * fred = Fred.new('cat', 99)
2908 * fred.instance_variable_get(:@a) #=> "cat"
2909 * fred.instance_variable_get("@b") #=> 99
2912 static VALUE
2913 rb_obj_ivar_get(VALUE obj, VALUE iv)
2915 ID id = id_for_var(obj, iv, instance);
2917 if (!id) {
2918 return Qnil;
2920 return rb_ivar_get(obj, id);
2924 * call-seq:
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.
2935 * class Fred
2936 * def initialize(p1, p2)
2937 * @a, @b = p1, p2
2938 * end
2939 * end
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\">"
2946 static VALUE
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);
2955 * call-seq:
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.
2963 * class Fred
2964 * def initialize(p1, p2)
2965 * @a, @b = p1, p2
2966 * end
2967 * end
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
2974 static VALUE
2975 rb_obj_ivar_defined(VALUE obj, VALUE iv)
2977 ID id = id_for_var(obj, iv, instance);
2979 if (!id) {
2980 return Qfalse;
2982 return rb_ivar_defined(obj, id);
2986 * call-seq:
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.
2995 * class Fred
2996 * @@foo = 99
2997 * end
2998 * Fred.class_variable_get(:@@foo) #=> 99
3001 static VALUE
3002 rb_mod_cvar_get(VALUE obj, VALUE iv)
3004 ID id = id_for_var(obj, iv, class);
3006 if (!id) {
3007 rb_name_err_raise("uninitialized class variable %1$s in %2$s",
3008 obj, iv);
3010 return rb_cvar_get(obj, id);
3014 * call-seq:
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
3019 * object.
3020 * If the class variable name is passed as a string, that string
3021 * is converted to a symbol.
3023 * class Fred
3024 * @@foo = 99
3025 * def foo
3026 * @@foo
3027 * end
3028 * end
3029 * Fred.class_variable_set(:@@foo, 101) #=> 101
3030 * Fred.new.foo #=> 101
3033 static VALUE
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);
3039 return val;
3043 * call-seq:
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
3048 * in <i>obj</i>.
3049 * String arguments are converted to symbols.
3051 * class Fred
3052 * @@foo = 99
3053 * end
3054 * Fred.class_variable_defined?(:@@foo) #=> true
3055 * Fred.class_variable_defined?(:@@bar) #=> false
3058 static VALUE
3059 rb_mod_cvar_defined(VALUE obj, VALUE iv)
3061 ID id = id_for_var(obj, iv, class);
3063 if (!id) {
3064 return Qfalse;
3066 return rb_cvar_defined(obj, id);
3070 * call-seq:
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.
3076 * class C
3077 * end
3078 * C.singleton_class? #=> false
3079 * C.singleton_class.singleton_class? #=> true
3082 static VALUE
3083 rb_mod_singleton_p(VALUE klass)
3085 return RBOOL(RCLASS_SINGLETON_P(klass));
3088 /*! \private */
3089 static const struct conv_method_tbl {
3090 const char method[6];
3091 unsigned short id;
3092 } conv_method_names[] = {
3093 #define M(n) {#n, (unsigned short)idTo_##n}
3094 M(int),
3095 M(ary),
3096 M(str),
3097 M(sym),
3098 M(hash),
3099 M(proc),
3100 M(io),
3101 M(a),
3102 M(s),
3103 M(i),
3104 M(f),
3105 M(r),
3106 #undef M
3108 #define IMPLICIT_CONVERSIONS 7
3110 static int
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];
3117 int i;
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) {
3121 return i;
3125 return numberof(conv_method_names);
3128 static VALUE
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);
3132 if (UNDEF_P(r)) {
3133 if (raise) {
3134 const char *msg =
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" :
3141 NULL;
3142 if (cname)
3143 rb_raise(rb_eTypeError, "%s %s into %s", msg, cname, tname);
3144 rb_raise(rb_eTypeError, "%s %"PRIsVALUE" into %s", msg,
3145 rb_obj_class(val),
3146 tname);
3148 return Qnil;
3150 return r;
3153 static VALUE
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);
3162 /*! \private */
3163 NORETURN(static void conversion_mismatch(VALUE, const char *, const char *, VALUE));
3164 static void
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));
3173 VALUE
3174 rb_convert_type(VALUE val, int type, const char *tname, const char *method)
3176 VALUE v;
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);
3183 return v;
3186 /*! \private */
3187 VALUE
3188 rb_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
3190 VALUE v;
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);
3197 return v;
3200 VALUE
3201 rb_check_convert_type(VALUE val, int type, const char *tname, const char *method)
3203 VALUE v;
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);
3212 return v;
3215 /*! \private */
3216 VALUE
3217 rb_check_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
3219 VALUE v;
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);
3228 return 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 */
3236 static inline VALUE
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;
3241 VALUE v;
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;
3249 return Qnil;
3251 if (!RB_INTEGER_TYPE_P(v)) {
3252 conversion_mismatch(val, "Integer", method, v);
3254 GET_EC()->cfp = current_cfp;
3255 return v;
3257 #define rb_to_integer(val, method, mid) \
3258 rb_to_integer_with_id_exception(val, method, mid, TRUE)
3260 VALUE
3261 rb_check_to_integer(VALUE val, const char *method)
3263 VALUE v;
3265 if (RB_INTEGER_TYPE_P(val)) return val;
3266 v = convert_type(val, "Integer", method, FALSE);
3267 if (!RB_INTEGER_TYPE_P(v)) {
3268 return Qnil;
3270 return v;
3273 VALUE
3274 rb_to_int(VALUE val)
3276 return rb_to_integer(val, "to_int", idTo_int);
3279 VALUE
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;
3285 return Qnil;
3288 static VALUE
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;
3294 return Qnil;
3297 static VALUE
3298 rb_convert_to_integer(VALUE val, int base, int raise_exception)
3300 VALUE tmp;
3302 if (base) {
3303 tmp = rb_check_string_type(val);
3305 if (! NIL_P(tmp)) {
3306 val = tmp;
3308 else if (! raise_exception) {
3309 return Qnil;
3311 else {
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)) {
3322 return 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);
3342 return result;
3345 return rb_to_integer(val, "to_i", idTo_i);
3348 VALUE
3349 rb_Integer(VALUE val)
3351 return rb_convert_to_integer(val, 0, TRUE);
3354 VALUE
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)
3363 switch (obj) {
3364 case Qtrue:
3365 return TRUE;
3366 case Qfalse:
3367 return FALSE;
3368 default: {
3369 static const char message[] = "expected true or false as %s: %+"PRIsVALUE;
3370 if (raise) {
3371 rb_raise(rb_eArgError, message, flagname, obj);
3373 rb_warning(message, flagname, obj);
3374 return !NIL_P(obj);
3380 rb_opts_exception_p(VALUE opts, int default_value)
3382 static const ID kwds[1] = {idException};
3383 VALUE exception;
3384 if (rb_get_kwargs(opts, kwds, 0, 1, &exception))
3385 return rb_bool_expected(exception, "exception", TRUE);
3386 return default_value;
3389 static VALUE
3390 rb_f_integer1(rb_execution_context_t *ec, VALUE obj, VALUE arg)
3392 return rb_convert_to_integer(arg, 0, TRUE);
3395 static VALUE
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);
3402 static double
3403 rb_cstr_to_dbl_raise(const char *p, int badcheck, int raise, int *error)
3405 const char *q;
3406 char *end;
3407 double d;
3408 const char *ellipsis = "";
3409 int w;
3410 enum {max_width = 20};
3411 #define OutOfRange() ((end - p > max_width) ? \
3412 (w = max_width, ellipsis = "...") : \
3413 (w = (int)(end - p), ellipsis = ""))
3415 if (!p) return 0.0;
3416 q = p;
3417 while (ISSPACE(*p)) p++;
3419 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3420 return 0.0;
3423 d = strtod(p, &end);
3424 if (errno == ERANGE) {
3425 OutOfRange();
3426 rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3427 errno = 0;
3429 if (p == end) {
3430 if (badcheck) {
3431 goto bad;
3433 return d;
3435 if (*end) {
3436 char buf[DBL_DIG * 4 + 10];
3437 char *n = buf;
3438 char *const init_e = buf + DBL_DIG * 4;
3439 char *e = init_e;
3440 char prev = 0;
3441 int dot_seen = FALSE;
3443 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3444 if (*p == '0') {
3445 prev = *n++ = '0';
3446 while (*++p == '0');
3448 while (p < end && n < e) prev = *n++ = *p++;
3449 while (*p) {
3450 if (*p == '_') {
3451 /* remove an underscore between digits */
3452 if (n == buf || !ISDIGIT(prev) || (++p, !ISDIGIT(*p))) {
3453 if (badcheck) goto bad;
3454 break;
3457 prev = *p++;
3458 if (e == init_e && (prev == 'e' || prev == 'E' || prev == 'p' || prev == 'P')) {
3459 e = buf + sizeof(buf) - 1;
3460 *n++ = prev;
3461 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3462 if (*p == '0') {
3463 prev = *n++ = '0';
3464 while (*++p == '0');
3466 continue;
3468 else if (ISSPACE(prev)) {
3469 while (ISSPACE(*p)) ++p;
3470 if (*p) {
3471 if (badcheck) goto bad;
3472 break;
3475 else if (prev == '.' ? dot_seen++ : !ISDIGIT(prev)) {
3476 if (badcheck) goto bad;
3477 break;
3479 if (n < e) *n++ = prev;
3481 *n = '\0';
3482 p = buf;
3484 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3485 return 0.0;
3488 d = strtod(p, &end);
3489 if (errno == ERANGE) {
3490 OutOfRange();
3491 rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3492 errno = 0;
3494 if (badcheck) {
3495 if (!end || p == end) goto bad;
3496 while (*end && ISSPACE(*end)) end++;
3497 if (*end) goto bad;
3500 if (errno == ERANGE) {
3501 errno = 0;
3502 OutOfRange();
3503 rb_raise(rb_eArgError, "Float %.*s%s out of range", w, q, ellipsis);
3505 return d;
3507 bad:
3508 if (raise) {
3509 rb_invalid_str(q, "Float()");
3510 UNREACHABLE_RETURN(nan(""));
3512 else {
3513 if (error) *error = 1;
3514 return 0.0;
3518 double
3519 rb_cstr_to_dbl(const char *p, int badcheck)
3521 return rb_cstr_to_dbl_raise(p, badcheck, TRUE, NULL);
3524 static double
3525 rb_str_to_dbl_raise(VALUE str, int badcheck, int raise, int *error)
3527 char *s;
3528 long len;
3529 double ret;
3530 VALUE v = 0;
3532 StringValue(str);
3533 s = RSTRING_PTR(str);
3534 len = RSTRING_LEN(str);
3535 if (s) {
3536 if (badcheck && memchr(s, '\0', len)) {
3537 if (raise)
3538 rb_raise(rb_eArgError, "string for Float contains null byte");
3539 else {
3540 if (error) *error = 1;
3541 return 0.0;
3544 if (s[len]) { /* no sentinel somehow */
3545 char *p = ALLOCV(v, (size_t)len + 1);
3546 MEMCPY(p, s, char, len);
3547 p[len] = '\0';
3548 s = p;
3551 ret = rb_cstr_to_dbl_raise(s, badcheck, raise, error);
3552 if (v)
3553 ALLOCV_END(v);
3554 return ret;
3557 FUNC_MINIMIZED(double rb_str_to_dbl(VALUE str, int badcheck));
3559 double
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) \
3583 switch (val) { \
3584 case Qnil: \
3585 rb_raise_static(rb_eTypeError, pre "nil" post); \
3586 case Qtrue: \
3587 rb_raise_static(rb_eTypeError, pre "true" post); \
3588 case Qfalse: \
3589 rb_raise_static(rb_eTypeError, pre "false" post); \
3591 /*! \endcond */
3593 static inline void
3594 conversion_to_float(VALUE val)
3596 special_const_to_float(val, "can't convert ", " into Float");
3599 static inline void
3600 implicit_conversion_to_float(VALUE val)
3602 special_const_to_float(val, "no implicit conversion to float from ", "");
3605 static int
3606 to_float(VALUE *valp, int raise_exception)
3608 VALUE val = *valp;
3609 if (SPECIAL_CONST_P(val)) {
3610 if (FIXNUM_P(val)) {
3611 *valp = DBL2NUM(fix2dbl_without_to_f(val));
3612 return T_FLOAT;
3614 else if (FLONUM_P(val)) {
3615 return T_FLOAT;
3617 else if (raise_exception) {
3618 conversion_to_float(val);
3621 else {
3622 int type = BUILTIN_TYPE(val);
3623 switch (type) {
3624 case T_FLOAT:
3625 return T_FLOAT;
3626 case T_BIGNUM:
3627 *valp = DBL2NUM(big2dbl_without_to_f(val));
3628 return T_FLOAT;
3629 case T_RATIONAL:
3630 *valp = DBL2NUM(rat2dbl_without_to_f(val));
3631 return T_FLOAT;
3632 case T_STRING:
3633 return T_STRING;
3636 return T_NONE;
3639 static VALUE
3640 convert_type_to_float_protected(VALUE val)
3642 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3645 static VALUE
3646 rb_convert_to_float(VALUE val, int raise_exception)
3648 switch (to_float(&val, raise_exception)) {
3649 case T_FLOAT:
3650 return val;
3651 case T_STRING:
3652 if (!raise_exception) {
3653 int e = 0;
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));
3658 case T_NONE:
3659 if (SPECIAL_CONST_P(val) && !raise_exception)
3660 return Qnil;
3663 if (!raise_exception) {
3664 int state;
3665 VALUE result = rb_protect(convert_type_to_float_protected, val, &state);
3666 if (state) rb_set_errinfo(Qnil);
3667 return result;
3670 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3673 FUNC_MINIMIZED(VALUE rb_Float(VALUE val));
3675 VALUE
3676 rb_Float(VALUE val)
3678 return rb_convert_to_float(val, TRUE);
3681 static VALUE
3682 rb_f_float1(rb_execution_context_t *ec, VALUE obj, VALUE arg)
3684 return rb_convert_to_float(arg, TRUE);
3687 static VALUE
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);
3694 static VALUE
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",
3699 rb_obj_class(val));
3701 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3704 VALUE
3705 rb_to_float(VALUE val)
3707 switch (to_float(&val, TRUE)) {
3708 case T_FLOAT:
3709 return val;
3711 return numeric_to_float(val);
3714 VALUE
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)) {
3719 return Qnil;
3721 return rb_check_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3724 static inline int
3725 basic_to_f_p(VALUE klass)
3727 return rb_method_basic_definition_p(klass, id_to_f);
3730 /*! \private */
3731 double
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);
3742 else {
3743 conversion_to_float(val);
3746 else {
3747 switch (BUILTIN_TYPE(val)) {
3748 case T_FLOAT:
3749 return rb_float_noflonum_value(val);
3750 case T_BIGNUM:
3751 if (basic_to_f_p(rb_cInteger))
3752 return big2dbl_without_to_f(val);
3753 break;
3754 case T_RATIONAL:
3755 if (basic_to_f_p(rb_cRational))
3756 return rat2dbl_without_to_f(val);
3757 break;
3758 default:
3759 break;
3762 val = numeric_to_float(val);
3763 return RFLOAT_VALUE(val);
3766 double
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);
3776 else {
3777 implicit_conversion_to_float(val);
3780 else {
3781 switch (BUILTIN_TYPE(val)) {
3782 case T_FLOAT:
3783 return rb_float_noflonum_value(val);
3784 case T_BIGNUM:
3785 return big2dbl_without_to_f(val);
3786 case T_RATIONAL:
3787 return rat2dbl_without_to_f(val);
3788 case T_STRING:
3789 rb_raise(rb_eTypeError, "no implicit conversion to float from string");
3790 default:
3791 break;
3794 val = rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3795 return RFLOAT_VALUE(val);
3798 VALUE
3799 rb_String(VALUE val)
3801 VALUE tmp = rb_check_string_type(val);
3802 if (NIL_P(tmp))
3803 tmp = rb_convert_type_with_id(val, T_STRING, "String", idTo_s);
3804 return tmp;
3809 * call-seq:
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.
3824 static VALUE
3825 rb_f_string(VALUE obj, VALUE arg)
3827 return rb_String(arg);
3830 VALUE
3831 rb_Array(VALUE val)
3833 VALUE tmp = rb_check_array_type(val);
3835 if (NIL_P(tmp)) {
3836 tmp = rb_check_to_array(val);
3837 if (NIL_P(tmp)) {
3838 return rb_ary_new3(1, val);
3841 return tmp;
3845 * call-seq:
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]
3864 static VALUE
3865 rb_f_array(VALUE obj, VALUE arg)
3867 return rb_Array(arg);
3871 * Equivalent to \c Kernel\#Hash in Ruby
3873 VALUE
3874 rb_Hash(VALUE val)
3876 VALUE tmp;
3878 if (NIL_P(val)) return rb_hash_new();
3879 tmp = rb_check_hash_type(val);
3880 if (NIL_P(tmp)) {
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));
3885 return tmp;
3889 * call-seq:
3890 * Hash(object) -> object or new_hash
3892 * Returns a hash converted from +object+.
3894 * - If +object+ is:
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.
3902 * Examples:
3904 * Hash({foo: 0, bar: 1}) # => {:foo=>0, :bar=>1}
3905 * Hash(nil) # => {}
3906 * Hash([]) # => {}
3910 static VALUE
3911 rb_f_hash(VALUE obj, VALUE arg)
3913 return rb_Hash(arg);
3916 /*! \private */
3917 struct dig_method {
3918 VALUE klass;
3919 int basic;
3922 static ID id_dig;
3924 static int
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;
3935 static void
3936 no_dig_method(int found, VALUE recv, ID mid, int argc, const VALUE *argv, VALUE data)
3938 if (!found) {
3939 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not have #dig method",
3940 CLASS_OF(data));
3944 /*! \private */
3945 VALUE
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)) {
3954 case T_HASH:
3955 if (dig_basic_p(obj, &hash)) {
3956 obj = rb_hash_aref(obj, *argv);
3957 continue;
3959 break;
3960 case T_ARRAY:
3961 if (dig_basic_p(obj, &ary)) {
3962 obj = rb_ary_at(obj, *argv);
3963 continue;
3965 break;
3966 case T_STRUCT:
3967 if (dig_basic_p(obj, &strt)) {
3968 obj = rb_struct_lookup(obj, *argv);
3969 continue;
3971 break;
3972 default:
3973 break;
3976 return rb_check_funcall_with_hook_kw(obj, id_dig, argc, argv,
3977 no_dig_method, obj,
3978 RB_NO_KEYWORDS);
3980 return obj;
3984 * call-seq:
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].
3994 static VALUE
3995 f_sprintf(int c, const VALUE *v, VALUE _)
3997 return rb_f_sprintf(c, v);
4000 static VALUE
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
4010 * class Class.
4012 * Typically, you create a new class by using:
4014 * class Name
4015 * # some code describing the class behavior
4016 * end
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:
4025 * class Class
4026 * alias old_new new
4027 * def new(*args)
4028 * print "Creating a new ", self.name, "\n"
4029 * old_new(*args)
4030 * end
4031 * end
4033 * class Name
4034 * end
4036 * n = Name.new
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'.
4046 * +---------+ +-...
4047 * | | |
4048 * BasicObject-----|-->(BasicObject)-------|-...
4049 * ^ | ^ |
4050 * | | | |
4051 * Object---------|----->(Object)---------|-...
4052 * ^ | ^ |
4053 * | | | |
4054 * +-------+ | +--------+ |
4055 * | | | | | |
4056 * | Module-|---------|--->(Module)-|-...
4057 * | ^ | | ^ |
4058 * | | | | | |
4059 * | Class-|---------|---->(Class)-|-...
4060 * | ^ | | ^ |
4061 * | +---+ | +----+
4062 * | |
4063 * obj--->OtherClass---------->(OtherClass)-----------...
4068 /* Document-class: BasicObject
4070 * BasicObject is the parent class of all classes in Ruby. It's an explicit
4071 * blank class.
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
4076 * avoided.
4078 * To avoid polluting BasicObject for other users an appropriately named
4079 * subclass of BasicObject should be created instead of directly modifying
4080 * BasicObject:
4082 * class MyObjectSystem < BasicObject
4083 * end
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)
4101 * end
4103 * def respond_to_missing?(name, include_private = false)
4104 * DELEGATE.include?(name)
4105 * end
4106 * end
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)
4117 * end
4118 * end
4120 * === What's Here
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>).
4155 * == What's Here
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]
4168 * === Querying
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
4183 * in +self+.
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
4197 * in +self+.
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+.
4217 * === Other
4219 * - #clone: Returns a shallow copy of +self+, including singleton class
4220 * and frozen state.
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+.
4239 void
4240 InitVM_Object(void)
4242 Init_class_hierarchy();
4244 #if 0
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);
4251 #endif
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"
4275 * == What's Here
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]
4292 * === Converting
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.
4302 * === Querying
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
4306 * method is called.
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.
4320 * === Exiting
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.
4329 * === Exceptions
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.
4336 * === \IO
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.
4351 * === Procs
4353 * - #lambda: Returns a lambda proc for the given block.
4354 * - #proc: Returns a new Proc; equivalent to Proc.new.
4356 * === Tracing
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.
4363 * === Subprocesses
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
4370 * for completion.
4371 * - #system: Executes the given command in a subshell.
4373 * === Loading
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.
4382 * === Yielding
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.
4394 * === Other
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"
4572 void
4573 Init_Object(void)
4575 id_dig = rb_intern_const("dig");
4576 InitVM(Object);
4580 * \}