* 2022-01-18 [ci skip]
[ruby-80x24.org.git] / object.c
blobef8a855dfbceab112553d6d0ab4e1d59a29a11d8
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/symbol.h"
35 #include "internal/variable.h"
36 #include "probes.h"
37 #include "ruby/encoding.h"
38 #include "ruby/st.h"
39 #include "ruby/util.h"
40 #include "ruby/assert.h"
41 #include "builtin.h"
43 /*!
44 * \addtogroup object
45 * \{
48 VALUE rb_cBasicObject;
49 VALUE rb_mKernel;
50 VALUE rb_cObject;
51 VALUE rb_cModule;
52 VALUE rb_cClass;
53 VALUE rb_cRefinement;
55 VALUE rb_cNilClass;
56 VALUE rb_cTrueClass;
57 VALUE rb_cFalseClass;
59 static VALUE rb_cNilClass_to_s;
60 static VALUE rb_cTrueClass_to_s;
61 static VALUE rb_cFalseClass_to_s;
63 /*! \cond INTERNAL_MACRO */
65 #define id_eq idEq
66 #define id_eql idEqlP
67 #define id_match idEqTilde
68 #define id_inspect idInspect
69 #define id_init_copy idInitialize_copy
70 #define id_init_clone idInitialize_clone
71 #define id_init_dup idInitialize_dup
72 #define id_const_missing idConst_missing
73 #define id_to_f idTo_f
75 #define CLASS_OR_MODULE_P(obj) \
76 (!SPECIAL_CONST_P(obj) && \
77 (BUILTIN_TYPE(obj) == T_CLASS || BUILTIN_TYPE(obj) == T_MODULE))
79 /*! \endcond */
81 VALUE
82 rb_obj_hide(VALUE obj)
84 if (!SPECIAL_CONST_P(obj)) {
85 RBASIC_CLEAR_CLASS(obj);
87 return obj;
90 VALUE
91 rb_obj_reveal(VALUE obj, VALUE klass)
93 if (!SPECIAL_CONST_P(obj)) {
94 RBASIC_SET_CLASS(obj, klass);
96 return obj;
99 VALUE
100 rb_obj_setup(VALUE obj, VALUE klass, VALUE type)
102 RBASIC(obj)->flags = type;
103 RBASIC_SET_CLASS(obj, klass);
104 return obj;
108 * call-seq:
109 * obj === other -> true or false
111 * Case Equality -- For class Object, effectively the same as calling
112 * <code>#==</code>, but typically overridden by descendants to provide
113 * meaningful semantics in +case+ statements.
115 #define case_equal rb_equal
116 /* The default implementation of #=== is
117 * to call #== with the rb_equal() optimization. */
119 VALUE
120 rb_equal(VALUE obj1, VALUE obj2)
122 VALUE result;
124 if (obj1 == obj2) return Qtrue;
125 result = rb_equal_opt(obj1, obj2);
126 if (result == Qundef) {
127 result = rb_funcall(obj1, id_eq, 1, obj2);
129 return RBOOL(RTEST(result));
133 rb_eql(VALUE obj1, VALUE obj2)
135 VALUE result;
137 if (obj1 == obj2) return Qtrue;
138 result = rb_eql_opt(obj1, obj2);
139 if (result == Qundef) {
140 result = rb_funcall(obj1, id_eql, 1, obj2);
142 return RBOOL(RTEST(result));
146 * call-seq:
147 * obj == other -> true or false
148 * obj.equal?(other) -> true or false
149 * obj.eql?(other) -> true or false
151 * Equality --- At the Object level, #== returns <code>true</code>
152 * only if +obj+ and +other+ are the same object. Typically, this
153 * method is overridden in descendant classes to provide
154 * class-specific meaning.
156 * Unlike #==, the #equal? method should never be overridden by
157 * subclasses as it is used to determine object identity (that is,
158 * <code>a.equal?(b)</code> if and only if <code>a</code> is the same
159 * object as <code>b</code>):
161 * obj = "a"
162 * other = obj.dup
164 * obj == other #=> true
165 * obj.equal? other #=> false
166 * obj.equal? obj #=> true
168 * The #eql? method returns <code>true</code> if +obj+ and +other+
169 * refer to the same hash key. This is used by Hash to test members
170 * for equality. For any pair of objects where #eql? returns +true+,
171 * the #hash value of both objects must be equal. So any subclass
172 * that overrides #eql? should also override #hash appropriately.
174 * For objects of class Object, #eql? is synonymous
175 * with #==. Subclasses normally continue this tradition by aliasing
176 * #eql? to their overridden #== method, but there are exceptions.
177 * Numeric types, for example, perform type conversion across #==,
178 * but not across #eql?, so:
180 * 1 == 1.0 #=> true
181 * 1.eql? 1.0 #=> false
183 * \private
186 MJIT_FUNC_EXPORTED VALUE
187 rb_obj_equal(VALUE obj1, VALUE obj2)
189 return RBOOL(obj1 == obj2);
192 VALUE rb_obj_hash(VALUE obj);
195 * call-seq:
196 * !obj -> true or false
198 * Boolean negate.
200 * \private
204 MJIT_FUNC_EXPORTED VALUE
205 rb_obj_not(VALUE obj)
207 return RBOOL(!RTEST(obj));
211 * call-seq:
212 * obj != other -> true or false
214 * Returns true if two objects are not-equal, otherwise false.
216 * \private
220 MJIT_FUNC_EXPORTED VALUE
221 rb_obj_not_equal(VALUE obj1, VALUE obj2)
223 VALUE result = rb_funcall(obj1, id_eq, 1, obj2);
224 return rb_obj_not(result);
227 VALUE
228 rb_class_real(VALUE cl)
230 while (cl &&
231 ((RBASIC(cl)->flags & FL_SINGLETON) || BUILTIN_TYPE(cl) == T_ICLASS)) {
232 cl = RCLASS_SUPER(cl);
234 return cl;
237 VALUE
238 rb_obj_class(VALUE obj)
240 return rb_class_real(CLASS_OF(obj));
244 * call-seq:
245 * obj.singleton_class -> class
247 * Returns the singleton class of <i>obj</i>. This method creates
248 * a new singleton class if <i>obj</i> does not have one.
250 * If <i>obj</i> is <code>nil</code>, <code>true</code>, or
251 * <code>false</code>, it returns NilClass, TrueClass, or FalseClass,
252 * respectively.
253 * If <i>obj</i> is an Integer, a Float or a Symbol, it raises a TypeError.
255 * Object.new.singleton_class #=> #<Class:#<Object:0xb7ce1e24>>
256 * String.singleton_class #=> #<Class:String>
257 * nil.singleton_class #=> NilClass
260 static VALUE
261 rb_obj_singleton_class(VALUE obj)
263 return rb_singleton_class(obj);
266 /*! \private */
267 MJIT_FUNC_EXPORTED void
268 rb_obj_copy_ivar(VALUE dest, VALUE obj)
270 VALUE *dst_buf = 0;
271 VALUE *src_buf = 0;
272 uint32_t len = ROBJECT_EMBED_LEN_MAX;
274 if (RBASIC(obj)->flags & ROBJECT_EMBED) {
275 src_buf = ROBJECT(obj)->as.ary;
277 // embedded -> embedded
278 if (RBASIC(dest)->flags & ROBJECT_EMBED) {
279 dst_buf = ROBJECT(dest)->as.ary;
281 // embedded -> extended
282 else {
283 dst_buf = ROBJECT(dest)->as.heap.ivptr;
286 // extended -> extended
287 else {
288 uint32_t src_len = ROBJECT(obj)->as.heap.numiv;
289 uint32_t dst_len = ROBJECT(dest)->as.heap.numiv;
291 len = src_len < dst_len ? src_len : dst_len;
292 dst_buf = ROBJECT(dest)->as.heap.ivptr;
293 src_buf = ROBJECT(obj)->as.heap.ivptr;
296 MEMCPY(dst_buf, src_buf, VALUE, len);
299 static void
300 init_copy(VALUE dest, VALUE obj)
302 if (OBJ_FROZEN(dest)) {
303 rb_raise(rb_eTypeError, "[bug] frozen object (%s) allocated", rb_obj_classname(dest));
305 RBASIC(dest)->flags &= ~(T_MASK|FL_EXIVAR);
306 RBASIC(dest)->flags |= RBASIC(obj)->flags & (T_MASK|FL_EXIVAR);
307 rb_copy_wb_protected_attribute(dest, obj);
308 rb_copy_generic_ivar(dest, obj);
309 rb_gc_copy_finalizer(dest, obj);
310 if (RB_TYPE_P(obj, T_OBJECT)) {
311 rb_obj_copy_ivar(dest, obj);
315 static VALUE immutable_obj_clone(VALUE obj, VALUE kwfreeze);
316 static VALUE mutable_obj_clone(VALUE obj, VALUE kwfreeze);
317 PUREFUNC(static inline int special_object_p(VALUE obj)); /*!< \private */
318 static inline int
319 special_object_p(VALUE obj)
321 if (SPECIAL_CONST_P(obj)) return TRUE;
322 switch (BUILTIN_TYPE(obj)) {
323 case T_BIGNUM:
324 case T_FLOAT:
325 case T_SYMBOL:
326 case T_RATIONAL:
327 case T_COMPLEX:
328 /* not a comprehensive list */
329 return TRUE;
330 default:
331 return FALSE;
335 static VALUE
336 obj_freeze_opt(VALUE freeze)
338 switch (freeze) {
339 case Qfalse:
340 case Qtrue:
341 case Qnil:
342 break;
343 default:
344 rb_raise(rb_eArgError, "unexpected value for freeze: %"PRIsVALUE, rb_obj_class(freeze));
347 return freeze;
350 static VALUE
351 rb_obj_clone2(rb_execution_context_t *ec, VALUE obj, VALUE freeze)
353 VALUE kwfreeze = obj_freeze_opt(freeze);
354 if (!special_object_p(obj))
355 return mutable_obj_clone(obj, kwfreeze);
356 return immutable_obj_clone(obj, kwfreeze);
359 /*! \private */
360 VALUE
361 rb_immutable_obj_clone(int argc, VALUE *argv, VALUE obj)
363 VALUE kwfreeze = rb_get_freeze_opt(argc, argv);
364 return immutable_obj_clone(obj, kwfreeze);
367 VALUE
368 rb_get_freeze_opt(int argc, VALUE *argv)
370 static ID keyword_ids[1];
371 VALUE opt;
372 VALUE kwfreeze = Qnil;
374 if (!keyword_ids[0]) {
375 CONST_ID(keyword_ids[0], "freeze");
377 rb_scan_args(argc, argv, "0:", &opt);
378 if (!NIL_P(opt)) {
379 rb_get_kwargs(opt, keyword_ids, 0, 1, &kwfreeze);
380 if (kwfreeze != Qundef)
381 kwfreeze = obj_freeze_opt(kwfreeze);
383 return kwfreeze;
386 static VALUE
387 immutable_obj_clone(VALUE obj, VALUE kwfreeze)
389 if (kwfreeze == Qfalse)
390 rb_raise(rb_eArgError, "can't unfreeze %"PRIsVALUE,
391 rb_obj_class(obj));
392 return obj;
395 static VALUE
396 mutable_obj_clone(VALUE obj, VALUE kwfreeze)
398 VALUE clone, singleton;
399 VALUE argv[2];
401 clone = rb_obj_alloc(rb_obj_class(obj));
403 singleton = rb_singleton_class_clone_and_attach(obj, clone);
404 RBASIC_SET_CLASS(clone, singleton);
405 if (FL_TEST(singleton, FL_SINGLETON)) {
406 rb_singleton_class_attached(singleton, clone);
409 init_copy(clone, obj);
411 switch (kwfreeze) {
412 case Qnil:
413 rb_funcall(clone, id_init_clone, 1, obj);
414 RBASIC(clone)->flags |= RBASIC(obj)->flags & FL_FREEZE;
415 break;
416 case Qtrue:
418 static VALUE freeze_true_hash;
419 if (!freeze_true_hash) {
420 freeze_true_hash = rb_hash_new();
421 rb_gc_register_mark_object(freeze_true_hash);
422 rb_hash_aset(freeze_true_hash, ID2SYM(idFreeze), Qtrue);
423 rb_obj_freeze(freeze_true_hash);
426 argv[0] = obj;
427 argv[1] = freeze_true_hash;
428 rb_funcallv_kw(clone, id_init_clone, 2, argv, RB_PASS_KEYWORDS);
429 RBASIC(clone)->flags |= FL_FREEZE;
430 break;
432 case Qfalse:
434 static VALUE freeze_false_hash;
435 if (!freeze_false_hash) {
436 freeze_false_hash = rb_hash_new();
437 rb_gc_register_mark_object(freeze_false_hash);
438 rb_hash_aset(freeze_false_hash, ID2SYM(idFreeze), Qfalse);
439 rb_obj_freeze(freeze_false_hash);
442 argv[0] = obj;
443 argv[1] = freeze_false_hash;
444 rb_funcallv_kw(clone, id_init_clone, 2, argv, RB_PASS_KEYWORDS);
445 break;
447 default:
448 rb_bug("invalid kwfreeze passed to mutable_obj_clone");
451 return clone;
454 VALUE
455 rb_obj_clone(VALUE obj)
457 if (special_object_p(obj)) return obj;
458 return mutable_obj_clone(obj, Qnil);
462 * call-seq:
463 * obj.dup -> an_object
465 * Produces a shallow copy of <i>obj</i>---the instance variables of
466 * <i>obj</i> are copied, but not the objects they reference.
468 * This method may have class-specific behavior. If so, that
469 * behavior will be documented under the #+initialize_copy+ method of
470 * the class.
472 * === on dup vs clone
474 * In general, #clone and #dup may have different semantics in
475 * descendant classes. While #clone is used to duplicate an object,
476 * including its internal state, #dup typically uses the class of the
477 * descendant object to create the new instance.
479 * When using #dup, any modules that the object has been extended with will not
480 * be copied.
482 * class Klass
483 * attr_accessor :str
484 * end
486 * module Foo
487 * def foo; 'foo'; end
488 * end
490 * s1 = Klass.new #=> #<Klass:0x401b3a38>
491 * s1.extend(Foo) #=> #<Klass:0x401b3a38>
492 * s1.foo #=> "foo"
494 * s2 = s1.clone #=> #<Klass:0x401be280>
495 * s2.foo #=> "foo"
497 * s3 = s1.dup #=> #<Klass:0x401c1084>
498 * s3.foo #=> NoMethodError: undefined method `foo' for #<Klass:0x401c1084>
500 VALUE
501 rb_obj_dup(VALUE obj)
503 VALUE dup;
505 if (special_object_p(obj)) {
506 return obj;
508 dup = rb_obj_alloc(rb_obj_class(obj));
509 init_copy(dup, obj);
510 rb_funcall(dup, id_init_dup, 1, obj);
512 return dup;
516 * call-seq:
517 * obj.itself -> obj
519 * Returns the receiver.
521 * string = "my string"
522 * string.itself.object_id == string.object_id #=> true
526 static VALUE
527 rb_obj_itself(VALUE obj)
529 return obj;
532 VALUE
533 rb_obj_size(VALUE self, VALUE args, VALUE obj)
535 return LONG2FIX(1);
538 static VALUE
539 block_given_p(rb_execution_context_t *ec, VALUE self)
541 return RBOOL(rb_block_given_p());
545 * :nodoc:
547 * Default implementation of \c #initialize_copy
548 * \param[in,out] obj the receiver being initialized
549 * \param[in] orig the object to be copied from.
552 VALUE
553 rb_obj_init_copy(VALUE obj, VALUE orig)
555 if (obj == orig) return obj;
556 rb_check_frozen(obj);
557 if (TYPE(obj) != TYPE(orig) || rb_obj_class(obj) != rb_obj_class(orig)) {
558 rb_raise(rb_eTypeError, "initialize_copy should take same class object");
560 return obj;
564 * :nodoc:
566 * Default implementation of \c #initialize_dup
568 * \param[in,out] obj the receiver being initialized
569 * \param[in] orig the object to be dup from.
572 VALUE
573 rb_obj_init_dup_clone(VALUE obj, VALUE orig)
575 rb_funcall(obj, id_init_copy, 1, orig);
576 return obj;
580 * :nodoc:
582 * Default implementation of \c #initialize_clone
584 * \param[in] The number of arguments
585 * \param[in] The array of arguments
586 * \param[in] obj the receiver being initialized
589 static VALUE
590 rb_obj_init_clone(int argc, VALUE *argv, VALUE obj)
592 VALUE orig, opts;
593 if (rb_scan_args(argc, argv, "1:", &orig, &opts) < argc) {
594 /* Ignore a freeze keyword */
595 rb_get_freeze_opt(1, &opts);
597 rb_funcall(obj, id_init_copy, 1, orig);
598 return obj;
602 * call-seq:
603 * obj.to_s -> string
605 * Returns a string representing <i>obj</i>. The default #to_s prints
606 * the object's class and an encoding of the object id. As a special
607 * case, the top-level object that is the initial execution context
608 * of Ruby programs returns ``main''.
611 VALUE
612 rb_any_to_s(VALUE obj)
614 VALUE str;
615 VALUE cname = rb_class_name(CLASS_OF(obj));
617 str = rb_sprintf("#<%"PRIsVALUE":%p>", cname, (void*)obj);
619 return str;
622 VALUE
623 rb_inspect(VALUE obj)
625 VALUE str = rb_obj_as_string(rb_funcallv(obj, id_inspect, 0, 0));
627 rb_encoding *enc = rb_default_internal_encoding();
628 if (enc == NULL) enc = rb_default_external_encoding();
629 if (!rb_enc_asciicompat(enc)) {
630 if (!rb_enc_str_asciionly_p(str))
631 return rb_str_escape(str);
632 return str;
634 if (rb_enc_get(str) != enc && !rb_enc_str_asciionly_p(str))
635 return rb_str_escape(str);
636 return str;
639 static int
640 inspect_i(st_data_t k, st_data_t v, st_data_t a)
642 ID id = (ID)k;
643 VALUE value = (VALUE)v;
644 VALUE str = (VALUE)a;
646 /* need not to show internal data */
647 if (CLASS_OF(value) == 0) return ST_CONTINUE;
648 if (!rb_is_instance_id(id)) return ST_CONTINUE;
649 if (RSTRING_PTR(str)[0] == '-') { /* first element */
650 RSTRING_PTR(str)[0] = '#';
651 rb_str_cat2(str, " ");
653 else {
654 rb_str_cat2(str, ", ");
656 rb_str_catf(str, "%"PRIsVALUE"=%+"PRIsVALUE,
657 rb_id2str(id), value);
659 return ST_CONTINUE;
662 static VALUE
663 inspect_obj(VALUE obj, VALUE str, int recur)
665 if (recur) {
666 rb_str_cat2(str, " ...");
668 else {
669 rb_ivar_foreach(obj, inspect_i, str);
671 rb_str_cat2(str, ">");
672 RSTRING_PTR(str)[0] = '#';
674 return str;
678 * call-seq:
679 * obj.inspect -> string
681 * Returns a string containing a human-readable representation of <i>obj</i>.
682 * The default #inspect shows the object's class name, an encoding of
683 * its memory address, and a list of the instance variables and their
684 * values (by calling #inspect on each of them). User defined classes
685 * should override this method to provide a better representation of
686 * <i>obj</i>. When overriding this method, it should return a string
687 * whose encoding is compatible with the default external encoding.
689 * [ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]"
690 * Time.new.inspect #=> "2008-03-08 19:43:39 +0900"
692 * class Foo
693 * end
694 * Foo.new.inspect #=> "#<Foo:0x0300c868>"
696 * class Bar
697 * def initialize
698 * @bar = 1
699 * end
700 * end
701 * Bar.new.inspect #=> "#<Bar:0x0300c868 @bar=1>"
704 static VALUE
705 rb_obj_inspect(VALUE obj)
707 if (rb_ivar_count(obj) > 0) {
708 VALUE str;
709 VALUE c = rb_class_name(CLASS_OF(obj));
711 str = rb_sprintf("-<%"PRIsVALUE":%p", c, (void*)obj);
712 return rb_exec_recursive(inspect_obj, obj, str);
714 else {
715 return rb_any_to_s(obj);
719 static VALUE
720 class_or_module_required(VALUE c)
722 switch (OBJ_BUILTIN_TYPE(c)) {
723 case T_MODULE:
724 case T_CLASS:
725 case T_ICLASS:
726 break;
728 default:
729 rb_raise(rb_eTypeError, "class or module required");
731 return c;
734 static VALUE class_search_ancestor(VALUE cl, VALUE c);
737 * call-seq:
738 * obj.instance_of?(class) -> true or false
740 * Returns <code>true</code> if <i>obj</i> is an instance of the given
741 * class. See also Object#kind_of?.
743 * class A; end
744 * class B < A; end
745 * class C < B; end
747 * b = B.new
748 * b.instance_of? A #=> false
749 * b.instance_of? B #=> true
750 * b.instance_of? C #=> false
753 VALUE
754 rb_obj_is_instance_of(VALUE obj, VALUE c)
756 c = class_or_module_required(c);
757 return RBOOL(rb_obj_class(obj) == c);
762 * call-seq:
763 * obj.is_a?(class) -> true or false
764 * obj.kind_of?(class) -> true or false
766 * Returns <code>true</code> if <i>class</i> is the class of
767 * <i>obj</i>, or if <i>class</i> is one of the superclasses of
768 * <i>obj</i> or modules included in <i>obj</i>.
770 * module M; end
771 * class A
772 * include M
773 * end
774 * class B < A; end
775 * class C < B; end
777 * b = B.new
778 * b.is_a? A #=> true
779 * b.is_a? B #=> true
780 * b.is_a? C #=> false
781 * b.is_a? M #=> true
783 * b.kind_of? A #=> true
784 * b.kind_of? B #=> true
785 * b.kind_of? C #=> false
786 * b.kind_of? M #=> true
789 VALUE
790 rb_obj_is_kind_of(VALUE obj, VALUE c)
792 VALUE cl = CLASS_OF(obj);
794 // Note: YJIT needs this function to never allocate and never raise when
795 // `c` is a class or a module.
796 c = class_or_module_required(c);
797 return RBOOL(class_search_ancestor(cl, RCLASS_ORIGIN(c)));
800 static VALUE
801 class_search_ancestor(VALUE cl, VALUE c)
803 while (cl) {
804 if (cl == c || RCLASS_M_TBL(cl) == RCLASS_M_TBL(c))
805 return cl;
806 cl = RCLASS_SUPER(cl);
808 return 0;
811 /*! \private */
812 VALUE
813 rb_class_search_ancestor(VALUE cl, VALUE c)
815 cl = class_or_module_required(cl);
816 c = class_or_module_required(c);
817 return class_search_ancestor(cl, RCLASS_ORIGIN(c));
822 * Document-method: inherited
824 * call-seq:
825 * inherited(subclass)
827 * Callback invoked whenever a subclass of the current class is created.
829 * Example:
831 * class Foo
832 * def self.inherited(subclass)
833 * puts "New subclass: #{subclass}"
834 * end
835 * end
837 * class Bar < Foo
838 * end
840 * class Baz < Bar
841 * end
843 * <em>produces:</em>
845 * New subclass: Bar
846 * New subclass: Baz
848 #define rb_obj_class_inherited rb_obj_dummy1
850 /* Document-method: method_added
852 * call-seq:
853 * method_added(method_name)
855 * Invoked as a callback whenever an instance method is added to the
856 * receiver.
858 * module Chatty
859 * def self.method_added(method_name)
860 * puts "Adding #{method_name.inspect}"
861 * end
862 * def self.some_class_method() end
863 * def some_instance_method() end
864 * end
866 * <em>produces:</em>
868 * Adding :some_instance_method
871 #define rb_obj_mod_method_added rb_obj_dummy1
873 /* Document-method: method_removed
875 * call-seq:
876 * method_removed(method_name)
878 * Invoked as a callback whenever an instance method is removed from the
879 * receiver.
881 * module Chatty
882 * def self.method_removed(method_name)
883 * puts "Removing #{method_name.inspect}"
884 * end
885 * def self.some_class_method() end
886 * def some_instance_method() end
887 * class << self
888 * remove_method :some_class_method
889 * end
890 * remove_method :some_instance_method
891 * end
893 * <em>produces:</em>
895 * Removing :some_instance_method
898 #define rb_obj_mod_method_removed rb_obj_dummy1
900 /* Document-method: method_undefined
902 * call-seq:
903 * method_undefined(method_name)
905 * Invoked as a callback whenever an instance method is undefined from the
906 * receiver.
908 * module Chatty
909 * def self.method_undefined(method_name)
910 * puts "Undefining #{method_name.inspect}"
911 * end
912 * def self.some_class_method() end
913 * def some_instance_method() end
914 * class << self
915 * undef_method :some_class_method
916 * end
917 * undef_method :some_instance_method
918 * end
920 * <em>produces:</em>
922 * Undefining :some_instance_method
925 #define rb_obj_mod_method_undefined rb_obj_dummy1
928 * Document-method: singleton_method_added
930 * call-seq:
931 * singleton_method_added(symbol)
933 * Invoked as a callback whenever a singleton method is added to the
934 * receiver.
936 * module Chatty
937 * def Chatty.singleton_method_added(id)
938 * puts "Adding #{id.id2name}"
939 * end
940 * def self.one() end
941 * def two() end
942 * def Chatty.three() end
943 * end
945 * <em>produces:</em>
947 * Adding singleton_method_added
948 * Adding one
949 * Adding three
952 #define rb_obj_singleton_method_added rb_obj_dummy1
955 * Document-method: singleton_method_removed
957 * call-seq:
958 * singleton_method_removed(symbol)
960 * Invoked as a callback whenever a singleton method is removed from
961 * the receiver.
963 * module Chatty
964 * def Chatty.singleton_method_removed(id)
965 * puts "Removing #{id.id2name}"
966 * end
967 * def self.one() end
968 * def two() end
969 * def Chatty.three() end
970 * class << self
971 * remove_method :three
972 * remove_method :one
973 * end
974 * end
976 * <em>produces:</em>
978 * Removing three
979 * Removing one
981 #define rb_obj_singleton_method_removed rb_obj_dummy1
984 * Document-method: singleton_method_undefined
986 * call-seq:
987 * singleton_method_undefined(symbol)
989 * Invoked as a callback whenever a singleton method is undefined in
990 * the receiver.
992 * module Chatty
993 * def Chatty.singleton_method_undefined(id)
994 * puts "Undefining #{id.id2name}"
995 * end
996 * def Chatty.one() end
997 * class << self
998 * undef_method(:one)
999 * end
1000 * end
1002 * <em>produces:</em>
1004 * Undefining one
1006 #define rb_obj_singleton_method_undefined rb_obj_dummy1
1008 /* Document-method: const_added
1010 * call-seq:
1011 * const_added(const_name)
1013 * Invoked as a callback whenever a constant is assigned on the receiver
1015 * module Chatty
1016 * def self.const_added(const_name)
1017 * super
1018 * puts "Added #{const_name.inspect}"
1019 * end
1020 * FOO = 1
1021 * end
1023 * <em>produces:</em>
1025 * Added :FOO
1028 #define rb_obj_mod_const_added rb_obj_dummy1
1031 * Document-method: extended
1033 * call-seq:
1034 * extended(othermod)
1036 * The equivalent of <tt>included</tt>, but for extended modules.
1038 * module A
1039 * def self.extended(mod)
1040 * puts "#{self} extended in #{mod}"
1041 * end
1042 * end
1043 * module Enumerable
1044 * extend A
1045 * end
1046 * # => prints "A extended in Enumerable"
1048 #define rb_obj_mod_extended rb_obj_dummy1
1051 * Document-method: included
1053 * call-seq:
1054 * included(othermod)
1056 * Callback invoked whenever the receiver is included in another
1057 * module or class. This should be used in preference to
1058 * <tt>Module.append_features</tt> if your code wants to perform some
1059 * action when a module is included in another.
1061 * module A
1062 * def A.included(mod)
1063 * puts "#{self} included in #{mod}"
1064 * end
1065 * end
1066 * module Enumerable
1067 * include A
1068 * end
1069 * # => prints "A included in Enumerable"
1071 #define rb_obj_mod_included rb_obj_dummy1
1074 * Document-method: prepended
1076 * call-seq:
1077 * prepended(othermod)
1079 * The equivalent of <tt>included</tt>, but for prepended modules.
1081 * module A
1082 * def self.prepended(mod)
1083 * puts "#{self} prepended to #{mod}"
1084 * end
1085 * end
1086 * module Enumerable
1087 * prepend A
1088 * end
1089 * # => prints "A prepended to Enumerable"
1091 #define rb_obj_mod_prepended rb_obj_dummy1
1094 * Document-method: initialize
1096 * call-seq:
1097 * BasicObject.new
1099 * Returns a new BasicObject.
1101 #define rb_obj_initialize rb_obj_dummy0
1104 * Not documented
1107 static VALUE
1108 rb_obj_dummy(void)
1110 return Qnil;
1113 static VALUE
1114 rb_obj_dummy0(VALUE _)
1116 return rb_obj_dummy();
1119 static VALUE
1120 rb_obj_dummy1(VALUE _x, VALUE _y)
1122 return rb_obj_dummy();
1126 * call-seq:
1127 * obj.freeze -> obj
1129 * Prevents further modifications to <i>obj</i>. A
1130 * FrozenError will be raised if modification is attempted.
1131 * There is no way to unfreeze a frozen object. See also
1132 * Object#frozen?.
1134 * This method returns self.
1136 * a = [ "a", "b", "c" ]
1137 * a.freeze
1138 * a << "z"
1140 * <em>produces:</em>
1142 * prog.rb:3:in `<<': can't modify frozen Array (FrozenError)
1143 * from prog.rb:3
1145 * Objects of the following classes are always frozen: Integer,
1146 * Float, Symbol.
1149 VALUE
1150 rb_obj_freeze(VALUE obj)
1152 if (!OBJ_FROZEN(obj)) {
1153 OBJ_FREEZE(obj);
1154 if (SPECIAL_CONST_P(obj)) {
1155 rb_bug("special consts should be frozen.");
1158 return obj;
1161 VALUE
1162 rb_obj_frozen_p(VALUE obj)
1164 return RBOOL(OBJ_FROZEN(obj));
1169 * Document-class: NilClass
1171 * The class of the singleton object <code>nil</code>.
1175 * call-seq:
1176 * nil.to_s -> ""
1178 * Always returns the empty string.
1181 MJIT_FUNC_EXPORTED VALUE
1182 rb_nil_to_s(VALUE obj)
1184 return rb_cNilClass_to_s;
1188 * Document-method: to_a
1190 * call-seq:
1191 * nil.to_a -> []
1193 * Always returns an empty array.
1195 * nil.to_a #=> []
1198 static VALUE
1199 nil_to_a(VALUE obj)
1201 return rb_ary_new2(0);
1205 * Document-method: to_h
1207 * call-seq:
1208 * nil.to_h -> {}
1210 * Always returns an empty hash.
1212 * nil.to_h #=> {}
1215 static VALUE
1216 nil_to_h(VALUE obj)
1218 return rb_hash_new();
1222 * call-seq:
1223 * nil.inspect -> "nil"
1225 * Always returns the string "nil".
1228 static VALUE
1229 nil_inspect(VALUE obj)
1231 return rb_usascii_str_new2("nil");
1235 * call-seq:
1236 * nil =~ other -> nil
1238 * Dummy pattern matching -- always returns nil.
1240 * This method makes it possible to `while gets =~ /re/ do`.
1243 static VALUE
1244 nil_match(VALUE obj1, VALUE obj2)
1246 return Qnil;
1249 /***********************************************************************
1250 * Document-class: TrueClass
1252 * The global value <code>true</code> is the only instance of class
1253 * TrueClass and represents a logically true value in
1254 * boolean expressions. The class provides operators allowing
1255 * <code>true</code> to be used in logical expressions.
1260 * call-seq:
1261 * true.to_s -> "true"
1263 * The string representation of <code>true</code> is "true".
1266 MJIT_FUNC_EXPORTED VALUE
1267 rb_true_to_s(VALUE obj)
1269 return rb_cTrueClass_to_s;
1274 * call-seq:
1275 * true & obj -> true or false
1277 * And---Returns <code>false</code> if <i>obj</i> is
1278 * <code>nil</code> or <code>false</code>, <code>true</code> otherwise.
1281 static VALUE
1282 true_and(VALUE obj, VALUE obj2)
1284 return RBOOL(RTEST(obj2));
1288 * call-seq:
1289 * true | obj -> true
1291 * Or---Returns <code>true</code>. As <i>obj</i> is an argument to
1292 * a method call, it is always evaluated; there is no short-circuit
1293 * evaluation in this case.
1295 * true | puts("or")
1296 * true || puts("logical or")
1298 * <em>produces:</em>
1300 * or
1303 static VALUE
1304 true_or(VALUE obj, VALUE obj2)
1306 return Qtrue;
1311 * call-seq:
1312 * true ^ obj -> !obj
1314 * Exclusive Or---Returns <code>true</code> if <i>obj</i> is
1315 * <code>nil</code> or <code>false</code>, <code>false</code>
1316 * otherwise.
1319 static VALUE
1320 true_xor(VALUE obj, VALUE obj2)
1322 return rb_obj_not(obj2);
1327 * Document-class: FalseClass
1329 * The global value <code>false</code> is the only instance of class
1330 * FalseClass and represents a logically false value in
1331 * boolean expressions. The class provides operators allowing
1332 * <code>false</code> to participate correctly in logical expressions.
1337 * call-seq:
1338 * false.to_s -> "false"
1340 * The string representation of <code>false</code> is "false".
1343 MJIT_FUNC_EXPORTED VALUE
1344 rb_false_to_s(VALUE obj)
1346 return rb_cFalseClass_to_s;
1350 * call-seq:
1351 * false & obj -> false
1352 * nil & obj -> false
1354 * And---Returns <code>false</code>. <i>obj</i> is always
1355 * evaluated as it is the argument to a method call---there is no
1356 * short-circuit evaluation in this case.
1359 static VALUE
1360 false_and(VALUE obj, VALUE obj2)
1362 return Qfalse;
1367 * call-seq:
1368 * false | obj -> true or false
1369 * nil | obj -> true or false
1371 * Or---Returns <code>false</code> if <i>obj</i> is
1372 * <code>nil</code> or <code>false</code>; <code>true</code> otherwise.
1375 #define false_or true_and
1378 * call-seq:
1379 * false ^ obj -> true or false
1380 * nil ^ obj -> true or false
1382 * Exclusive Or---If <i>obj</i> is <code>nil</code> or
1383 * <code>false</code>, returns <code>false</code>; otherwise, returns
1384 * <code>true</code>.
1388 #define false_xor true_and
1391 * call-seq:
1392 * nil.nil? -> true
1394 * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1397 static VALUE
1398 rb_true(VALUE obj)
1400 return Qtrue;
1404 * call-seq:
1405 * obj.nil? -> true or false
1407 * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1409 * Object.new.nil? #=> false
1410 * nil.nil? #=> true
1414 MJIT_FUNC_EXPORTED VALUE
1415 rb_false(VALUE obj)
1417 return Qfalse;
1421 * call-seq:
1422 * obj !~ other -> true or false
1424 * Returns true if two objects do not match (using the <i>=~</i>
1425 * method), otherwise false.
1428 static VALUE
1429 rb_obj_not_match(VALUE obj1, VALUE obj2)
1431 VALUE result = rb_funcall(obj1, id_match, 1, obj2);
1432 return rb_obj_not(result);
1437 * call-seq:
1438 * obj <=> other -> 0 or nil
1440 * Returns 0 if +obj+ and +other+ are the same object
1441 * or <code>obj == other</code>, otherwise nil.
1443 * The #<=> is used by various methods to compare objects, for example
1444 * Enumerable#sort, Enumerable#max etc.
1446 * Your implementation of #<=> should return one of the following values: -1, 0,
1447 * 1 or nil. -1 means self is smaller than other. 0 means self is equal to other.
1448 * 1 means self is bigger than other. Nil means the two values could not be
1449 * compared.
1451 * When you define #<=>, you can include Comparable to gain the
1452 * methods #<=, #<, #==, #>=, #> and #between?.
1454 static VALUE
1455 rb_obj_cmp(VALUE obj1, VALUE obj2)
1457 if (rb_equal(obj1, obj2))
1458 return INT2FIX(0);
1459 return Qnil;
1462 /***********************************************************************
1464 * Document-class: Module
1466 * A Module is a collection of methods and constants. The
1467 * methods in a module may be instance methods or module methods.
1468 * Instance methods appear as methods in a class when the module is
1469 * included, module methods do not. Conversely, module methods may be
1470 * called without creating an encapsulating object, while instance
1471 * methods may not. (See Module#module_function.)
1473 * In the descriptions that follow, the parameter <i>sym</i> refers
1474 * to a symbol, which is either a quoted string or a
1475 * Symbol (such as <code>:name</code>).
1477 * module Mod
1478 * include Math
1479 * CONST = 1
1480 * def meth
1481 * # ...
1482 * end
1483 * end
1484 * Mod.class #=> Module
1485 * Mod.constants #=> [:CONST, :PI, :E]
1486 * Mod.instance_methods #=> [:meth]
1491 * call-seq:
1492 * mod.to_s -> string
1494 * Returns a string representing this module or class. For basic
1495 * classes and modules, this is the name. For singletons, we
1496 * show information on the thing we're attached to as well.
1499 MJIT_FUNC_EXPORTED VALUE
1500 rb_mod_to_s(VALUE klass)
1502 ID id_defined_at;
1503 VALUE refined_class, defined_at;
1505 if (FL_TEST(klass, FL_SINGLETON)) {
1506 VALUE s = rb_usascii_str_new2("#<Class:");
1507 VALUE v = rb_ivar_get(klass, id__attached__);
1509 if (CLASS_OR_MODULE_P(v)) {
1510 rb_str_append(s, rb_inspect(v));
1512 else {
1513 rb_str_append(s, rb_any_to_s(v));
1515 rb_str_cat2(s, ">");
1517 return s;
1519 refined_class = rb_refinement_module_get_refined_class(klass);
1520 if (!NIL_P(refined_class)) {
1521 VALUE s = rb_usascii_str_new2("#<refinement:");
1523 rb_str_concat(s, rb_inspect(refined_class));
1524 rb_str_cat2(s, "@");
1525 CONST_ID(id_defined_at, "__defined_at__");
1526 defined_at = rb_attr_get(klass, id_defined_at);
1527 rb_str_concat(s, rb_inspect(defined_at));
1528 rb_str_cat2(s, ">");
1529 return s;
1531 return rb_class_name(klass);
1535 * call-seq:
1536 * mod.freeze -> mod
1538 * Prevents further modifications to <i>mod</i>.
1540 * This method returns self.
1543 static VALUE
1544 rb_mod_freeze(VALUE mod)
1546 rb_class_name(mod);
1547 return rb_obj_freeze(mod);
1551 * call-seq:
1552 * mod === obj -> true or false
1554 * Case Equality---Returns <code>true</code> if <i>obj</i> is an
1555 * instance of <i>mod</i> or an instance of one of <i>mod</i>'s descendants.
1556 * Of limited use for modules, but can be used in <code>case</code> statements
1557 * to classify objects by class.
1560 static VALUE
1561 rb_mod_eqq(VALUE mod, VALUE arg)
1563 return rb_obj_is_kind_of(arg, mod);
1567 * call-seq:
1568 * mod <= other -> true, false, or nil
1570 * Returns true if <i>mod</i> is a subclass of <i>other</i> or
1571 * is the same as <i>other</i>. Returns
1572 * <code>nil</code> if there's no relationship between the two.
1573 * (Think of the relationship in terms of the class definition:
1574 * "class A < B" implies "A < B".)
1577 VALUE
1578 rb_class_inherited_p(VALUE mod, VALUE arg)
1580 if (mod == arg) return Qtrue;
1581 if (!CLASS_OR_MODULE_P(arg) && !RB_TYPE_P(arg, T_ICLASS)) {
1582 rb_raise(rb_eTypeError, "compared with non class/module");
1584 if (class_search_ancestor(mod, RCLASS_ORIGIN(arg))) {
1585 return Qtrue;
1587 /* not mod < arg; check if mod > arg */
1588 if (class_search_ancestor(arg, mod)) {
1589 return Qfalse;
1591 return Qnil;
1595 * call-seq:
1596 * mod < other -> true, false, or nil
1598 * Returns true if <i>mod</i> is a subclass of <i>other</i>. Returns
1599 * <code>nil</code> if there's no relationship between the two.
1600 * (Think of the relationship in terms of the class definition:
1601 * "class A < B" implies "A < B".)
1605 static VALUE
1606 rb_mod_lt(VALUE mod, VALUE arg)
1608 if (mod == arg) return Qfalse;
1609 return rb_class_inherited_p(mod, arg);
1614 * call-seq:
1615 * mod >= other -> true, false, or nil
1617 * Returns true if <i>mod</i> is an ancestor of <i>other</i>, or the
1618 * two modules are the same. Returns
1619 * <code>nil</code> if there's no relationship between the two.
1620 * (Think of the relationship in terms of the class definition:
1621 * "class A < B" implies "B > A".)
1625 static VALUE
1626 rb_mod_ge(VALUE mod, VALUE arg)
1628 if (!CLASS_OR_MODULE_P(arg)) {
1629 rb_raise(rb_eTypeError, "compared with non class/module");
1632 return rb_class_inherited_p(arg, mod);
1636 * call-seq:
1637 * mod > other -> true, false, or nil
1639 * Returns true if <i>mod</i> is an ancestor of <i>other</i>. Returns
1640 * <code>nil</code> if there's no relationship between the two.
1641 * (Think of the relationship in terms of the class definition:
1642 * "class A < B" implies "B > A".)
1646 static VALUE
1647 rb_mod_gt(VALUE mod, VALUE arg)
1649 if (mod == arg) return Qfalse;
1650 return rb_mod_ge(mod, arg);
1654 * call-seq:
1655 * module <=> other_module -> -1, 0, +1, or nil
1657 * Comparison---Returns -1, 0, +1 or nil depending on whether +module+
1658 * includes +other_module+, they are the same, or if +module+ is included by
1659 * +other_module+.
1661 * Returns +nil+ if +module+ has no relationship with +other_module+, if
1662 * +other_module+ is not a module, or if the two values are incomparable.
1665 static VALUE
1666 rb_mod_cmp(VALUE mod, VALUE arg)
1668 VALUE cmp;
1670 if (mod == arg) return INT2FIX(0);
1671 if (!CLASS_OR_MODULE_P(arg)) {
1672 return Qnil;
1675 cmp = rb_class_inherited_p(mod, arg);
1676 if (NIL_P(cmp)) return Qnil;
1677 if (cmp) {
1678 return INT2FIX(-1);
1680 return INT2FIX(1);
1683 static VALUE rb_mod_initialize_exec(VALUE module);
1686 * call-seq:
1687 * Module.new -> mod
1688 * Module.new {|mod| block } -> mod
1690 * Creates a new anonymous module. If a block is given, it is passed
1691 * the module object, and the block is evaluated in the context of this
1692 * module like #module_eval.
1694 * fred = Module.new do
1695 * def meth1
1696 * "hello"
1697 * end
1698 * def meth2
1699 * "bye"
1700 * end
1701 * end
1702 * a = "my string"
1703 * a.extend(fred) #=> "my string"
1704 * a.meth1 #=> "hello"
1705 * a.meth2 #=> "bye"
1707 * Assign the module to a constant (name starting uppercase) if you
1708 * want to treat it like a regular module.
1711 static VALUE
1712 rb_mod_initialize(VALUE module)
1714 return rb_mod_initialize_exec(module);
1717 static VALUE
1718 rb_mod_initialize_exec(VALUE module)
1720 if (rb_block_given_p()) {
1721 rb_mod_module_exec(1, &module, module);
1723 return Qnil;
1726 /* :nodoc: */
1727 static VALUE
1728 rb_mod_initialize_clone(int argc, VALUE* argv, VALUE clone)
1730 VALUE ret, orig, opts;
1731 rb_scan_args(argc, argv, "1:", &orig, &opts);
1732 ret = rb_obj_init_clone(argc, argv, clone);
1733 if (OBJ_FROZEN(orig))
1734 rb_class_name(clone);
1735 return ret;
1739 * call-seq:
1740 * Class.new(super_class=Object) -> a_class
1741 * Class.new(super_class=Object) { |mod| ... } -> a_class
1743 * Creates a new anonymous (unnamed) class with the given superclass
1744 * (or Object if no parameter is given). You can give a
1745 * class a name by assigning the class object to a constant.
1747 * If a block is given, it is passed the class object, and the block
1748 * is evaluated in the context of this class like
1749 * #class_eval.
1751 * fred = Class.new do
1752 * def meth1
1753 * "hello"
1754 * end
1755 * def meth2
1756 * "bye"
1757 * end
1758 * end
1760 * a = fred.new #=> #<#<Class:0x100381890>:0x100376b98>
1761 * a.meth1 #=> "hello"
1762 * a.meth2 #=> "bye"
1764 * Assign the class to a constant (name starting uppercase) if you
1765 * want to treat it like a regular class.
1768 static VALUE
1769 rb_class_initialize(int argc, VALUE *argv, VALUE klass)
1771 VALUE super;
1773 if (RCLASS_SUPER(klass) != 0 || klass == rb_cBasicObject) {
1774 rb_raise(rb_eTypeError, "already initialized class");
1776 if (rb_check_arity(argc, 0, 1) == 0) {
1777 super = rb_cObject;
1779 else {
1780 super = argv[0];
1781 rb_check_inheritable(super);
1782 if (super != rb_cBasicObject && !RCLASS_SUPER(super)) {
1783 rb_raise(rb_eTypeError, "can't inherit uninitialized class");
1786 RCLASS_SET_SUPER(klass, super);
1787 rb_make_metaclass(klass, RBASIC(super)->klass);
1788 rb_class_inherited(super, klass);
1789 rb_mod_initialize_exec(klass);
1791 return klass;
1794 /*! \private */
1795 void
1796 rb_undefined_alloc(VALUE klass)
1798 rb_raise(rb_eTypeError, "allocator undefined for %"PRIsVALUE,
1799 klass);
1802 static rb_alloc_func_t class_get_alloc_func(VALUE klass);
1803 static VALUE class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass);
1806 * call-seq:
1807 * class.allocate() -> obj
1809 * Allocates space for a new object of <i>class</i>'s class and does not
1810 * call initialize on the new instance. The returned object must be an
1811 * instance of <i>class</i>.
1813 * klass = Class.new do
1814 * def initialize(*args)
1815 * @initialized = true
1816 * end
1818 * def initialized?
1819 * @initialized || false
1820 * end
1821 * end
1823 * klass.allocate.initialized? #=> false
1827 static VALUE
1828 rb_class_alloc_m(VALUE klass)
1830 rb_alloc_func_t allocator = class_get_alloc_func(klass);
1831 if (!rb_obj_respond_to(klass, rb_intern("allocate"), 1)) {
1832 rb_raise(rb_eTypeError, "calling %"PRIsVALUE".allocate is prohibited",
1833 klass);
1835 return class_call_alloc_func(allocator, klass);
1838 static VALUE
1839 rb_class_alloc(VALUE klass)
1841 rb_alloc_func_t allocator = class_get_alloc_func(klass);
1842 return class_call_alloc_func(allocator, klass);
1845 static rb_alloc_func_t
1846 class_get_alloc_func(VALUE klass)
1848 rb_alloc_func_t allocator;
1850 if (RCLASS_SUPER(klass) == 0 && klass != rb_cBasicObject) {
1851 rb_raise(rb_eTypeError, "can't instantiate uninitialized class");
1853 if (FL_TEST(klass, FL_SINGLETON)) {
1854 rb_raise(rb_eTypeError, "can't create instance of singleton class");
1856 allocator = rb_get_alloc_func(klass);
1857 if (!allocator) {
1858 rb_undefined_alloc(klass);
1860 return allocator;
1863 static VALUE
1864 class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass)
1866 VALUE obj;
1868 RUBY_DTRACE_CREATE_HOOK(OBJECT, rb_class2name(klass));
1870 obj = (*allocator)(klass);
1872 if (rb_obj_class(obj) != rb_class_real(klass)) {
1873 rb_raise(rb_eTypeError, "wrong instance allocation");
1875 return obj;
1878 VALUE
1879 rb_obj_alloc(VALUE klass)
1881 Check_Type(klass, T_CLASS);
1882 return rb_class_alloc(klass);
1886 * call-seq:
1887 * class.new(args, ...) -> obj
1889 * Calls #allocate to create a new object of <i>class</i>'s class,
1890 * then invokes that object's #initialize method, passing it
1891 * <i>args</i>. This is the method that ends up getting called
1892 * whenever an object is constructed using <code>.new</code>.
1896 VALUE
1897 rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass)
1899 VALUE obj;
1901 obj = rb_class_alloc(klass);
1902 rb_obj_call_init_kw(obj, argc, argv, RB_PASS_CALLED_KEYWORDS);
1904 return obj;
1907 VALUE
1908 rb_class_new_instance_kw(int argc, const VALUE *argv, VALUE klass, int kw_splat)
1910 VALUE obj;
1911 Check_Type(klass, T_CLASS);
1913 obj = rb_class_alloc(klass);
1914 rb_obj_call_init_kw(obj, argc, argv, kw_splat);
1916 return obj;
1919 VALUE
1920 rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
1922 VALUE obj;
1923 Check_Type(klass, T_CLASS);
1925 obj = rb_class_alloc(klass);
1926 rb_obj_call_init_kw(obj, argc, argv, RB_NO_KEYWORDS);
1928 return obj;
1932 * call-seq:
1933 * class.superclass -> a_super_class or nil
1935 * Returns the superclass of <i>class</i>, or <code>nil</code>.
1937 * File.superclass #=> IO
1938 * IO.superclass #=> Object
1939 * Object.superclass #=> BasicObject
1940 * class Foo; end
1941 * class Bar < Foo; end
1942 * Bar.superclass #=> Foo
1944 * Returns nil when the given class does not have a parent class:
1946 * BasicObject.superclass #=> nil
1949 * Returns the superclass of \a klass. Equivalent to \c Class\#superclass in Ruby.
1951 * It skips modules.
1952 * \param[in] klass a Class object
1953 * \return the superclass, or \c Qnil if \a klass does not have a parent class.
1954 * \sa rb_class_get_superclass
1958 VALUE
1959 rb_class_superclass(VALUE klass)
1961 VALUE super = RCLASS_SUPER(klass);
1963 if (!super) {
1964 if (klass == rb_cBasicObject) return Qnil;
1965 rb_raise(rb_eTypeError, "uninitialized class");
1967 while (RB_TYPE_P(super, T_ICLASS)) {
1968 super = RCLASS_SUPER(super);
1970 if (!super) {
1971 return Qnil;
1973 return super;
1976 VALUE
1977 rb_class_get_superclass(VALUE klass)
1979 return RCLASS(klass)->super;
1982 static const char bad_instance_name[] = "`%1$s' is not allowed as an instance variable name";
1983 static const char bad_class_name[] = "`%1$s' is not allowed as a class variable name";
1984 static const char bad_const_name[] = "wrong constant name %1$s";
1985 static const char bad_attr_name[] = "invalid attribute name `%1$s'";
1986 #define wrong_constant_name bad_const_name
1988 /*! \private */
1989 #define id_for_var(obj, name, type) id_for_setter(obj, name, type, bad_##type##_name)
1990 /*! \private */
1991 #define id_for_setter(obj, name, type, message) \
1992 check_setter_id(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message))
1993 static ID
1994 check_setter_id(VALUE obj, VALUE *pname,
1995 int (*valid_id_p)(ID), int (*valid_name_p)(VALUE),
1996 const char *message, size_t message_len)
1998 ID id = rb_check_id(pname);
1999 VALUE name = *pname;
2001 if (id ? !valid_id_p(id) : !valid_name_p(name)) {
2002 rb_name_err_raise_str(rb_fstring_new(message, message_len),
2003 obj, name);
2005 return id;
2008 static int
2009 rb_is_attr_name(VALUE name)
2011 return rb_is_local_name(name) || rb_is_const_name(name);
2014 static int
2015 rb_is_attr_id(ID id)
2017 return rb_is_local_id(id) || rb_is_const_id(id);
2020 static ID
2021 id_for_attr(VALUE obj, VALUE name)
2023 ID id = id_for_var(obj, name, attr);
2024 if (!id) id = rb_intern_str(name);
2025 return id;
2029 * call-seq:
2030 * attr_reader(symbol, ...) -> array
2031 * attr(symbol, ...) -> array
2032 * attr_reader(string, ...) -> array
2033 * attr(string, ...) -> array
2035 * Creates instance variables and corresponding methods that return the
2036 * value of each instance variable. Equivalent to calling
2037 * ``<code>attr</code><i>:name</i>'' on each name in turn.
2038 * String arguments are converted to symbols.
2039 * Returns an array of defined method names as symbols.
2042 static VALUE
2043 rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass)
2045 int i;
2046 VALUE names = rb_ary_new2(argc);
2048 for (i=0; i<argc; i++) {
2049 ID id = id_for_attr(klass, argv[i]);
2050 rb_attr(klass, id, TRUE, FALSE, TRUE);
2051 rb_ary_push(names, ID2SYM(id));
2053 return names;
2057 * call-seq:
2058 * attr(name, ...) -> array
2059 * attr(name, true) -> array
2060 * attr(name, false) -> array
2062 * The first form is equivalent to #attr_reader.
2063 * The second form is equivalent to <code>attr_accessor(name)</code> but deprecated.
2064 * The last form is equivalent to <code>attr_reader(name)</code> but deprecated.
2065 * Returns an array of defined method names as symbols.
2067 * \private
2068 * \todo can be static?
2071 VALUE
2072 rb_mod_attr(int argc, VALUE *argv, VALUE klass)
2074 if (argc == 2 && (argv[1] == Qtrue || argv[1] == Qfalse)) {
2075 ID id = id_for_attr(klass, argv[0]);
2076 VALUE names = rb_ary_new();
2078 rb_category_warning(RB_WARN_CATEGORY_DEPRECATED, "optional boolean argument is obsoleted");
2079 rb_attr(klass, id, 1, RTEST(argv[1]), TRUE);
2080 rb_ary_push(names, ID2SYM(id));
2081 if (argv[1] == Qtrue) rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2082 return names;
2084 return rb_mod_attr_reader(argc, argv, klass);
2088 * call-seq:
2089 * attr_writer(symbol, ...) -> array
2090 * attr_writer(string, ...) -> array
2092 * Creates an accessor method to allow assignment to the attribute
2093 * <i>symbol</i><code>.id2name</code>.
2094 * String arguments are converted to symbols.
2095 * Returns an array of defined method names as symbols.
2098 static VALUE
2099 rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass)
2101 int i;
2102 VALUE names = rb_ary_new2(argc);
2104 for (i=0; i<argc; i++) {
2105 ID id = id_for_attr(klass, argv[i]);
2106 rb_attr(klass, id, FALSE, TRUE, TRUE);
2107 rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2109 return names;
2113 * call-seq:
2114 * attr_accessor(symbol, ...) -> array
2115 * attr_accessor(string, ...) -> array
2117 * Defines a named attribute for this module, where the name is
2118 * <i>symbol.</i><code>id2name</code>, creating an instance variable
2119 * (<code>@name</code>) and a corresponding access method to read it.
2120 * Also creates a method called <code>name=</code> to set the attribute.
2121 * String arguments are converted to symbols.
2122 * Returns an array of defined method names as symbols.
2124 * module Mod
2125 * attr_accessor(:one, :two) #=> [:one, :one=, :two, :two=]
2126 * end
2127 * Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
2130 static VALUE
2131 rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass)
2133 int i;
2134 VALUE names = rb_ary_new2(argc * 2);
2136 for (i=0; i<argc; i++) {
2137 ID id = id_for_attr(klass, argv[i]);
2139 rb_attr(klass, id, TRUE, TRUE, TRUE);
2140 rb_ary_push(names, ID2SYM(id));
2141 rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2143 return names;
2147 * call-seq:
2148 * mod.const_get(sym, inherit=true) -> obj
2149 * mod.const_get(str, inherit=true) -> obj
2151 * Checks for a constant with the given name in <i>mod</i>.
2152 * If +inherit+ is set, the lookup will also search
2153 * the ancestors (and +Object+ if <i>mod</i> is a +Module+).
2155 * The value of the constant is returned if a definition is found,
2156 * otherwise a +NameError+ is raised.
2158 * Math.const_get(:PI) #=> 3.14159265358979
2160 * This method will recursively look up constant names if a namespaced
2161 * class name is provided. For example:
2163 * module Foo; class Bar; end end
2164 * Object.const_get 'Foo::Bar'
2166 * The +inherit+ flag is respected on each lookup. For example:
2168 * module Foo
2169 * class Bar
2170 * VAL = 10
2171 * end
2173 * class Baz < Bar; end
2174 * end
2176 * Object.const_get 'Foo::Baz::VAL' # => 10
2177 * Object.const_get 'Foo::Baz::VAL', false # => NameError
2179 * If the argument is not a valid constant name a +NameError+ will be
2180 * raised with a warning "wrong constant name".
2182 * Object.const_get 'foobar' #=> NameError: wrong constant name foobar
2186 static VALUE
2187 rb_mod_const_get(int argc, VALUE *argv, VALUE mod)
2189 VALUE name, recur;
2190 rb_encoding *enc;
2191 const char *pbeg, *p, *path, *pend;
2192 ID id;
2194 rb_check_arity(argc, 1, 2);
2195 name = argv[0];
2196 recur = (argc == 1) ? Qtrue : argv[1];
2198 if (SYMBOL_P(name)) {
2199 if (!rb_is_const_sym(name)) goto wrong_name;
2200 id = rb_check_id(&name);
2201 if (!id) return rb_const_missing(mod, name);
2202 return RTEST(recur) ? rb_const_get(mod, id) : rb_const_get_at(mod, id);
2205 path = StringValuePtr(name);
2206 enc = rb_enc_get(name);
2208 if (!rb_enc_asciicompat(enc)) {
2209 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2212 pbeg = p = path;
2213 pend = path + RSTRING_LEN(name);
2215 if (p >= pend || !*p) {
2216 goto wrong_name;
2219 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2220 mod = rb_cObject;
2221 p += 2;
2222 pbeg = p;
2225 while (p < pend) {
2226 VALUE part;
2227 long len, beglen;
2229 while (p < pend && *p != ':') p++;
2231 if (pbeg == p) goto wrong_name;
2233 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2234 beglen = pbeg-path;
2236 if (p < pend && p[0] == ':') {
2237 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2238 p += 2;
2239 pbeg = p;
2242 if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2243 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2244 QUOTE(name));
2247 if (!id) {
2248 part = rb_str_subseq(name, beglen, len);
2249 OBJ_FREEZE(part);
2250 if (!rb_is_const_name(part)) {
2251 name = part;
2252 goto wrong_name;
2254 else if (!rb_method_basic_definition_p(CLASS_OF(mod), id_const_missing)) {
2255 part = rb_str_intern(part);
2256 mod = rb_const_missing(mod, part);
2257 continue;
2259 else {
2260 rb_mod_const_missing(mod, part);
2263 if (!rb_is_const_id(id)) {
2264 name = ID2SYM(id);
2265 goto wrong_name;
2267 #if 0
2268 mod = rb_const_get_0(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2269 #else
2270 if (!RTEST(recur)) {
2271 mod = rb_const_get_at(mod, id);
2273 else if (beglen == 0) {
2274 mod = rb_const_get(mod, id);
2276 else {
2277 mod = rb_const_get_from(mod, id);
2279 #endif
2282 return mod;
2284 wrong_name:
2285 rb_name_err_raise(wrong_constant_name, mod, name);
2286 UNREACHABLE_RETURN(Qundef);
2290 * call-seq:
2291 * mod.const_set(sym, obj) -> obj
2292 * mod.const_set(str, obj) -> obj
2294 * Sets the named constant to the given object, returning that object.
2295 * Creates a new constant if no constant with the given name previously
2296 * existed.
2298 * Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714
2299 * Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968
2301 * If +sym+ or +str+ is not a valid constant name a +NameError+ will be
2302 * raised with a warning "wrong constant name".
2304 * Object.const_set('foobar', 42) #=> NameError: wrong constant name foobar
2308 static VALUE
2309 rb_mod_const_set(VALUE mod, VALUE name, VALUE value)
2311 ID id = id_for_var(mod, name, const);
2312 if (!id) id = rb_intern_str(name);
2313 rb_const_set(mod, id, value);
2315 return value;
2319 * call-seq:
2320 * mod.const_defined?(sym, inherit=true) -> true or false
2321 * mod.const_defined?(str, inherit=true) -> true or false
2323 * Says whether _mod_ or its ancestors have a constant with the given name:
2325 * Float.const_defined?(:EPSILON) #=> true, found in Float itself
2326 * Float.const_defined?("String") #=> true, found in Object (ancestor)
2327 * BasicObject.const_defined?(:Hash) #=> false
2329 * If _mod_ is a +Module+, additionally +Object+ and its ancestors are checked:
2331 * Math.const_defined?(:String) #=> true, found in Object
2333 * In each of the checked classes or modules, if the constant is not present
2334 * but there is an autoload for it, +true+ is returned directly without
2335 * autoloading:
2337 * module Admin
2338 * autoload :User, 'admin/user'
2339 * end
2340 * Admin.const_defined?(:User) #=> true
2342 * If the constant is not found the callback +const_missing+ is *not* called
2343 * and the method returns +false+.
2345 * If +inherit+ is false, the lookup only checks the constants in the receiver:
2347 * IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor)
2348 * IO.const_defined?(:SYNC, false) #=> false, not found in IO itself
2350 * In this case, the same logic for autoloading applies.
2352 * If the argument is not a valid constant name a +NameError+ is raised with the
2353 * message "wrong constant name _name_":
2355 * Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar
2359 static VALUE
2360 rb_mod_const_defined(int argc, VALUE *argv, VALUE mod)
2362 VALUE name, recur;
2363 rb_encoding *enc;
2364 const char *pbeg, *p, *path, *pend;
2365 ID id;
2367 rb_check_arity(argc, 1, 2);
2368 name = argv[0];
2369 recur = (argc == 1) ? Qtrue : argv[1];
2371 if (SYMBOL_P(name)) {
2372 if (!rb_is_const_sym(name)) goto wrong_name;
2373 id = rb_check_id(&name);
2374 if (!id) return Qfalse;
2375 return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id);
2378 path = StringValuePtr(name);
2379 enc = rb_enc_get(name);
2381 if (!rb_enc_asciicompat(enc)) {
2382 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2385 pbeg = p = path;
2386 pend = path + RSTRING_LEN(name);
2388 if (p >= pend || !*p) {
2389 goto wrong_name;
2392 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2393 mod = rb_cObject;
2394 p += 2;
2395 pbeg = p;
2398 while (p < pend) {
2399 VALUE part;
2400 long len, beglen;
2402 while (p < pend && *p != ':') p++;
2404 if (pbeg == p) goto wrong_name;
2406 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2407 beglen = pbeg-path;
2409 if (p < pend && p[0] == ':') {
2410 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2411 p += 2;
2412 pbeg = p;
2415 if (!id) {
2416 part = rb_str_subseq(name, beglen, len);
2417 OBJ_FREEZE(part);
2418 if (!rb_is_const_name(part)) {
2419 name = part;
2420 goto wrong_name;
2422 else {
2423 return Qfalse;
2426 if (!rb_is_const_id(id)) {
2427 name = ID2SYM(id);
2428 goto wrong_name;
2431 #if 0
2432 mod = rb_const_search(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2433 if (mod == Qundef) return Qfalse;
2434 #else
2435 if (!RTEST(recur)) {
2436 if (!rb_const_defined_at(mod, id))
2437 return Qfalse;
2438 if (p == pend) return Qtrue;
2439 mod = rb_const_get_at(mod, id);
2441 else if (beglen == 0) {
2442 if (!rb_const_defined(mod, id))
2443 return Qfalse;
2444 if (p == pend) return Qtrue;
2445 mod = rb_const_get(mod, id);
2447 else {
2448 if (!rb_const_defined_from(mod, id))
2449 return Qfalse;
2450 if (p == pend) return Qtrue;
2451 mod = rb_const_get_from(mod, id);
2453 #endif
2455 if (p < pend && !RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2456 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2457 QUOTE(name));
2461 return Qtrue;
2463 wrong_name:
2464 rb_name_err_raise(wrong_constant_name, mod, name);
2465 UNREACHABLE_RETURN(Qundef);
2469 * call-seq:
2470 * mod.const_source_location(sym, inherit=true) -> [String, Integer]
2471 * mod.const_source_location(str, inherit=true) -> [String, Integer]
2473 * Returns the Ruby source filename and line number containing the definition
2474 * of the constant specified. If the named constant is not found, +nil+ is returned.
2475 * If the constant is found, but its source location can not be extracted
2476 * (constant is defined in C code), empty array is returned.
2478 * _inherit_ specifies whether to lookup in <code>mod.ancestors</code> (+true+
2479 * by default).
2481 * # test.rb:
2482 * class A # line 1
2483 * C1 = 1
2484 * C2 = 2
2485 * end
2487 * module M # line 6
2488 * C3 = 3
2489 * end
2491 * class B < A # line 10
2492 * include M
2493 * C4 = 4
2494 * end
2496 * class A # continuation of A definition
2497 * C2 = 8 # constant redefinition; warned yet allowed
2498 * end
2500 * p B.const_source_location('C4') # => ["test.rb", 12]
2501 * p B.const_source_location('C3') # => ["test.rb", 7]
2502 * p B.const_source_location('C1') # => ["test.rb", 2]
2504 * p B.const_source_location('C3', false) # => nil -- don't lookup in ancestors
2506 * p A.const_source_location('C2') # => ["test.rb", 16] -- actual (last) definition place
2508 * p Object.const_source_location('B') # => ["test.rb", 10] -- top-level constant could be looked through Object
2509 * p Object.const_source_location('A') # => ["test.rb", 1] -- class reopening is NOT considered new definition
2511 * p B.const_source_location('A') # => ["test.rb", 1] -- because Object is in ancestors
2512 * p M.const_source_location('A') # => ["test.rb", 1] -- Object is not ancestor, but additionally checked for modules
2514 * p Object.const_source_location('A::C1') # => ["test.rb", 2] -- nesting is supported
2515 * p Object.const_source_location('String') # => [] -- constant is defined in C code
2519 static VALUE
2520 rb_mod_const_source_location(int argc, VALUE *argv, VALUE mod)
2522 VALUE name, recur, loc = Qnil;
2523 rb_encoding *enc;
2524 const char *pbeg, *p, *path, *pend;
2525 ID id;
2527 rb_check_arity(argc, 1, 2);
2528 name = argv[0];
2529 recur = (argc == 1) ? Qtrue : argv[1];
2531 if (SYMBOL_P(name)) {
2532 if (!rb_is_const_sym(name)) goto wrong_name;
2533 id = rb_check_id(&name);
2534 if (!id) return Qnil;
2535 return RTEST(recur) ? rb_const_source_location(mod, id) : rb_const_source_location_at(mod, id);
2538 path = StringValuePtr(name);
2539 enc = rb_enc_get(name);
2541 if (!rb_enc_asciicompat(enc)) {
2542 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2545 pbeg = p = path;
2546 pend = path + RSTRING_LEN(name);
2548 if (p >= pend || !*p) {
2549 goto wrong_name;
2552 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2553 mod = rb_cObject;
2554 p += 2;
2555 pbeg = p;
2558 while (p < pend) {
2559 VALUE part;
2560 long len, beglen;
2562 while (p < pend && *p != ':') p++;
2564 if (pbeg == p) goto wrong_name;
2566 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2567 beglen = pbeg-path;
2569 if (p < pend && p[0] == ':') {
2570 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2571 p += 2;
2572 pbeg = p;
2575 if (!id) {
2576 part = rb_str_subseq(name, beglen, len);
2577 OBJ_FREEZE(part);
2578 if (!rb_is_const_name(part)) {
2579 name = part;
2580 goto wrong_name;
2582 else {
2583 return Qnil;
2586 if (!rb_is_const_id(id)) {
2587 name = ID2SYM(id);
2588 goto wrong_name;
2590 if (p < pend) {
2591 if (RTEST(recur)) {
2592 mod = rb_const_get(mod, id);
2594 else {
2595 mod = rb_const_get_at(mod, id);
2597 if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2598 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2599 QUOTE(name));
2602 else {
2603 if (RTEST(recur)) {
2604 loc = rb_const_source_location(mod, id);
2606 else {
2607 loc = rb_const_source_location_at(mod, id);
2609 break;
2611 recur = Qfalse;
2614 return loc;
2616 wrong_name:
2617 rb_name_err_raise(wrong_constant_name, mod, name);
2618 UNREACHABLE_RETURN(Qundef);
2622 * call-seq:
2623 * obj.instance_variable_get(symbol) -> obj
2624 * obj.instance_variable_get(string) -> obj
2626 * Returns the value of the given instance variable, or nil if the
2627 * instance variable is not set. The <code>@</code> part of the
2628 * variable name should be included for regular instance
2629 * variables. Throws a NameError exception if the
2630 * supplied symbol is not valid as an instance variable name.
2631 * String arguments are converted to symbols.
2633 * class Fred
2634 * def initialize(p1, p2)
2635 * @a, @b = p1, p2
2636 * end
2637 * end
2638 * fred = Fred.new('cat', 99)
2639 * fred.instance_variable_get(:@a) #=> "cat"
2640 * fred.instance_variable_get("@b") #=> 99
2643 static VALUE
2644 rb_obj_ivar_get(VALUE obj, VALUE iv)
2646 ID id = id_for_var(obj, iv, instance);
2648 if (!id) {
2649 return Qnil;
2651 return rb_ivar_get(obj, id);
2655 * call-seq:
2656 * obj.instance_variable_set(symbol, obj) -> obj
2657 * obj.instance_variable_set(string, obj) -> obj
2659 * Sets the instance variable named by <i>symbol</i> to the given
2660 * object. This may circumvent the encapsulation intended by
2661 * the author of the class, so it should be used with care.
2662 * The variable does not have to exist prior to this call.
2663 * If the instance variable name is passed as a string, that string
2664 * is converted to a symbol.
2666 * class Fred
2667 * def initialize(p1, p2)
2668 * @a, @b = p1, p2
2669 * end
2670 * end
2671 * fred = Fred.new('cat', 99)
2672 * fred.instance_variable_set(:@a, 'dog') #=> "dog"
2673 * fred.instance_variable_set(:@c, 'cat') #=> "cat"
2674 * fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
2677 static VALUE
2678 rb_obj_ivar_set(VALUE obj, VALUE iv, VALUE val)
2680 ID id = id_for_var(obj, iv, instance);
2681 if (!id) id = rb_intern_str(iv);
2682 return rb_ivar_set(obj, id, val);
2686 * call-seq:
2687 * obj.instance_variable_defined?(symbol) -> true or false
2688 * obj.instance_variable_defined?(string) -> true or false
2690 * Returns <code>true</code> if the given instance variable is
2691 * defined in <i>obj</i>.
2692 * String arguments are converted to symbols.
2694 * class Fred
2695 * def initialize(p1, p2)
2696 * @a, @b = p1, p2
2697 * end
2698 * end
2699 * fred = Fred.new('cat', 99)
2700 * fred.instance_variable_defined?(:@a) #=> true
2701 * fred.instance_variable_defined?("@b") #=> true
2702 * fred.instance_variable_defined?("@c") #=> false
2705 static VALUE
2706 rb_obj_ivar_defined(VALUE obj, VALUE iv)
2708 ID id = id_for_var(obj, iv, instance);
2710 if (!id) {
2711 return Qfalse;
2713 return rb_ivar_defined(obj, id);
2717 * call-seq:
2718 * mod.class_variable_get(symbol) -> obj
2719 * mod.class_variable_get(string) -> obj
2721 * Returns the value of the given class variable (or throws a
2722 * NameError exception). The <code>@@</code> part of the
2723 * variable name should be included for regular class variables.
2724 * String arguments are converted to symbols.
2726 * class Fred
2727 * @@foo = 99
2728 * end
2729 * Fred.class_variable_get(:@@foo) #=> 99
2732 static VALUE
2733 rb_mod_cvar_get(VALUE obj, VALUE iv)
2735 ID id = id_for_var(obj, iv, class);
2737 if (!id) {
2738 rb_name_err_raise("uninitialized class variable %1$s in %2$s",
2739 obj, iv);
2741 return rb_cvar_get(obj, id);
2745 * call-seq:
2746 * obj.class_variable_set(symbol, obj) -> obj
2747 * obj.class_variable_set(string, obj) -> obj
2749 * Sets the class variable named by <i>symbol</i> to the given
2750 * object.
2751 * If the class variable name is passed as a string, that string
2752 * is converted to a symbol.
2754 * class Fred
2755 * @@foo = 99
2756 * def foo
2757 * @@foo
2758 * end
2759 * end
2760 * Fred.class_variable_set(:@@foo, 101) #=> 101
2761 * Fred.new.foo #=> 101
2764 static VALUE
2765 rb_mod_cvar_set(VALUE obj, VALUE iv, VALUE val)
2767 ID id = id_for_var(obj, iv, class);
2768 if (!id) id = rb_intern_str(iv);
2769 rb_cvar_set(obj, id, val);
2770 return val;
2774 * call-seq:
2775 * obj.class_variable_defined?(symbol) -> true or false
2776 * obj.class_variable_defined?(string) -> true or false
2778 * Returns <code>true</code> if the given class variable is defined
2779 * in <i>obj</i>.
2780 * String arguments are converted to symbols.
2782 * class Fred
2783 * @@foo = 99
2784 * end
2785 * Fred.class_variable_defined?(:@@foo) #=> true
2786 * Fred.class_variable_defined?(:@@bar) #=> false
2789 static VALUE
2790 rb_mod_cvar_defined(VALUE obj, VALUE iv)
2792 ID id = id_for_var(obj, iv, class);
2794 if (!id) {
2795 return Qfalse;
2797 return rb_cvar_defined(obj, id);
2801 * call-seq:
2802 * mod.singleton_class? -> true or false
2804 * Returns <code>true</code> if <i>mod</i> is a singleton class or
2805 * <code>false</code> if it is an ordinary class or module.
2807 * class C
2808 * end
2809 * C.singleton_class? #=> false
2810 * C.singleton_class.singleton_class? #=> true
2813 static VALUE
2814 rb_mod_singleton_p(VALUE klass)
2816 return RBOOL(RB_TYPE_P(klass, T_CLASS) && FL_TEST(klass, FL_SINGLETON));
2819 /*! \private */
2820 static const struct conv_method_tbl {
2821 const char method[6];
2822 unsigned short id;
2823 } conv_method_names[] = {
2824 #define M(n) {#n, (unsigned short)idTo_##n}
2825 M(int),
2826 M(ary),
2827 M(str),
2828 M(sym),
2829 M(hash),
2830 M(proc),
2831 M(io),
2832 M(a),
2833 M(s),
2834 M(i),
2835 M(f),
2836 M(r),
2837 #undef M
2839 #define IMPLICIT_CONVERSIONS 7
2841 static int
2842 conv_method_index(const char *method)
2844 static const char prefix[] = "to_";
2846 if (strncmp(prefix, method, sizeof(prefix)-1) == 0) {
2847 const char *const meth = &method[sizeof(prefix)-1];
2848 int i;
2849 for (i=0; i < numberof(conv_method_names); i++) {
2850 if (conv_method_names[i].method[0] == meth[0] &&
2851 strcmp(conv_method_names[i].method, meth) == 0) {
2852 return i;
2856 return numberof(conv_method_names);
2859 static VALUE
2860 convert_type_with_id(VALUE val, const char *tname, ID method, int raise, int index)
2862 VALUE r = rb_check_funcall(val, method, 0, 0);
2863 if (r == Qundef) {
2864 if (raise) {
2865 const char *msg =
2866 ((index < 0 ? conv_method_index(rb_id2name(method)) : index)
2867 < IMPLICIT_CONVERSIONS) ?
2868 "no implicit conversion of" : "can't convert";
2869 const char *cname = NIL_P(val) ? "nil" :
2870 val == Qtrue ? "true" :
2871 val == Qfalse ? "false" :
2872 NULL;
2873 if (cname)
2874 rb_raise(rb_eTypeError, "%s %s into %s", msg, cname, tname);
2875 rb_raise(rb_eTypeError, "%s %"PRIsVALUE" into %s", msg,
2876 rb_obj_class(val),
2877 tname);
2879 return Qnil;
2881 return r;
2884 static VALUE
2885 convert_type(VALUE val, const char *tname, const char *method, int raise)
2887 int i = conv_method_index(method);
2888 ID m = i < numberof(conv_method_names) ?
2889 conv_method_names[i].id : rb_intern(method);
2890 return convert_type_with_id(val, tname, m, raise, i);
2893 /*! \private */
2894 NORETURN(static void conversion_mismatch(VALUE, const char *, const char *, VALUE));
2895 static void
2896 conversion_mismatch(VALUE val, const char *tname, const char *method, VALUE result)
2898 VALUE cname = rb_obj_class(val);
2899 rb_raise(rb_eTypeError,
2900 "can't convert %"PRIsVALUE" to %s (%"PRIsVALUE"#%s gives %"PRIsVALUE")",
2901 cname, tname, cname, method, rb_obj_class(result));
2904 VALUE
2905 rb_convert_type(VALUE val, int type, const char *tname, const char *method)
2907 VALUE v;
2909 if (TYPE(val) == type) return val;
2910 v = convert_type(val, tname, method, TRUE);
2911 if (TYPE(v) != type) {
2912 conversion_mismatch(val, tname, method, v);
2914 return v;
2917 /*! \private */
2918 VALUE
2919 rb_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
2921 VALUE v;
2923 if (TYPE(val) == type) return val;
2924 v = convert_type_with_id(val, tname, method, TRUE, -1);
2925 if (TYPE(v) != type) {
2926 conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v);
2928 return v;
2931 VALUE
2932 rb_check_convert_type(VALUE val, int type, const char *tname, const char *method)
2934 VALUE v;
2936 /* always convert T_DATA */
2937 if (TYPE(val) == type && type != T_DATA) return val;
2938 v = convert_type(val, tname, method, FALSE);
2939 if (NIL_P(v)) return Qnil;
2940 if (TYPE(v) != type) {
2941 conversion_mismatch(val, tname, method, v);
2943 return v;
2946 /*! \private */
2947 MJIT_FUNC_EXPORTED VALUE
2948 rb_check_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
2950 VALUE v;
2952 /* always convert T_DATA */
2953 if (TYPE(val) == type && type != T_DATA) return val;
2954 v = convert_type_with_id(val, tname, method, FALSE, -1);
2955 if (NIL_P(v)) return Qnil;
2956 if (TYPE(v) != type) {
2957 conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v);
2959 return v;
2962 #define try_to_int(val, mid, raise) \
2963 convert_type_with_id(val, "Integer", mid, raise, -1)
2965 ALWAYS_INLINE(static VALUE rb_to_integer_with_id_exception(VALUE val, const char *method, ID mid, int raise));
2966 /* Integer specific rb_check_convert_type_with_id */
2967 static inline VALUE
2968 rb_to_integer_with_id_exception(VALUE val, const char *method, ID mid, int raise)
2970 VALUE v;
2972 if (RB_INTEGER_TYPE_P(val)) return val;
2973 v = try_to_int(val, mid, raise);
2974 if (!raise && NIL_P(v)) return Qnil;
2975 if (!RB_INTEGER_TYPE_P(v)) {
2976 conversion_mismatch(val, "Integer", method, v);
2978 return v;
2980 #define rb_to_integer(val, method, mid) \
2981 rb_to_integer_with_id_exception(val, method, mid, TRUE)
2983 VALUE
2984 rb_check_to_integer(VALUE val, const char *method)
2986 VALUE v;
2988 if (RB_INTEGER_TYPE_P(val)) return val;
2989 v = convert_type(val, "Integer", method, FALSE);
2990 if (!RB_INTEGER_TYPE_P(v)) {
2991 return Qnil;
2993 return v;
2996 VALUE
2997 rb_to_int(VALUE val)
2999 return rb_to_integer(val, "to_int", idTo_int);
3002 VALUE
3003 rb_check_to_int(VALUE val)
3005 if (RB_INTEGER_TYPE_P(val)) return val;
3006 val = try_to_int(val, idTo_int, FALSE);
3007 if (RB_INTEGER_TYPE_P(val)) return val;
3008 return Qnil;
3011 static VALUE
3012 rb_check_to_i(VALUE val)
3014 if (RB_INTEGER_TYPE_P(val)) return val;
3015 val = try_to_int(val, idTo_i, FALSE);
3016 if (RB_INTEGER_TYPE_P(val)) return val;
3017 return Qnil;
3020 static VALUE
3021 rb_convert_to_integer(VALUE val, int base, int raise_exception)
3023 VALUE tmp;
3025 if (base) {
3026 tmp = rb_check_string_type(val);
3028 if (! NIL_P(tmp)) {
3029 val = tmp;
3031 else if (! raise_exception) {
3032 return Qnil;
3034 else {
3035 rb_raise(rb_eArgError, "base specified for non string value");
3038 if (RB_FLOAT_TYPE_P(val)) {
3039 double f = RFLOAT_VALUE(val);
3040 if (!raise_exception && !isfinite(f)) return Qnil;
3041 if (FIXABLE(f)) return LONG2FIX((long)f);
3042 return rb_dbl2big(f);
3044 else if (RB_INTEGER_TYPE_P(val)) {
3045 return val;
3047 else if (RB_TYPE_P(val, T_STRING)) {
3048 return rb_str_convert_to_inum(val, base, TRUE, raise_exception);
3050 else if (NIL_P(val)) {
3051 if (!raise_exception) return Qnil;
3052 rb_raise(rb_eTypeError, "can't convert nil into Integer");
3055 tmp = rb_protect(rb_check_to_int, val, NULL);
3056 if (RB_INTEGER_TYPE_P(tmp)) return tmp;
3057 rb_set_errinfo(Qnil);
3059 if (!raise_exception) {
3060 VALUE result = rb_protect(rb_check_to_i, val, NULL);
3061 rb_set_errinfo(Qnil);
3062 return result;
3065 return rb_to_integer(val, "to_i", idTo_i);
3068 VALUE
3069 rb_Integer(VALUE val)
3071 return rb_convert_to_integer(val, 0, TRUE);
3074 VALUE
3075 rb_check_integer_type(VALUE val)
3077 return rb_to_integer_with_id_exception(val, "to_int", idTo_int, FALSE);
3081 rb_bool_expected(VALUE obj, const char *flagname)
3083 switch (obj) {
3084 case Qtrue: case Qfalse:
3085 break;
3086 default:
3087 rb_raise(rb_eArgError, "expected true or false as %s: %+"PRIsVALUE,
3088 flagname, obj);
3090 return obj != Qfalse;
3094 rb_opts_exception_p(VALUE opts, int default_value)
3096 static const ID kwds[1] = {idException};
3097 VALUE exception;
3098 if (rb_get_kwargs(opts, kwds, 0, 1, &exception))
3099 return rb_bool_expected(exception, "exception");
3100 return default_value;
3103 #define opts_exception_p(opts) rb_opts_exception_p((opts), TRUE)
3106 * call-seq:
3107 * Integer(arg, base=0, exception: true) -> integer or nil
3109 * Converts <i>arg</i> to an Integer.
3110 * Numeric types are converted directly (with floating point numbers
3111 * being truncated). <i>base</i> (0, or between 2 and 36) is a base for
3112 * integer string representation. If <i>arg</i> is a String,
3113 * when <i>base</i> is omitted or equals zero, radix indicators
3114 * (<code>0</code>, <code>0b</code>, and <code>0x</code>) are honored.
3115 * In any case, strings should consist only of one or more digits, except
3116 * for that a sign, one underscore between two digits, and leading/trailing
3117 * spaces are optional. This behavior is different from that of
3118 * String#to_i. Non string values will be converted by first
3119 * trying <code>to_int</code>, then <code>to_i</code>.
3121 * Passing <code>nil</code> raises a TypeError, while passing a String that
3122 * does not conform with numeric representation raises an ArgumentError.
3123 * This behavior can be altered by passing <code>exception: false</code>,
3124 * in this case a not convertible value will return <code>nil</code>.
3126 * Integer(123.999) #=> 123
3127 * Integer("0x1a") #=> 26
3128 * Integer(Time.new) #=> 1204973019
3129 * Integer("0930", 10) #=> 930
3130 * Integer("111", 2) #=> 7
3131 * Integer(" +1_0 ") #=> 10
3132 * Integer(nil) #=> TypeError: can't convert nil into Integer
3133 * Integer("x") #=> ArgumentError: invalid value for Integer(): "x"
3135 * Integer("x", exception: false) #=> nil
3139 static VALUE
3140 rb_f_integer(int argc, VALUE *argv, VALUE obj)
3142 VALUE arg = Qnil, opts = Qnil;
3143 int base = 0;
3145 if (argc > 1) {
3146 int narg = 1;
3147 VALUE vbase = rb_check_to_int(argv[1]);
3148 if (!NIL_P(vbase)) {
3149 base = NUM2INT(vbase);
3150 narg = 2;
3152 if (argc > narg) {
3153 VALUE hash = rb_check_hash_type(argv[argc-1]);
3154 if (!NIL_P(hash)) {
3155 opts = rb_extract_keywords(&hash);
3156 if (!hash) --argc;
3160 rb_check_arity(argc, 1, 2);
3161 arg = argv[0];
3163 return rb_convert_to_integer(arg, base, opts_exception_p(opts));
3166 static double
3167 rb_cstr_to_dbl_raise(const char *p, int badcheck, int raise, int *error)
3169 const char *q;
3170 char *end;
3171 double d;
3172 const char *ellipsis = "";
3173 int w;
3174 enum {max_width = 20};
3175 #define OutOfRange() ((end - p > max_width) ? \
3176 (w = max_width, ellipsis = "...") : \
3177 (w = (int)(end - p), ellipsis = ""))
3179 if (!p) return 0.0;
3180 q = p;
3181 while (ISSPACE(*p)) p++;
3183 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3184 return 0.0;
3187 d = strtod(p, &end);
3188 if (errno == ERANGE) {
3189 OutOfRange();
3190 rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3191 errno = 0;
3193 if (p == end) {
3194 if (badcheck) {
3195 goto bad;
3197 return d;
3199 if (*end) {
3200 char buf[DBL_DIG * 4 + 10];
3201 char *n = buf;
3202 char *const init_e = buf + DBL_DIG * 4;
3203 char *e = init_e;
3204 char prev = 0;
3205 int dot_seen = FALSE;
3207 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3208 if (*p == '0') {
3209 prev = *n++ = '0';
3210 while (*++p == '0');
3212 while (p < end && n < e) prev = *n++ = *p++;
3213 while (*p) {
3214 if (*p == '_') {
3215 /* remove an underscore between digits */
3216 if (n == buf || !ISDIGIT(prev) || (++p, !ISDIGIT(*p))) {
3217 if (badcheck) goto bad;
3218 break;
3221 prev = *p++;
3222 if (e == init_e && (prev == 'e' || prev == 'E' || prev == 'p' || prev == 'P')) {
3223 e = buf + sizeof(buf) - 1;
3224 *n++ = prev;
3225 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3226 if (*p == '0') {
3227 prev = *n++ = '0';
3228 while (*++p == '0');
3230 continue;
3232 else if (ISSPACE(prev)) {
3233 while (ISSPACE(*p)) ++p;
3234 if (*p) {
3235 if (badcheck) goto bad;
3236 break;
3239 else if (prev == '.' ? dot_seen++ : !ISDIGIT(prev)) {
3240 if (badcheck) goto bad;
3241 break;
3243 if (n < e) *n++ = prev;
3245 *n = '\0';
3246 p = buf;
3248 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3249 return 0.0;
3252 d = strtod(p, &end);
3253 if (errno == ERANGE) {
3254 OutOfRange();
3255 rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3256 errno = 0;
3258 if (badcheck) {
3259 if (!end || p == end) goto bad;
3260 while (*end && ISSPACE(*end)) end++;
3261 if (*end) goto bad;
3264 if (errno == ERANGE) {
3265 errno = 0;
3266 OutOfRange();
3267 rb_raise(rb_eArgError, "Float %.*s%s out of range", w, q, ellipsis);
3269 return d;
3271 bad:
3272 if (raise) {
3273 rb_invalid_str(q, "Float()");
3274 UNREACHABLE_RETURN(nan(""));
3276 else {
3277 if (error) *error = 1;
3278 return 0.0;
3282 double
3283 rb_cstr_to_dbl(const char *p, int badcheck)
3285 return rb_cstr_to_dbl_raise(p, badcheck, TRUE, NULL);
3288 static double
3289 rb_str_to_dbl_raise(VALUE str, int badcheck, int raise, int *error)
3291 char *s;
3292 long len;
3293 double ret;
3294 VALUE v = 0;
3296 StringValue(str);
3297 s = RSTRING_PTR(str);
3298 len = RSTRING_LEN(str);
3299 if (s) {
3300 if (badcheck && memchr(s, '\0', len)) {
3301 if (raise)
3302 rb_raise(rb_eArgError, "string for Float contains null byte");
3303 else {
3304 if (error) *error = 1;
3305 return 0.0;
3308 if (s[len]) { /* no sentinel somehow */
3309 char *p = ALLOCV(v, (size_t)len + 1);
3310 MEMCPY(p, s, char, len);
3311 p[len] = '\0';
3312 s = p;
3315 ret = rb_cstr_to_dbl_raise(s, badcheck, raise, error);
3316 if (v)
3317 ALLOCV_END(v);
3318 return ret;
3321 FUNC_MINIMIZED(double rb_str_to_dbl(VALUE str, int badcheck));
3323 double
3324 rb_str_to_dbl(VALUE str, int badcheck)
3326 return rb_str_to_dbl_raise(str, badcheck, TRUE, NULL);
3329 /*! \cond INTERNAL_MACRO */
3330 #define fix2dbl_without_to_f(x) (double)FIX2LONG(x)
3331 #define big2dbl_without_to_f(x) rb_big2dbl(x)
3332 #define int2dbl_without_to_f(x) \
3333 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : big2dbl_without_to_f(x))
3334 #define num2dbl_without_to_f(x) \
3335 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : \
3336 RB_BIGNUM_TYPE_P(x) ? big2dbl_without_to_f(x) : \
3337 (Check_Type(x, T_FLOAT), RFLOAT_VALUE(x)))
3338 static inline double
3339 rat2dbl_without_to_f(VALUE x)
3341 VALUE num = rb_rational_num(x);
3342 VALUE den = rb_rational_den(x);
3343 return num2dbl_without_to_f(num) / num2dbl_without_to_f(den);
3346 #define special_const_to_float(val, pre, post) \
3347 switch (val) { \
3348 case Qnil: \
3349 rb_raise_static(rb_eTypeError, pre "nil" post); \
3350 case Qtrue: \
3351 rb_raise_static(rb_eTypeError, pre "true" post); \
3352 case Qfalse: \
3353 rb_raise_static(rb_eTypeError, pre "false" post); \
3355 /*! \endcond */
3357 static inline void
3358 conversion_to_float(VALUE val)
3360 special_const_to_float(val, "can't convert ", " into Float");
3363 static inline void
3364 implicit_conversion_to_float(VALUE val)
3366 special_const_to_float(val, "no implicit conversion to float from ", "");
3369 static int
3370 to_float(VALUE *valp, int raise_exception)
3372 VALUE val = *valp;
3373 if (SPECIAL_CONST_P(val)) {
3374 if (FIXNUM_P(val)) {
3375 *valp = DBL2NUM(fix2dbl_without_to_f(val));
3376 return T_FLOAT;
3378 else if (FLONUM_P(val)) {
3379 return T_FLOAT;
3381 else if (raise_exception) {
3382 conversion_to_float(val);
3385 else {
3386 int type = BUILTIN_TYPE(val);
3387 switch (type) {
3388 case T_FLOAT:
3389 return T_FLOAT;
3390 case T_BIGNUM:
3391 *valp = DBL2NUM(big2dbl_without_to_f(val));
3392 return T_FLOAT;
3393 case T_RATIONAL:
3394 *valp = DBL2NUM(rat2dbl_without_to_f(val));
3395 return T_FLOAT;
3396 case T_STRING:
3397 return T_STRING;
3400 return T_NONE;
3403 static VALUE
3404 convert_type_to_float_protected(VALUE val)
3406 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3409 static VALUE
3410 rb_convert_to_float(VALUE val, int raise_exception)
3412 switch (to_float(&val, raise_exception)) {
3413 case T_FLOAT:
3414 return val;
3415 case T_STRING:
3416 if (!raise_exception) {
3417 int e = 0;
3418 double x = rb_str_to_dbl_raise(val, TRUE, raise_exception, &e);
3419 return e ? Qnil : DBL2NUM(x);
3421 return DBL2NUM(rb_str_to_dbl(val, TRUE));
3422 case T_NONE:
3423 if (SPECIAL_CONST_P(val) && !raise_exception)
3424 return Qnil;
3427 if (!raise_exception) {
3428 int state;
3429 VALUE result = rb_protect(convert_type_to_float_protected, val, &state);
3430 if (state) rb_set_errinfo(Qnil);
3431 return result;
3434 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3437 FUNC_MINIMIZED(VALUE rb_Float(VALUE val));
3439 VALUE
3440 rb_Float(VALUE val)
3442 return rb_convert_to_float(val, TRUE);
3445 static VALUE
3446 rb_f_float1(rb_execution_context_t *ec, VALUE obj, VALUE arg)
3448 return rb_convert_to_float(arg, TRUE);
3451 static VALUE
3452 rb_f_float(rb_execution_context_t *ec, VALUE obj, VALUE arg, VALUE opts)
3454 int exception = rb_bool_expected(opts, "exception");
3455 return rb_convert_to_float(arg, exception);
3458 static VALUE
3459 numeric_to_float(VALUE val)
3461 if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3462 rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into Float",
3463 rb_obj_class(val));
3465 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3468 VALUE
3469 rb_to_float(VALUE val)
3471 switch (to_float(&val, TRUE)) {
3472 case T_FLOAT:
3473 return val;
3475 return numeric_to_float(val);
3478 VALUE
3479 rb_check_to_float(VALUE val)
3481 if (RB_FLOAT_TYPE_P(val)) return val;
3482 if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3483 return Qnil;
3485 return rb_check_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3488 static inline int
3489 basic_to_f_p(VALUE klass)
3491 return rb_method_basic_definition_p(klass, id_to_f);
3494 /*! \private */
3495 double
3496 rb_num_to_dbl(VALUE val)
3498 if (SPECIAL_CONST_P(val)) {
3499 if (FIXNUM_P(val)) {
3500 if (basic_to_f_p(rb_cInteger))
3501 return fix2dbl_without_to_f(val);
3503 else if (FLONUM_P(val)) {
3504 return rb_float_flonum_value(val);
3506 else {
3507 conversion_to_float(val);
3510 else {
3511 switch (BUILTIN_TYPE(val)) {
3512 case T_FLOAT:
3513 return rb_float_noflonum_value(val);
3514 case T_BIGNUM:
3515 if (basic_to_f_p(rb_cInteger))
3516 return big2dbl_without_to_f(val);
3517 break;
3518 case T_RATIONAL:
3519 if (basic_to_f_p(rb_cRational))
3520 return rat2dbl_without_to_f(val);
3521 break;
3522 default:
3523 break;
3526 val = numeric_to_float(val);
3527 return RFLOAT_VALUE(val);
3530 double
3531 rb_num2dbl(VALUE val)
3533 if (SPECIAL_CONST_P(val)) {
3534 if (FIXNUM_P(val)) {
3535 return fix2dbl_without_to_f(val);
3537 else if (FLONUM_P(val)) {
3538 return rb_float_flonum_value(val);
3540 else {
3541 implicit_conversion_to_float(val);
3544 else {
3545 switch (BUILTIN_TYPE(val)) {
3546 case T_FLOAT:
3547 return rb_float_noflonum_value(val);
3548 case T_BIGNUM:
3549 return big2dbl_without_to_f(val);
3550 case T_RATIONAL:
3551 return rat2dbl_without_to_f(val);
3552 case T_STRING:
3553 rb_raise(rb_eTypeError, "no implicit conversion to float from string");
3554 default:
3555 break;
3558 val = rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3559 return RFLOAT_VALUE(val);
3562 VALUE
3563 rb_String(VALUE val)
3565 VALUE tmp = rb_check_string_type(val);
3566 if (NIL_P(tmp))
3567 tmp = rb_convert_type_with_id(val, T_STRING, "String", idTo_s);
3568 return tmp;
3573 * call-seq:
3574 * String(arg) -> string
3576 * Returns <i>arg</i> as a String.
3578 * First tries to call its <code>to_str</code> method, then its <code>to_s</code> method.
3580 * String(self) #=> "main"
3581 * String(self.class) #=> "Object"
3582 * String(123456) #=> "123456"
3585 static VALUE
3586 rb_f_string(VALUE obj, VALUE arg)
3588 return rb_String(arg);
3591 VALUE
3592 rb_Array(VALUE val)
3594 VALUE tmp = rb_check_array_type(val);
3596 if (NIL_P(tmp)) {
3597 tmp = rb_check_to_array(val);
3598 if (NIL_P(tmp)) {
3599 return rb_ary_new3(1, val);
3602 return tmp;
3606 * call-seq:
3607 * Array(arg) -> array
3609 * Returns +arg+ as an Array.
3611 * First tries to call <code>to_ary</code> on +arg+, then <code>to_a</code>.
3612 * If +arg+ does not respond to <code>to_ary</code> or <code>to_a</code>,
3613 * returns an Array of length 1 containing +arg+.
3615 * If <code>to_ary</code> or <code>to_a</code> returns something other than
3616 * an Array, raises a TypeError.
3618 * Array(["a", "b"]) #=> ["a", "b"]
3619 * Array(1..5) #=> [1, 2, 3, 4, 5]
3620 * Array(key: :value) #=> [[:key, :value]]
3621 * Array(nil) #=> []
3622 * Array(1) #=> [1]
3625 static VALUE
3626 rb_f_array(VALUE obj, VALUE arg)
3628 return rb_Array(arg);
3632 * Equivalent to \c Kernel\#Hash in Ruby
3634 VALUE
3635 rb_Hash(VALUE val)
3637 VALUE tmp;
3639 if (NIL_P(val)) return rb_hash_new();
3640 tmp = rb_check_hash_type(val);
3641 if (NIL_P(tmp)) {
3642 if (RB_TYPE_P(val, T_ARRAY) && RARRAY_LEN(val) == 0)
3643 return rb_hash_new();
3644 rb_raise(rb_eTypeError, "can't convert %s into Hash", rb_obj_classname(val));
3646 return tmp;
3650 * call-seq:
3651 * Hash(arg) -> hash
3653 * Converts <i>arg</i> to a Hash by calling
3654 * <i>arg</i><code>.to_hash</code>. Returns an empty Hash when
3655 * <i>arg</i> is <tt>nil</tt> or <tt>[]</tt>.
3657 * Hash([]) #=> {}
3658 * Hash(nil) #=> {}
3659 * Hash(key: :value) #=> {:key => :value}
3660 * Hash([1, 2, 3]) #=> TypeError
3663 static VALUE
3664 rb_f_hash(VALUE obj, VALUE arg)
3666 return rb_Hash(arg);
3669 /*! \private */
3670 struct dig_method {
3671 VALUE klass;
3672 int basic;
3675 static ID id_dig;
3677 static int
3678 dig_basic_p(VALUE obj, struct dig_method *cache)
3680 VALUE klass = RBASIC_CLASS(obj);
3681 if (klass != cache->klass) {
3682 cache->klass = klass;
3683 cache->basic = rb_method_basic_definition_p(klass, id_dig);
3685 return cache->basic;
3688 static void
3689 no_dig_method(int found, VALUE recv, ID mid, int argc, const VALUE *argv, VALUE data)
3691 if (!found) {
3692 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not have #dig method",
3693 CLASS_OF(data));
3697 /*! \private */
3698 VALUE
3699 rb_obj_dig(int argc, VALUE *argv, VALUE obj, VALUE notfound)
3701 struct dig_method hash = {Qnil}, ary = {Qnil}, strt = {Qnil};
3703 for (; argc > 0; ++argv, --argc) {
3704 if (NIL_P(obj)) return notfound;
3705 if (!SPECIAL_CONST_P(obj)) {
3706 switch (BUILTIN_TYPE(obj)) {
3707 case T_HASH:
3708 if (dig_basic_p(obj, &hash)) {
3709 obj = rb_hash_aref(obj, *argv);
3710 continue;
3712 break;
3713 case T_ARRAY:
3714 if (dig_basic_p(obj, &ary)) {
3715 obj = rb_ary_at(obj, *argv);
3716 continue;
3718 break;
3719 case T_STRUCT:
3720 if (dig_basic_p(obj, &strt)) {
3721 obj = rb_struct_lookup(obj, *argv);
3722 continue;
3724 break;
3725 default:
3726 break;
3729 return rb_check_funcall_with_hook_kw(obj, id_dig, argc, argv,
3730 no_dig_method, obj,
3731 RB_NO_KEYWORDS);
3733 return obj;
3737 * call-seq:
3738 * format(format_string [, arguments...] ) -> string
3739 * sprintf(format_string [, arguments...] ) -> string
3741 * Returns the string resulting from applying <i>format_string</i> to
3742 * any additional arguments. Within the format string, any characters
3743 * other than format sequences are copied to the result.
3745 * The syntax of a format sequence is as follows.
3747 * %[flags][width][.precision]type
3749 * A format
3750 * sequence consists of a percent sign, followed by optional flags,
3751 * width, and precision indicators, then terminated with a field type
3752 * character. The field type controls how the corresponding
3753 * <code>sprintf</code> argument is to be interpreted, while the flags
3754 * modify that interpretation.
3756 * The field type characters are:
3758 * Field | Integer Format
3759 * ------+--------------------------------------------------------------
3760 * b | Convert argument as a binary number.
3761 * | Negative numbers will be displayed as a two's complement
3762 * | prefixed with `..1'.
3763 * B | Equivalent to `b', but uses an uppercase 0B for prefix
3764 * | in the alternative format by #.
3765 * d | Convert argument as a decimal number.
3766 * i | Identical to `d'.
3767 * o | Convert argument as an octal number.
3768 * | Negative numbers will be displayed as a two's complement
3769 * | prefixed with `..7'.
3770 * u | Identical to `d'.
3771 * x | Convert argument as a hexadecimal number.
3772 * | Negative numbers will be displayed as a two's complement
3773 * | prefixed with `..f' (representing an infinite string of
3774 * | leading 'ff's).
3775 * X | Equivalent to `x', but uses uppercase letters.
3777 * Field | Float Format
3778 * ------+--------------------------------------------------------------
3779 * e | Convert floating point argument into exponential notation
3780 * | with one digit before the decimal point as [-]d.dddddde[+-]dd.
3781 * | The precision specifies the number of digits after the decimal
3782 * | point (defaulting to six).
3783 * E | Equivalent to `e', but uses an uppercase E to indicate
3784 * | the exponent.
3785 * f | Convert floating point argument as [-]ddd.dddddd,
3786 * | where the precision specifies the number of digits after
3787 * | the decimal point.
3788 * g | Convert a floating point number using exponential form
3789 * | if the exponent is less than -4 or greater than or
3790 * | equal to the precision, or in dd.dddd form otherwise.
3791 * | The precision specifies the number of significant digits.
3792 * G | Equivalent to `g', but use an uppercase `E' in exponent form.
3793 * a | Convert floating point argument as [-]0xh.hhhhp[+-]dd,
3794 * | which is consisted from optional sign, "0x", fraction part
3795 * | as hexadecimal, "p", and exponential part as decimal.
3796 * A | Equivalent to `a', but use uppercase `X' and `P'.
3798 * Field | Other Format
3799 * ------+--------------------------------------------------------------
3800 * c | Argument is the numeric code for a single character or
3801 * | a single character string itself.
3802 * p | The valuing of argument.inspect.
3803 * s | Argument is a string to be substituted. If the format
3804 * | sequence contains a precision, at most that many characters
3805 * | will be copied.
3806 * % | A percent sign itself will be displayed. No argument taken.
3808 * The flags modifies the behavior of the formats.
3809 * The flag characters are:
3811 * Flag | Applies to | Meaning
3812 * ---------+---------------+-----------------------------------------
3813 * space | bBdiouxX | Leave a space at the start of
3814 * | aAeEfgG | non-negative numbers.
3815 * | (numeric fmt) | For `o', `x', `X', `b' and `B', use
3816 * | | a minus sign with absolute value for
3817 * | | negative values.
3818 * ---------+---------------+-----------------------------------------
3819 * (digit)$ | all | Specifies the absolute argument number
3820 * | | for this field. Absolute and relative
3821 * | | argument numbers cannot be mixed in a
3822 * | | sprintf string.
3823 * ---------+---------------+-----------------------------------------
3824 * # | bBoxX | Use an alternative format.
3825 * | aAeEfgG | For the conversions `o', increase the precision
3826 * | | until the first digit will be `0' if
3827 * | | it is not formatted as complements.
3828 * | | For the conversions `x', `X', `b' and `B'
3829 * | | on non-zero, prefix the result with ``0x'',
3830 * | | ``0X'', ``0b'' and ``0B'', respectively.
3831 * | | For `a', `A', `e', `E', `f', `g', and 'G',
3832 * | | force a decimal point to be added,
3833 * | | even if no digits follow.
3834 * | | For `g' and 'G', do not remove trailing zeros.
3835 * ---------+---------------+-----------------------------------------
3836 * + | bBdiouxX | Add a leading plus sign to non-negative
3837 * | aAeEfgG | numbers.
3838 * | (numeric fmt) | For `o', `x', `X', `b' and `B', use
3839 * | | a minus sign with absolute value for
3840 * | | negative values.
3841 * ---------+---------------+-----------------------------------------
3842 * - | all | Left-justify the result of this conversion.
3843 * ---------+---------------+-----------------------------------------
3844 * 0 (zero) | bBdiouxX | Pad with zeros, not spaces.
3845 * | aAeEfgG | For `o', `x', `X', `b' and `B', radix-1
3846 * | (numeric fmt) | is used for negative numbers formatted as
3847 * | | complements.
3848 * ---------+---------------+-----------------------------------------
3849 * * | all | Use the next argument as the field width.
3850 * | | If negative, left-justify the result. If the
3851 * | | asterisk is followed by a number and a dollar
3852 * | | sign, use the indicated argument as the width.
3854 * Examples of flags:
3856 * # `+' and space flag specifies the sign of non-negative numbers.
3857 * sprintf("%d", 123) #=> "123"
3858 * sprintf("%+d", 123) #=> "+123"
3859 * sprintf("% d", 123) #=> " 123"
3861 * # `#' flag for `o' increases number of digits to show `0'.
3862 * # `+' and space flag changes format of negative numbers.
3863 * sprintf("%o", 123) #=> "173"
3864 * sprintf("%#o", 123) #=> "0173"
3865 * sprintf("%+o", -123) #=> "-173"
3866 * sprintf("%o", -123) #=> "..7605"
3867 * sprintf("%#o", -123) #=> "..7605"
3869 * # `#' flag for `x' add a prefix `0x' for non-zero numbers.
3870 * # `+' and space flag disables complements for negative numbers.
3871 * sprintf("%x", 123) #=> "7b"
3872 * sprintf("%#x", 123) #=> "0x7b"
3873 * sprintf("%+x", -123) #=> "-7b"
3874 * sprintf("%x", -123) #=> "..f85"
3875 * sprintf("%#x", -123) #=> "0x..f85"
3876 * sprintf("%#x", 0) #=> "0"
3878 * # `#' for `X' uses the prefix `0X'.
3879 * sprintf("%X", 123) #=> "7B"
3880 * sprintf("%#X", 123) #=> "0X7B"
3882 * # `#' flag for `b' add a prefix `0b' for non-zero numbers.
3883 * # `+' and space flag disables complements for negative numbers.
3884 * sprintf("%b", 123) #=> "1111011"
3885 * sprintf("%#b", 123) #=> "0b1111011"
3886 * sprintf("%+b", -123) #=> "-1111011"
3887 * sprintf("%b", -123) #=> "..10000101"
3888 * sprintf("%#b", -123) #=> "0b..10000101"
3889 * sprintf("%#b", 0) #=> "0"
3891 * # `#' for `B' uses the prefix `0B'.
3892 * sprintf("%B", 123) #=> "1111011"
3893 * sprintf("%#B", 123) #=> "0B1111011"
3895 * # `#' for `e' forces to show the decimal point.
3896 * sprintf("%.0e", 1) #=> "1e+00"
3897 * sprintf("%#.0e", 1) #=> "1.e+00"
3899 * # `#' for `f' forces to show the decimal point.
3900 * sprintf("%.0f", 1234) #=> "1234"
3901 * sprintf("%#.0f", 1234) #=> "1234."
3903 * # `#' for `g' forces to show the decimal point.
3904 * # It also disables stripping lowest zeros.
3905 * sprintf("%g", 123.4) #=> "123.4"
3906 * sprintf("%#g", 123.4) #=> "123.400"
3907 * sprintf("%g", 123456) #=> "123456"
3908 * sprintf("%#g", 123456) #=> "123456."
3910 * The field width is an optional integer, followed optionally by a
3911 * period and a precision. The width specifies the minimum number of
3912 * characters that will be written to the result for this field.
3914 * Examples of width:
3916 * # padding is done by spaces, width=20
3917 * # 0 or radix-1. <------------------>
3918 * sprintf("%20d", 123) #=> " 123"
3919 * sprintf("%+20d", 123) #=> " +123"
3920 * sprintf("%020d", 123) #=> "00000000000000000123"
3921 * sprintf("%+020d", 123) #=> "+0000000000000000123"
3922 * sprintf("% 020d", 123) #=> " 0000000000000000123"
3923 * sprintf("%-20d", 123) #=> "123 "
3924 * sprintf("%-+20d", 123) #=> "+123 "
3925 * sprintf("%- 20d", 123) #=> " 123 "
3926 * sprintf("%020x", -123) #=> "..ffffffffffffffff85"
3928 * For
3929 * numeric fields, the precision controls the number of decimal places
3930 * displayed. For string fields, the precision determines the maximum
3931 * number of characters to be copied from the string. (Thus, the format
3932 * sequence <code>%10.10s</code> will always contribute exactly ten
3933 * characters to the result.)
3935 * Examples of precisions:
3937 * # precision for `d', 'o', 'x' and 'b' is
3938 * # minimum number of digits <------>
3939 * sprintf("%20.8d", 123) #=> " 00000123"
3940 * sprintf("%20.8o", 123) #=> " 00000173"
3941 * sprintf("%20.8x", 123) #=> " 0000007b"
3942 * sprintf("%20.8b", 123) #=> " 01111011"
3943 * sprintf("%20.8d", -123) #=> " -00000123"
3944 * sprintf("%20.8o", -123) #=> " ..777605"
3945 * sprintf("%20.8x", -123) #=> " ..ffff85"
3946 * sprintf("%20.8b", -11) #=> " ..110101"
3948 * # "0x" and "0b" for `#x' and `#b' is not counted for
3949 * # precision but "0" for `#o' is counted. <------>
3950 * sprintf("%#20.8d", 123) #=> " 00000123"
3951 * sprintf("%#20.8o", 123) #=> " 00000173"
3952 * sprintf("%#20.8x", 123) #=> " 0x0000007b"
3953 * sprintf("%#20.8b", 123) #=> " 0b01111011"
3954 * sprintf("%#20.8d", -123) #=> " -00000123"
3955 * sprintf("%#20.8o", -123) #=> " ..777605"
3956 * sprintf("%#20.8x", -123) #=> " 0x..ffff85"
3957 * sprintf("%#20.8b", -11) #=> " 0b..110101"
3959 * # precision for `e' is number of
3960 * # digits after the decimal point <------>
3961 * sprintf("%20.8e", 1234.56789) #=> " 1.23456789e+03"
3963 * # precision for `f' is number of
3964 * # digits after the decimal point <------>
3965 * sprintf("%20.8f", 1234.56789) #=> " 1234.56789000"
3967 * # precision for `g' is number of
3968 * # significant digits <------->
3969 * sprintf("%20.8g", 1234.56789) #=> " 1234.5679"
3971 * # <------->
3972 * sprintf("%20.8g", 123456789) #=> " 1.2345679e+08"
3974 * # precision for `s' is
3975 * # maximum number of characters <------>
3976 * sprintf("%20.8s", "string test") #=> " string t"
3978 * Examples:
3980 * sprintf("%d %04x", 123, 123) #=> "123 007b"
3981 * sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'"
3982 * sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello"
3983 * sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8"
3984 * sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23"
3985 * sprintf("%u", -123) #=> "-123"
3987 * For more complex formatting, Ruby supports a reference by name.
3988 * %<name>s style uses format style, but %{name} style doesn't.
3990 * Examples:
3991 * sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 })
3992 * #=> 1 : 2.000000
3993 * sprintf("%{foo}f", { :foo => 1 })
3994 * # => "1f"
3997 static VALUE
3998 f_sprintf(int c, const VALUE *v, VALUE _)
4000 return rb_f_sprintf(c, v);
4004 * Document-class: Class
4006 * Classes in Ruby are first-class objects---each is an instance of
4007 * class Class.
4009 * Typically, you create a new class by using:
4011 * class Name
4012 * # some code describing the class behavior
4013 * end
4015 * When a new class is created, an object of type Class is initialized and
4016 * assigned to a global constant (Name in this case).
4018 * When <code>Name.new</code> is called to create a new object, the
4019 * #new method in Class is run by default.
4020 * This can be demonstrated by overriding #new in Class:
4022 * class Class
4023 * alias old_new new
4024 * def new(*args)
4025 * print "Creating a new ", self.name, "\n"
4026 * old_new(*args)
4027 * end
4028 * end
4030 * class Name
4031 * end
4033 * n = Name.new
4035 * <em>produces:</em>
4037 * Creating a new Name
4039 * Classes, modules, and objects are interrelated. In the diagram
4040 * that follows, the vertical arrows represent inheritance, and the
4041 * parentheses metaclasses. All metaclasses are instances
4042 * of the class `Class'.
4043 * +---------+ +-...
4044 * | | |
4045 * BasicObject-----|-->(BasicObject)-------|-...
4046 * ^ | ^ |
4047 * | | | |
4048 * Object---------|----->(Object)---------|-...
4049 * ^ | ^ |
4050 * | | | |
4051 * +-------+ | +--------+ |
4052 * | | | | | |
4053 * | Module-|---------|--->(Module)-|-...
4054 * | ^ | | ^ |
4055 * | | | | | |
4056 * | Class-|---------|---->(Class)-|-...
4057 * | ^ | | ^ |
4058 * | +---+ | +----+
4059 * | |
4060 * obj--->OtherClass---------->(OtherClass)-----------...
4065 /* Document-class: BasicObject
4067 * BasicObject is the parent class of all classes in Ruby. It's an explicit
4068 * blank class.
4070 * BasicObject can be used for creating object hierarchies independent of
4071 * Ruby's object hierarchy, proxy objects like the Delegator class, or other
4072 * uses where namespace pollution from Ruby's methods and classes must be
4073 * avoided.
4075 * To avoid polluting BasicObject for other users an appropriately named
4076 * subclass of BasicObject should be created instead of directly modifying
4077 * BasicObject:
4079 * class MyObjectSystem < BasicObject
4080 * end
4082 * BasicObject does not include Kernel (for methods like +puts+) and
4083 * BasicObject is outside of the namespace of the standard library so common
4084 * classes will not be found without using a full class path.
4086 * A variety of strategies can be used to provide useful portions of the
4087 * standard library to subclasses of BasicObject. A subclass could
4088 * <code>include Kernel</code> to obtain +puts+, +exit+, etc. A custom
4089 * Kernel-like module could be created and included or delegation can be used
4090 * via #method_missing:
4092 * class MyObjectSystem < BasicObject
4093 * DELEGATE = [:puts, :p]
4095 * def method_missing(name, *args, &block)
4096 * return super unless DELEGATE.include? name
4097 * ::Kernel.send(name, *args, &block)
4098 * end
4100 * def respond_to_missing?(name, include_private = false)
4101 * DELEGATE.include?(name) or super
4102 * end
4103 * end
4105 * Access to classes and modules from the Ruby standard library can be
4106 * obtained in a BasicObject subclass by referencing the desired constant
4107 * from the root like <code>::File</code> or <code>::Enumerator</code>.
4108 * Like #method_missing, #const_missing can be used to delegate constant
4109 * lookup to +Object+:
4111 * class MyObjectSystem < BasicObject
4112 * def self.const_missing(name)
4113 * ::Object.const_get(name)
4114 * end
4115 * end
4117 * === What's Here
4119 * These are the methods defined for \BasicObject:
4121 * - ::new:: Returns a new \BasicObject instance.
4122 * - {!}[#method-i-21]:: Returns the boolean negation of +self+: +true+ or +false+.
4123 * - {!=}[#method-i-21-3D]:: Returns whether +self+ and the given object
4124 * are _not_ equal.
4125 * - {==}[#method-i-3D-3D]:: Returns whether +self+ and the given object
4126 * are equivalent.
4127 * - {__id__}[#method-i-__id__]:: Returns the integer object identifier for +self+.
4128 * - {__send__}[#method-i-__send__]:: Calls the method identified by the given symbol.
4129 * - #equal?:: Returns whether +self+ and the given object are the same object.
4130 * - #instance_eval:: Evaluates the given string or block in the context of +self+.
4131 * - #instance_exec:: Executes the given block in the context of +self+,
4132 * passing the given arguments.
4133 * - #method_missing:: Method called when an undefined method is called on +self+.
4134 * - #singleton_method_added:: Method called when a singleton method
4135 * is added to +self+.
4136 * - #singleton_method_removed:: Method called when a singleton method
4137 * is added removed from +self+.
4138 * - #singleton_method_undefined:: Method called when a singleton method
4139 * is undefined in +self+.
4143 /* Document-class: Object
4145 * Object is the default root of all Ruby objects. Object inherits from
4146 * BasicObject which allows creating alternate object hierarchies. Methods
4147 * on Object are available to all classes unless explicitly overridden.
4149 * Object mixes in the Kernel module, making the built-in kernel functions
4150 * globally accessible. Although the instance methods of Object are defined
4151 * by the Kernel module, we have chosen to document them here for clarity.
4153 * When referencing constants in classes inheriting from Object you do not
4154 * need to use the full namespace. For example, referencing +File+ inside
4155 * +YourClass+ will find the top-level File class.
4157 * In the descriptions of Object's methods, the parameter <i>symbol</i> refers
4158 * to a symbol, which is either a quoted string or a Symbol (such as
4159 * <code>:name</code>).
4161 * == What's Here
4163 * First, what's elsewhere. \Class \Object:
4165 * - Inherits from {class BasicObject}[BasicObject.html#class-BasicObject-label-What-27s+Here].
4166 * - Includes {module Kernel}[Kernel.html#module-Kernel-label-What-27s+Here].
4168 * Here, class \Object provides methods for:
4170 * - {Querying}[#class-Object-label-Querying]
4171 * - {Instance Variables}[#class-Object-label-Instance+Variables]
4172 * - {Other}[#class-Object-label-Other]
4174 * === Querying
4176 * - {!~}[#method-i-21~]:: Returns +true+ if +self+ does not match the given object,
4177 * otherwise +false+.
4178 * - {<=>}[#method-i-3C-3D-3E]:: Returns 0 if +self+ and the given object +object+
4179 * are the same object, or if
4180 * <tt>self == object</tt>; otherwise returns +nil+.
4181 * - #===:: Implements case equality, effectively the same as calling #==.
4182 * - #eql?:: Implements hash equality, effectively the same as calling #==.
4183 * - #kind_of? (aliased as #is_a?):: Returns whether given argument is an ancestor
4184 * of the singleton class of +self+.
4185 * - #instance_of?:: Returns whether +self+ is an instance of the given class.
4186 * - #instance_variable_defined?:: Returns whether the given instance variable
4187 * is defined in +self+.
4188 * - #method:: Returns the Method object for the given method in +self+.
4189 * - #methods:: Returns an array of symbol names of public and protected methods
4190 * in +self+.
4191 * - #nil?:: Returns +false+. (Only +nil+ responds +true+ to method <tt>nil?</tt>.)
4192 * - #object_id:: Returns an integer corresponding to +self+ that is unique
4193 * for the current process
4194 * - #private_methods:: Returns an array of the symbol names
4195 * of the private methods in +self+.
4196 * - #protected_methods:: Returns an array of the symbol names
4197 * of the protected methods in +self+.
4198 * - #public_method:: Returns the Method object for the given public method in +self+.
4199 * - #public_methods:: Returns an array of the symbol names
4200 * of the public methods in +self+.
4201 * - #respond_to?:: Returns whether +self+ responds to the given method.
4202 * - #singleton_class:: Returns the singleton class of +self+.
4203 * - #singleton_method:: Returns the Method object for the given singleton method
4204 * in +self+.
4205 * - #singleton_methods:: Returns an array of the symbol names
4206 * of the singleton methods in +self+.
4208 * - #define_singleton_method:: Defines a singleton method in +self+
4209 * for the given symbol method-name and block or proc.
4210 * - #extend:: Includes the given modules in the singleton class of +self+.
4211 * - #public_send:: Calls the given public method in +self+ with the given argument.
4212 * - #send:: Calls the given method in +self+ with the given argument.
4214 * === Instance Variables
4216 * - #instance_variable_get:: Returns the value of the given instance variable
4217 * in +self+, or +nil+ if the instance variable is not set.
4218 * - #instance_variable_set:: Sets the value of the given instance variable in +self+
4219 * to the given object.
4220 * - #instance_variables:: Returns an array of the symbol names
4221 * of the instance variables in +self+.
4222 * - #remove_instance_variable:: Removes the named instance variable from +self+.
4224 * === Other
4226 * - #clone:: Returns a shallow copy of +self+, including singleton class
4227 * and frozen state.
4228 * - #define_singleton_method:: Defines a singleton method in +self+
4229 * for the given symbol method-name and block or proc.
4230 * - #display:: Prints +self+ to the given \IO stream or <tt>$stdout</tt>.
4231 * - #dup:: Returns a shallow unfrozen copy of +self+.
4232 * - #enum_for (aliased as #to_enum):: Returns an Enumerator for +self+
4233 * using the using the given method,
4234 * arguments, and block.
4235 * - #extend:: Includes the given modules in the singleton class of +self+.
4236 * - #freeze:: Prevents further modifications to +self+.
4237 * - #hash:: Returns the integer hash value for +self+.
4238 * - #inspect:: Returns a human-readable string representation of +self+.
4239 * - #itself:: Returns +self+.
4240 * - #public_send:: Calls the given public method in +self+ with the given argument.
4241 * - #send:: Calls the given method in +self+ with the given argument.
4242 * - #to_s:: Returns a string representation of +self+.
4248 * \private
4249 * Initializes the world of objects and classes.
4251 * At first, the function bootstraps the class hierarchy.
4252 * It initializes the most fundamental classes and their metaclasses.
4253 * - \c BasicObject
4254 * - \c Object
4255 * - \c Module
4256 * - \c Class
4257 * After the bootstrap step, the class hierarchy becomes as the following
4258 * diagram.
4260 * \image html boottime-classes.png
4262 * Then, the function defines classes, modules and methods as usual.
4263 * \ingroup class
4267 void
4268 InitVM_Object(void)
4270 Init_class_hierarchy();
4272 #if 0
4273 // teach RDoc about these classes
4274 rb_cBasicObject = rb_define_class("BasicObject", Qnil);
4275 rb_cObject = rb_define_class("Object", rb_cBasicObject);
4276 rb_cModule = rb_define_class("Module", rb_cObject);
4277 rb_cClass = rb_define_class("Class", rb_cModule);
4278 rb_cRefinement = rb_define_class("Refinement", rb_cModule);
4279 #endif
4281 rb_define_private_method(rb_cBasicObject, "initialize", rb_obj_initialize, 0);
4282 rb_define_alloc_func(rb_cBasicObject, rb_class_allocate_instance);
4283 rb_define_method(rb_cBasicObject, "==", rb_obj_equal, 1);
4284 rb_define_method(rb_cBasicObject, "equal?", rb_obj_equal, 1);
4285 rb_define_method(rb_cBasicObject, "!", rb_obj_not, 0);
4286 rb_define_method(rb_cBasicObject, "!=", rb_obj_not_equal, 1);
4288 rb_define_private_method(rb_cBasicObject, "singleton_method_added", rb_obj_singleton_method_added, 1);
4289 rb_define_private_method(rb_cBasicObject, "singleton_method_removed", rb_obj_singleton_method_removed, 1);
4290 rb_define_private_method(rb_cBasicObject, "singleton_method_undefined", rb_obj_singleton_method_undefined, 1);
4292 /* Document-module: Kernel
4294 * The Kernel module is included by class Object, so its methods are
4295 * available in every Ruby object.
4297 * The Kernel instance methods are documented in class Object while the
4298 * module methods are documented here. These methods are called without a
4299 * receiver and thus can be called in functional form:
4301 * sprintf "%.1f", 1.234 #=> "1.2"
4303 * == What's Here
4305 * \Module \Kernel provides methods that are useful for:
4307 * - {Converting}[#module-Kernel-label-Converting]
4308 * - {Querying}[#module-Kernel-label-Querying]
4309 * - {Exiting}[#module-Kernel-label-Exiting]
4310 * - {Exceptions}[#module-Kernel-label-Exceptions]
4311 * - {IO}[#module-Kernel-label-IO]
4312 * - {Procs}[#module-Kernel-label-Procs]
4313 * - {Tracing}[#module-Kernel-label-Tracing]
4314 * - {Subprocesses}[#module-Kernel-label-Subprocesses]
4315 * - {Loading}[#module-Kernel-label-Loading]
4316 * - {Yielding}[#module-Kernel-label-Yielding]
4317 * - {Random Values}[#module-Kernel-label-Random+Values]
4318 * - {Other}[#module-Kernel-label-Other]
4320 * === Converting
4322 * - {#Array}[#method-i-Array]:: Returns an Array based on the given argument.
4323 * - {#Complex}[#method-i-Complex]:: Returns a Complex based on the given arguments.
4324 * - {#Float}[#method-i-Float]:: Returns a Float based on the given arguments.
4325 * - {#Hash}[#method-i-Hash]:: Returns a Hash based on the given argument.
4326 * - {#Integer}[#method-i-Integer]:: Returns an Integer based on the given arguments.
4327 * - {#Rational}[#method-i-Rational]:: Returns a Rational
4328 * based on the given arguments.
4329 * - {#String}[#method-i-String]:: Returns a String based on the given argument.
4331 * === Querying
4333 * - {#__callee__}[#method-i-__callee__]:: Returns the called name
4334 * of the current method as a symbol.
4335 * - {#__dir__}[#method-i-__dir__]:: Returns the path to the directory
4336 * from which the current method is called.
4337 * - {#__method__}[#method-i-__method__]:: Returns the name
4338 * of the current method as a symbol.
4339 * - #autoload?:: Returns the file to be loaded when the given module is referenced.
4340 * - #binding:: Returns a Binding for the context at the point of call.
4341 * - #block_given?:: Returns +true+ if a block was passed to the calling method.
4342 * - #caller:: Returns the current execution stack as an array of strings.
4343 * - #caller_locations:: Returns the current execution stack as an array
4344 * of Thread::Backtrace::Location objects.
4345 * - #class:: Returns the class of +self+.
4346 * - #frozen?:: Returns whether +self+ is frozen.
4347 * - #global_variables:: Returns an array of global variables as symbols.
4348 * - #local_variables:: Returns an array of local variables as symbols.
4349 * - #test:: Performs specified tests on the given single file or pair of files.
4351 * === Exiting
4353 * - #abort:: Exits the current process after printing the given arguments.
4354 * - #at_exit:: Executes the given block when the process exits.
4355 * - #exit:: Exits the current process after calling any registered
4356 * +at_exit+ handlers.
4357 * - #exit!:: Exits the current process without calling any registered
4358 * +at_exit+ handlers.
4360 * === Exceptions
4362 * - #catch:: Executes the given block, possibly catching a thrown object.
4363 * - #raise (aliased as #fail):: Raises an exception based on the given arguments.
4364 * - #throw:: Returns from the active catch block waiting for the given tag.
4367 * === \IO
4369 * - #gets:: Returns and assigns to <tt>$_</tt> the next line from the current input.
4370 * - #open:: Creates an IO object connected to the given stream, file, or subprocess.
4371 * - #p:: Prints the given objects' inspect output to the standard output.
4372 * - #pp:: Prints the given objects in pretty form.
4373 * - #print:: Prints the given objects to standard output without a newline.
4374 * - #printf:: Prints the string resulting from applying the given format string
4375 * to any additional arguments.
4376 * - #putc:: Equivalent to <tt.$stdout.putc(object)</tt> for the given object.
4377 * - #puts:: Equivalent to <tt>$stdout.puts(*objects)</tt> for the given objects.
4378 * - #readline:: Similar to #gets, but raises an exception at the end of file.
4379 * - #readlines:: Returns an array of the remaining lines from the current input.
4380 * - #select:: Same as IO.select.
4382 * === Procs
4384 * - #lambda:: Returns a lambda proc for the given block.
4385 * - #proc:: Returns a new Proc; equivalent to Proc.new.
4387 * === Tracing
4389 * - #set_trace_func:: Sets the given proc as the handler for tracing,
4390 * or disables tracing if given +nil+.
4391 * - #trace_var:: Starts tracing assignments to the given global variable.
4392 * - #untrace_var:: Disables tracing of assignments to the given global variable.
4394 * === Subprocesses
4396 * - #`cmd`:: Returns the standard output of running +cmd+ in a subshell.
4397 * - #exec:: Replaces current process with a new process.
4398 * - #fork:: Forks the current process into two processes.
4399 * - #spawn:: Executes the given command and returns its pid without waiting
4400 * for completion.
4401 * - #system:: Executes the given command in a subshell.
4403 * === Loading
4405 * - #autoload:: Registers the given file to be loaded when the given constant
4406 * is first referenced.
4407 * - #load:: Loads the given Ruby file.
4408 * - #require:: Loads the given Ruby file unless it has already been loaded.
4409 * - #require_relative:: Loads the Ruby file path relative to the calling file,
4410 * unless it has already been loaded.
4412 * === Yielding
4414 * - #tap:: Yields +self+ to the given block; returns +self+.
4415 * - #then (aliased as #yield_self):: Yields +self+ to the block
4416 * and returns the result of the block.
4418 * === \Random Values
4420 * - #rand:: Returns a pseudo-random floating point number
4421 * strictly between 0.0 and 1.0.
4422 * - #srand:: Seeds the pseudo-random number generator with the given number.
4424 * === Other
4426 * - #eval:: Evaluates the given string as Ruby code.
4427 * - #loop:: Repeatedly executes the given block.
4428 * - #sleep:: Suspends the current thread for the given number of seconds.
4429 * - #sprintf (aliased as #format):: Returns the string resulting from applying
4430 * the given format string
4431 * to any additional arguments.
4432 * - #syscall:: Runs an operating system call.
4433 * - #trap:: Specifies the handling of system signals.
4434 * - #warn:: Issue a warning based on the given messages and options.
4437 rb_mKernel = rb_define_module("Kernel");
4438 rb_include_module(rb_cObject, rb_mKernel);
4439 rb_define_private_method(rb_cClass, "inherited", rb_obj_class_inherited, 1);
4440 rb_define_private_method(rb_cModule, "included", rb_obj_mod_included, 1);
4441 rb_define_private_method(rb_cModule, "extended", rb_obj_mod_extended, 1);
4442 rb_define_private_method(rb_cModule, "prepended", rb_obj_mod_prepended, 1);
4443 rb_define_private_method(rb_cModule, "method_added", rb_obj_mod_method_added, 1);
4444 rb_define_private_method(rb_cModule, "const_added", rb_obj_mod_const_added, 1);
4445 rb_define_private_method(rb_cModule, "method_removed", rb_obj_mod_method_removed, 1);
4446 rb_define_private_method(rb_cModule, "method_undefined", rb_obj_mod_method_undefined, 1);
4448 rb_define_method(rb_mKernel, "nil?", rb_false, 0);
4449 rb_define_method(rb_mKernel, "===", case_equal, 1);
4450 rb_define_method(rb_mKernel, "!~", rb_obj_not_match, 1);
4451 rb_define_method(rb_mKernel, "eql?", rb_obj_equal, 1);
4452 rb_define_method(rb_mKernel, "hash", rb_obj_hash, 0); /* in hash.c */
4453 rb_define_method(rb_mKernel, "<=>", rb_obj_cmp, 1);
4455 rb_define_method(rb_mKernel, "singleton_class", rb_obj_singleton_class, 0);
4456 rb_define_method(rb_mKernel, "dup", rb_obj_dup, 0);
4457 rb_define_method(rb_mKernel, "itself", rb_obj_itself, 0);
4458 rb_define_method(rb_mKernel, "initialize_copy", rb_obj_init_copy, 1);
4459 rb_define_method(rb_mKernel, "initialize_dup", rb_obj_init_dup_clone, 1);
4460 rb_define_method(rb_mKernel, "initialize_clone", rb_obj_init_clone, -1);
4462 rb_define_method(rb_mKernel, "freeze", rb_obj_freeze, 0);
4464 rb_define_method(rb_mKernel, "to_s", rb_any_to_s, 0);
4465 rb_define_method(rb_mKernel, "inspect", rb_obj_inspect, 0);
4466 rb_define_method(rb_mKernel, "methods", rb_obj_methods, -1); /* in class.c */
4467 rb_define_method(rb_mKernel, "singleton_methods", rb_obj_singleton_methods, -1); /* in class.c */
4468 rb_define_method(rb_mKernel, "protected_methods", rb_obj_protected_methods, -1); /* in class.c */
4469 rb_define_method(rb_mKernel, "private_methods", rb_obj_private_methods, -1); /* in class.c */
4470 rb_define_method(rb_mKernel, "public_methods", rb_obj_public_methods, -1); /* in class.c */
4471 rb_define_method(rb_mKernel, "instance_variables", rb_obj_instance_variables, 0); /* in variable.c */
4472 rb_define_method(rb_mKernel, "instance_variable_get", rb_obj_ivar_get, 1);
4473 rb_define_method(rb_mKernel, "instance_variable_set", rb_obj_ivar_set, 2);
4474 rb_define_method(rb_mKernel, "instance_variable_defined?", rb_obj_ivar_defined, 1);
4475 rb_define_method(rb_mKernel, "remove_instance_variable",
4476 rb_obj_remove_instance_variable, 1); /* in variable.c */
4478 rb_define_method(rb_mKernel, "instance_of?", rb_obj_is_instance_of, 1);
4479 rb_define_method(rb_mKernel, "kind_of?", rb_obj_is_kind_of, 1);
4480 rb_define_method(rb_mKernel, "is_a?", rb_obj_is_kind_of, 1);
4482 rb_define_global_function("sprintf", f_sprintf, -1);
4483 rb_define_global_function("format", f_sprintf, -1);
4485 rb_define_global_function("Integer", rb_f_integer, -1);
4487 rb_define_global_function("String", rb_f_string, 1);
4488 rb_define_global_function("Array", rb_f_array, 1);
4489 rb_define_global_function("Hash", rb_f_hash, 1);
4491 rb_cNilClass = rb_define_class("NilClass", rb_cObject);
4492 rb_cNilClass_to_s = rb_fstring_enc_lit("", rb_usascii_encoding());
4493 rb_gc_register_mark_object(rb_cNilClass_to_s);
4494 rb_define_method(rb_cNilClass, "to_s", rb_nil_to_s, 0);
4495 rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0);
4496 rb_define_method(rb_cNilClass, "to_h", nil_to_h, 0);
4497 rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0);
4498 rb_define_method(rb_cNilClass, "=~", nil_match, 1);
4499 rb_define_method(rb_cNilClass, "&", false_and, 1);
4500 rb_define_method(rb_cNilClass, "|", false_or, 1);
4501 rb_define_method(rb_cNilClass, "^", false_xor, 1);
4502 rb_define_method(rb_cNilClass, "===", case_equal, 1);
4504 rb_define_method(rb_cNilClass, "nil?", rb_true, 0);
4505 rb_undef_alloc_func(rb_cNilClass);
4506 rb_undef_method(CLASS_OF(rb_cNilClass), "new");
4508 rb_define_method(rb_cModule, "freeze", rb_mod_freeze, 0);
4509 rb_define_method(rb_cModule, "===", rb_mod_eqq, 1);
4510 rb_define_method(rb_cModule, "==", rb_obj_equal, 1);
4511 rb_define_method(rb_cModule, "<=>", rb_mod_cmp, 1);
4512 rb_define_method(rb_cModule, "<", rb_mod_lt, 1);
4513 rb_define_method(rb_cModule, "<=", rb_class_inherited_p, 1);
4514 rb_define_method(rb_cModule, ">", rb_mod_gt, 1);
4515 rb_define_method(rb_cModule, ">=", rb_mod_ge, 1);
4516 rb_define_method(rb_cModule, "initialize_copy", rb_mod_init_copy, 1); /* in class.c */
4517 rb_define_method(rb_cModule, "to_s", rb_mod_to_s, 0);
4518 rb_define_alias(rb_cModule, "inspect", "to_s");
4519 rb_define_method(rb_cModule, "included_modules", rb_mod_included_modules, 0); /* in class.c */
4520 rb_define_method(rb_cModule, "include?", rb_mod_include_p, 1); /* in class.c */
4521 rb_define_method(rb_cModule, "name", rb_mod_name, 0); /* in variable.c */
4522 rb_define_method(rb_cModule, "ancestors", rb_mod_ancestors, 0); /* in class.c */
4524 rb_define_method(rb_cModule, "attr", rb_mod_attr, -1);
4525 rb_define_method(rb_cModule, "attr_reader", rb_mod_attr_reader, -1);
4526 rb_define_method(rb_cModule, "attr_writer", rb_mod_attr_writer, -1);
4527 rb_define_method(rb_cModule, "attr_accessor", rb_mod_attr_accessor, -1);
4529 rb_define_alloc_func(rb_cModule, rb_module_s_alloc);
4530 rb_undef_method(rb_singleton_class(rb_cModule), "allocate");
4531 rb_define_method(rb_cModule, "initialize", rb_mod_initialize, 0);
4532 rb_define_method(rb_cModule, "initialize_clone", rb_mod_initialize_clone, -1);
4533 rb_define_method(rb_cModule, "instance_methods", rb_class_instance_methods, -1); /* in class.c */
4534 rb_define_method(rb_cModule, "public_instance_methods",
4535 rb_class_public_instance_methods, -1); /* in class.c */
4536 rb_define_method(rb_cModule, "protected_instance_methods",
4537 rb_class_protected_instance_methods, -1); /* in class.c */
4538 rb_define_method(rb_cModule, "private_instance_methods",
4539 rb_class_private_instance_methods, -1); /* in class.c */
4541 rb_define_method(rb_cModule, "constants", rb_mod_constants, -1); /* in variable.c */
4542 rb_define_method(rb_cModule, "const_get", rb_mod_const_get, -1);
4543 rb_define_method(rb_cModule, "const_set", rb_mod_const_set, 2);
4544 rb_define_method(rb_cModule, "const_defined?", rb_mod_const_defined, -1);
4545 rb_define_method(rb_cModule, "const_source_location", rb_mod_const_source_location, -1);
4546 rb_define_private_method(rb_cModule, "remove_const",
4547 rb_mod_remove_const, 1); /* in variable.c */
4548 rb_define_method(rb_cModule, "const_missing",
4549 rb_mod_const_missing, 1); /* in variable.c */
4550 rb_define_method(rb_cModule, "class_variables",
4551 rb_mod_class_variables, -1); /* in variable.c */
4552 rb_define_method(rb_cModule, "remove_class_variable",
4553 rb_mod_remove_cvar, 1); /* in variable.c */
4554 rb_define_method(rb_cModule, "class_variable_get", rb_mod_cvar_get, 1);
4555 rb_define_method(rb_cModule, "class_variable_set", rb_mod_cvar_set, 2);
4556 rb_define_method(rb_cModule, "class_variable_defined?", rb_mod_cvar_defined, 1);
4557 rb_define_method(rb_cModule, "public_constant", rb_mod_public_constant, -1); /* in variable.c */
4558 rb_define_method(rb_cModule, "private_constant", rb_mod_private_constant, -1); /* in variable.c */
4559 rb_define_method(rb_cModule, "deprecate_constant", rb_mod_deprecate_constant, -1); /* in variable.c */
4560 rb_define_method(rb_cModule, "singleton_class?", rb_mod_singleton_p, 0);
4562 rb_define_method(rb_singleton_class(rb_cClass), "allocate", rb_class_alloc_m, 0);
4563 rb_define_method(rb_cClass, "allocate", rb_class_alloc_m, 0);
4564 rb_define_method(rb_cClass, "new", rb_class_new_instance_pass_kw, -1);
4565 rb_define_method(rb_cClass, "initialize", rb_class_initialize, -1);
4566 rb_define_method(rb_cClass, "superclass", rb_class_superclass, 0);
4567 rb_define_method(rb_cClass, "subclasses", rb_class_subclasses, 0); /* in class.c */
4568 rb_define_alloc_func(rb_cClass, rb_class_s_alloc);
4569 rb_undef_method(rb_cClass, "extend_object");
4570 rb_undef_method(rb_cClass, "append_features");
4571 rb_undef_method(rb_cClass, "prepend_features");
4573 rb_cTrueClass = rb_define_class("TrueClass", rb_cObject);
4574 rb_cTrueClass_to_s = rb_fstring_enc_lit("true", rb_usascii_encoding());
4575 rb_gc_register_mark_object(rb_cTrueClass_to_s);
4576 rb_define_method(rb_cTrueClass, "to_s", rb_true_to_s, 0);
4577 rb_define_alias(rb_cTrueClass, "inspect", "to_s");
4578 rb_define_method(rb_cTrueClass, "&", true_and, 1);
4579 rb_define_method(rb_cTrueClass, "|", true_or, 1);
4580 rb_define_method(rb_cTrueClass, "^", true_xor, 1);
4581 rb_define_method(rb_cTrueClass, "===", case_equal, 1);
4582 rb_undef_alloc_func(rb_cTrueClass);
4583 rb_undef_method(CLASS_OF(rb_cTrueClass), "new");
4585 rb_cFalseClass = rb_define_class("FalseClass", rb_cObject);
4586 rb_cFalseClass_to_s = rb_fstring_enc_lit("false", rb_usascii_encoding());
4587 rb_gc_register_mark_object(rb_cFalseClass_to_s);
4588 rb_define_method(rb_cFalseClass, "to_s", rb_false_to_s, 0);
4589 rb_define_alias(rb_cFalseClass, "inspect", "to_s");
4590 rb_define_method(rb_cFalseClass, "&", false_and, 1);
4591 rb_define_method(rb_cFalseClass, "|", false_or, 1);
4592 rb_define_method(rb_cFalseClass, "^", false_xor, 1);
4593 rb_define_method(rb_cFalseClass, "===", case_equal, 1);
4594 rb_undef_alloc_func(rb_cFalseClass);
4595 rb_undef_method(CLASS_OF(rb_cFalseClass), "new");
4598 #include "kernel.rbinc"
4599 #include "nilclass.rbinc"
4601 void
4602 Init_Object(void)
4604 id_dig = rb_intern_const("dig");
4605 InitVM(Object);
4609 * \}