[ruby/win32ole] Undefine allocator of WIN32OLE_VARIABLE to get rid of warning
[ruby-80x24.org.git] / object.c
bloba34d971606fb0f8e5c595502c34535c179f180ca
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 RTEST(obj) ? Qfalse : Qtrue;
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 RTEST(result) ? Qfalse : Qtrue;
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
1009 * Document-method: extended
1011 * call-seq:
1012 * extended(othermod)
1014 * The equivalent of <tt>included</tt>, but for extended modules.
1016 * module A
1017 * def self.extended(mod)
1018 * puts "#{self} extended in #{mod}"
1019 * end
1020 * end
1021 * module Enumerable
1022 * extend A
1023 * end
1024 * # => prints "A extended in Enumerable"
1026 #define rb_obj_mod_extended rb_obj_dummy1
1029 * Document-method: included
1031 * call-seq:
1032 * included(othermod)
1034 * Callback invoked whenever the receiver is included in another
1035 * module or class. This should be used in preference to
1036 * <tt>Module.append_features</tt> if your code wants to perform some
1037 * action when a module is included in another.
1039 * module A
1040 * def A.included(mod)
1041 * puts "#{self} included in #{mod}"
1042 * end
1043 * end
1044 * module Enumerable
1045 * include A
1046 * end
1047 * # => prints "A included in Enumerable"
1049 #define rb_obj_mod_included rb_obj_dummy1
1052 * Document-method: prepended
1054 * call-seq:
1055 * prepended(othermod)
1057 * The equivalent of <tt>included</tt>, but for prepended modules.
1059 * module A
1060 * def self.prepended(mod)
1061 * puts "#{self} prepended to #{mod}"
1062 * end
1063 * end
1064 * module Enumerable
1065 * prepend A
1066 * end
1067 * # => prints "A prepended to Enumerable"
1069 #define rb_obj_mod_prepended rb_obj_dummy1
1072 * Document-method: initialize
1074 * call-seq:
1075 * BasicObject.new
1077 * Returns a new BasicObject.
1079 #define rb_obj_initialize rb_obj_dummy0
1082 * Not documented
1085 static VALUE
1086 rb_obj_dummy(void)
1088 return Qnil;
1091 static VALUE
1092 rb_obj_dummy0(VALUE _)
1094 return rb_obj_dummy();
1097 static VALUE
1098 rb_obj_dummy1(VALUE _x, VALUE _y)
1100 return rb_obj_dummy();
1104 * call-seq:
1105 * obj.freeze -> obj
1107 * Prevents further modifications to <i>obj</i>. A
1108 * FrozenError will be raised if modification is attempted.
1109 * There is no way to unfreeze a frozen object. See also
1110 * Object#frozen?.
1112 * This method returns self.
1114 * a = [ "a", "b", "c" ]
1115 * a.freeze
1116 * a << "z"
1118 * <em>produces:</em>
1120 * prog.rb:3:in `<<': can't modify frozen Array (FrozenError)
1121 * from prog.rb:3
1123 * Objects of the following classes are always frozen: Integer,
1124 * Float, Symbol.
1127 VALUE
1128 rb_obj_freeze(VALUE obj)
1130 if (!OBJ_FROZEN(obj)) {
1131 OBJ_FREEZE(obj);
1132 if (SPECIAL_CONST_P(obj)) {
1133 rb_bug("special consts should be frozen.");
1136 return obj;
1139 VALUE
1140 rb_obj_frozen_p(VALUE obj)
1142 return RBOOL(OBJ_FROZEN(obj));
1147 * Document-class: NilClass
1149 * The class of the singleton object <code>nil</code>.
1153 * call-seq:
1154 * nil.to_s -> ""
1156 * Always returns the empty string.
1159 MJIT_FUNC_EXPORTED VALUE
1160 rb_nil_to_s(VALUE obj)
1162 return rb_cNilClass_to_s;
1166 * Document-method: to_a
1168 * call-seq:
1169 * nil.to_a -> []
1171 * Always returns an empty array.
1173 * nil.to_a #=> []
1176 static VALUE
1177 nil_to_a(VALUE obj)
1179 return rb_ary_new2(0);
1183 * Document-method: to_h
1185 * call-seq:
1186 * nil.to_h -> {}
1188 * Always returns an empty hash.
1190 * nil.to_h #=> {}
1193 static VALUE
1194 nil_to_h(VALUE obj)
1196 return rb_hash_new();
1200 * call-seq:
1201 * nil.inspect -> "nil"
1203 * Always returns the string "nil".
1206 static VALUE
1207 nil_inspect(VALUE obj)
1209 return rb_usascii_str_new2("nil");
1213 * call-seq:
1214 * nil =~ other -> nil
1216 * Dummy pattern matching -- always returns nil.
1219 static VALUE
1220 nil_match(VALUE obj1, VALUE obj2)
1222 return Qnil;
1225 /***********************************************************************
1226 * Document-class: TrueClass
1228 * The global value <code>true</code> is the only instance of class
1229 * TrueClass and represents a logically true value in
1230 * boolean expressions. The class provides operators allowing
1231 * <code>true</code> to be used in logical expressions.
1236 * call-seq:
1237 * true.to_s -> "true"
1239 * The string representation of <code>true</code> is "true".
1242 MJIT_FUNC_EXPORTED VALUE
1243 rb_true_to_s(VALUE obj)
1245 return rb_cTrueClass_to_s;
1250 * call-seq:
1251 * true & obj -> true or false
1253 * And---Returns <code>false</code> if <i>obj</i> is
1254 * <code>nil</code> or <code>false</code>, <code>true</code> otherwise.
1257 static VALUE
1258 true_and(VALUE obj, VALUE obj2)
1260 return RBOOL(RTEST(obj2));
1264 * call-seq:
1265 * true | obj -> true
1267 * Or---Returns <code>true</code>. As <i>obj</i> is an argument to
1268 * a method call, it is always evaluated; there is no short-circuit
1269 * evaluation in this case.
1271 * true | puts("or")
1272 * true || puts("logical or")
1274 * <em>produces:</em>
1276 * or
1279 static VALUE
1280 true_or(VALUE obj, VALUE obj2)
1282 return Qtrue;
1287 * call-seq:
1288 * true ^ obj -> !obj
1290 * Exclusive Or---Returns <code>true</code> if <i>obj</i> is
1291 * <code>nil</code> or <code>false</code>, <code>false</code>
1292 * otherwise.
1295 static VALUE
1296 true_xor(VALUE obj, VALUE obj2)
1298 return RTEST(obj2)?Qfalse:Qtrue;
1303 * Document-class: FalseClass
1305 * The global value <code>false</code> is the only instance of class
1306 * FalseClass and represents a logically false value in
1307 * boolean expressions. The class provides operators allowing
1308 * <code>false</code> to participate correctly in logical expressions.
1313 * call-seq:
1314 * false.to_s -> "false"
1316 * The string representation of <code>false</code> is "false".
1319 MJIT_FUNC_EXPORTED VALUE
1320 rb_false_to_s(VALUE obj)
1322 return rb_cFalseClass_to_s;
1326 * call-seq:
1327 * false & obj -> false
1328 * nil & obj -> false
1330 * And---Returns <code>false</code>. <i>obj</i> is always
1331 * evaluated as it is the argument to a method call---there is no
1332 * short-circuit evaluation in this case.
1335 static VALUE
1336 false_and(VALUE obj, VALUE obj2)
1338 return Qfalse;
1343 * call-seq:
1344 * false | obj -> true or false
1345 * nil | obj -> true or false
1347 * Or---Returns <code>false</code> if <i>obj</i> is
1348 * <code>nil</code> or <code>false</code>; <code>true</code> otherwise.
1351 #define false_or true_and
1354 * call-seq:
1355 * false ^ obj -> true or false
1356 * nil ^ obj -> true or false
1358 * Exclusive Or---If <i>obj</i> is <code>nil</code> or
1359 * <code>false</code>, returns <code>false</code>; otherwise, returns
1360 * <code>true</code>.
1364 #define false_xor true_and
1367 * call-seq:
1368 * nil.nil? -> true
1370 * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1373 static VALUE
1374 rb_true(VALUE obj)
1376 return Qtrue;
1380 * call-seq:
1381 * obj.nil? -> true or false
1383 * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1385 * Object.new.nil? #=> false
1386 * nil.nil? #=> true
1390 MJIT_FUNC_EXPORTED VALUE
1391 rb_false(VALUE obj)
1393 return Qfalse;
1398 * call-seq:
1399 * obj =~ other -> nil
1401 * This method is deprecated.
1403 * This is not only useless but also troublesome because it may hide a
1404 * type error.
1407 static VALUE
1408 rb_obj_match(VALUE obj1, VALUE obj2)
1410 if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) {
1411 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "deprecated Object#=~ is called on %"PRIsVALUE
1412 "; it always returns nil", rb_obj_class(obj1));
1414 return Qnil;
1418 * call-seq:
1419 * obj !~ other -> true or false
1421 * Returns true if two objects do not match (using the <i>=~</i>
1422 * method), otherwise false.
1425 static VALUE
1426 rb_obj_not_match(VALUE obj1, VALUE obj2)
1428 VALUE result = rb_funcall(obj1, id_match, 1, obj2);
1429 return RTEST(result) ? Qfalse : Qtrue;
1434 * call-seq:
1435 * obj <=> other -> 0 or nil
1437 * Returns 0 if +obj+ and +other+ are the same object
1438 * or <code>obj == other</code>, otherwise nil.
1440 * The #<=> is used by various methods to compare objects, for example
1441 * Enumerable#sort, Enumerable#max etc.
1443 * Your implementation of #<=> should return one of the following values: -1, 0,
1444 * 1 or nil. -1 means self is smaller than other. 0 means self is equal to other.
1445 * 1 means self is bigger than other. Nil means the two values could not be
1446 * compared.
1448 * When you define #<=>, you can include Comparable to gain the
1449 * methods #<=, #<, #==, #>=, #> and #between?.
1451 static VALUE
1452 rb_obj_cmp(VALUE obj1, VALUE obj2)
1454 if (rb_equal(obj1, obj2))
1455 return INT2FIX(0);
1456 return Qnil;
1459 /***********************************************************************
1461 * Document-class: Module
1463 * A Module is a collection of methods and constants. The
1464 * methods in a module may be instance methods or module methods.
1465 * Instance methods appear as methods in a class when the module is
1466 * included, module methods do not. Conversely, module methods may be
1467 * called without creating an encapsulating object, while instance
1468 * methods may not. (See Module#module_function.)
1470 * In the descriptions that follow, the parameter <i>sym</i> refers
1471 * to a symbol, which is either a quoted string or a
1472 * Symbol (such as <code>:name</code>).
1474 * module Mod
1475 * include Math
1476 * CONST = 1
1477 * def meth
1478 * # ...
1479 * end
1480 * end
1481 * Mod.class #=> Module
1482 * Mod.constants #=> [:CONST, :PI, :E]
1483 * Mod.instance_methods #=> [:meth]
1488 * call-seq:
1489 * mod.to_s -> string
1491 * Returns a string representing this module or class. For basic
1492 * classes and modules, this is the name. For singletons, we
1493 * show information on the thing we're attached to as well.
1496 MJIT_FUNC_EXPORTED VALUE
1497 rb_mod_to_s(VALUE klass)
1499 ID id_defined_at;
1500 VALUE refined_class, defined_at;
1502 if (FL_TEST(klass, FL_SINGLETON)) {
1503 VALUE s = rb_usascii_str_new2("#<Class:");
1504 VALUE v = rb_ivar_get(klass, id__attached__);
1506 if (CLASS_OR_MODULE_P(v)) {
1507 rb_str_append(s, rb_inspect(v));
1509 else {
1510 rb_str_append(s, rb_any_to_s(v));
1512 rb_str_cat2(s, ">");
1514 return s;
1516 refined_class = rb_refinement_module_get_refined_class(klass);
1517 if (!NIL_P(refined_class)) {
1518 VALUE s = rb_usascii_str_new2("#<refinement:");
1520 rb_str_concat(s, rb_inspect(refined_class));
1521 rb_str_cat2(s, "@");
1522 CONST_ID(id_defined_at, "__defined_at__");
1523 defined_at = rb_attr_get(klass, id_defined_at);
1524 rb_str_concat(s, rb_inspect(defined_at));
1525 rb_str_cat2(s, ">");
1526 return s;
1528 return rb_class_name(klass);
1532 * call-seq:
1533 * mod.freeze -> mod
1535 * Prevents further modifications to <i>mod</i>.
1537 * This method returns self.
1540 static VALUE
1541 rb_mod_freeze(VALUE mod)
1543 rb_class_name(mod);
1544 return rb_obj_freeze(mod);
1548 * call-seq:
1549 * mod === obj -> true or false
1551 * Case Equality---Returns <code>true</code> if <i>obj</i> is an
1552 * instance of <i>mod</i> or an instance of one of <i>mod</i>'s descendants.
1553 * Of limited use for modules, but can be used in <code>case</code> statements
1554 * to classify objects by class.
1557 static VALUE
1558 rb_mod_eqq(VALUE mod, VALUE arg)
1560 return rb_obj_is_kind_of(arg, mod);
1564 * call-seq:
1565 * mod <= other -> true, false, or nil
1567 * Returns true if <i>mod</i> is a subclass of <i>other</i> or
1568 * is the same as <i>other</i>. Returns
1569 * <code>nil</code> if there's no relationship between the two.
1570 * (Think of the relationship in terms of the class definition:
1571 * "class A < B" implies "A < B".)
1574 VALUE
1575 rb_class_inherited_p(VALUE mod, VALUE arg)
1577 if (mod == arg) return Qtrue;
1578 if (!CLASS_OR_MODULE_P(arg) && !RB_TYPE_P(arg, T_ICLASS)) {
1579 rb_raise(rb_eTypeError, "compared with non class/module");
1581 if (class_search_ancestor(mod, RCLASS_ORIGIN(arg))) {
1582 return Qtrue;
1584 /* not mod < arg; check if mod > arg */
1585 if (class_search_ancestor(arg, mod)) {
1586 return Qfalse;
1588 return Qnil;
1592 * call-seq:
1593 * mod < other -> true, false, or nil
1595 * Returns true if <i>mod</i> is a subclass of <i>other</i>. Returns
1596 * <code>nil</code> if there's no relationship between the two.
1597 * (Think of the relationship in terms of the class definition:
1598 * "class A < B" implies "A < B".)
1602 static VALUE
1603 rb_mod_lt(VALUE mod, VALUE arg)
1605 if (mod == arg) return Qfalse;
1606 return rb_class_inherited_p(mod, arg);
1611 * call-seq:
1612 * mod >= other -> true, false, or nil
1614 * Returns true if <i>mod</i> is an ancestor of <i>other</i>, or the
1615 * two modules are the same. Returns
1616 * <code>nil</code> if there's no relationship between the two.
1617 * (Think of the relationship in terms of the class definition:
1618 * "class A < B" implies "B > A".)
1622 static VALUE
1623 rb_mod_ge(VALUE mod, VALUE arg)
1625 if (!CLASS_OR_MODULE_P(arg)) {
1626 rb_raise(rb_eTypeError, "compared with non class/module");
1629 return rb_class_inherited_p(arg, mod);
1633 * call-seq:
1634 * mod > other -> true, false, or nil
1636 * Returns true if <i>mod</i> is an ancestor of <i>other</i>. Returns
1637 * <code>nil</code> if there's no relationship between the two.
1638 * (Think of the relationship in terms of the class definition:
1639 * "class A < B" implies "B > A".)
1643 static VALUE
1644 rb_mod_gt(VALUE mod, VALUE arg)
1646 if (mod == arg) return Qfalse;
1647 return rb_mod_ge(mod, arg);
1651 * call-seq:
1652 * module <=> other_module -> -1, 0, +1, or nil
1654 * Comparison---Returns -1, 0, +1 or nil depending on whether +module+
1655 * includes +other_module+, they are the same, or if +module+ is included by
1656 * +other_module+.
1658 * Returns +nil+ if +module+ has no relationship with +other_module+, if
1659 * +other_module+ is not a module, or if the two values are incomparable.
1662 static VALUE
1663 rb_mod_cmp(VALUE mod, VALUE arg)
1665 VALUE cmp;
1667 if (mod == arg) return INT2FIX(0);
1668 if (!CLASS_OR_MODULE_P(arg)) {
1669 return Qnil;
1672 cmp = rb_class_inherited_p(mod, arg);
1673 if (NIL_P(cmp)) return Qnil;
1674 if (cmp) {
1675 return INT2FIX(-1);
1677 return INT2FIX(1);
1680 static VALUE rb_mod_initialize_exec(VALUE module);
1683 * call-seq:
1684 * Module.new -> mod
1685 * Module.new {|mod| block } -> mod
1687 * Creates a new anonymous module. If a block is given, it is passed
1688 * the module object, and the block is evaluated in the context of this
1689 * module like #module_eval.
1691 * fred = Module.new do
1692 * def meth1
1693 * "hello"
1694 * end
1695 * def meth2
1696 * "bye"
1697 * end
1698 * end
1699 * a = "my string"
1700 * a.extend(fred) #=> "my string"
1701 * a.meth1 #=> "hello"
1702 * a.meth2 #=> "bye"
1704 * Assign the module to a constant (name starting uppercase) if you
1705 * want to treat it like a regular module.
1708 static VALUE
1709 rb_mod_initialize(VALUE module)
1711 rb_module_check_initializable(module);
1712 return rb_mod_initialize_exec(module);
1715 static VALUE
1716 rb_mod_initialize_exec(VALUE module)
1718 if (rb_block_given_p()) {
1719 rb_mod_module_exec(1, &module, module);
1721 return Qnil;
1724 /* :nodoc: */
1725 static VALUE
1726 rb_mod_initialize_clone(int argc, VALUE* argv, VALUE clone)
1728 VALUE ret, orig, opts;
1729 rb_scan_args(argc, argv, "1:", &orig, &opts);
1730 ret = rb_obj_init_clone(argc, argv, clone);
1731 if (OBJ_FROZEN(orig))
1732 rb_class_name(clone);
1733 return ret;
1737 * call-seq:
1738 * Class.new(super_class=Object) -> a_class
1739 * Class.new(super_class=Object) { |mod| ... } -> a_class
1741 * Creates a new anonymous (unnamed) class with the given superclass
1742 * (or Object if no parameter is given). You can give a
1743 * class a name by assigning the class object to a constant.
1745 * If a block is given, it is passed the class object, and the block
1746 * is evaluated in the context of this class like
1747 * #class_eval.
1749 * fred = Class.new do
1750 * def meth1
1751 * "hello"
1752 * end
1753 * def meth2
1754 * "bye"
1755 * end
1756 * end
1758 * a = fred.new #=> #<#<Class:0x100381890>:0x100376b98>
1759 * a.meth1 #=> "hello"
1760 * a.meth2 #=> "bye"
1762 * Assign the class to a constant (name starting uppercase) if you
1763 * want to treat it like a regular class.
1766 static VALUE
1767 rb_class_initialize(int argc, VALUE *argv, VALUE klass)
1769 VALUE super;
1771 if (RCLASS_SUPER(klass) != 0 || klass == rb_cBasicObject) {
1772 rb_raise(rb_eTypeError, "already initialized class");
1774 if (rb_check_arity(argc, 0, 1) == 0) {
1775 super = rb_cObject;
1777 else {
1778 super = argv[0];
1779 rb_check_inheritable(super);
1780 if (super != rb_cBasicObject && !RCLASS_SUPER(super)) {
1781 rb_raise(rb_eTypeError, "can't inherit uninitialized class");
1784 RCLASS_SET_SUPER(klass, super);
1785 rb_make_metaclass(klass, RBASIC(super)->klass);
1786 rb_class_inherited(super, klass);
1787 rb_mod_initialize_exec(klass);
1789 return klass;
1792 /*! \private */
1793 void
1794 rb_undefined_alloc(VALUE klass)
1796 rb_raise(rb_eTypeError, "allocator undefined for %"PRIsVALUE,
1797 klass);
1800 static rb_alloc_func_t class_get_alloc_func(VALUE klass);
1801 static VALUE class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass);
1804 * call-seq:
1805 * class.allocate() -> obj
1807 * Allocates space for a new object of <i>class</i>'s class and does not
1808 * call initialize on the new instance. The returned object must be an
1809 * instance of <i>class</i>.
1811 * klass = Class.new do
1812 * def initialize(*args)
1813 * @initialized = true
1814 * end
1816 * def initialized?
1817 * @initialized || false
1818 * end
1819 * end
1821 * klass.allocate.initialized? #=> false
1825 static VALUE
1826 rb_class_alloc_m(VALUE klass)
1828 rb_alloc_func_t allocator = class_get_alloc_func(klass);
1829 if (!rb_obj_respond_to(klass, rb_intern("allocate"), 1)) {
1830 rb_raise(rb_eTypeError, "calling %"PRIsVALUE".allocate is prohibited",
1831 klass);
1833 return class_call_alloc_func(allocator, klass);
1836 static VALUE
1837 rb_class_alloc(VALUE klass)
1839 rb_alloc_func_t allocator = class_get_alloc_func(klass);
1840 return class_call_alloc_func(allocator, klass);
1843 static rb_alloc_func_t
1844 class_get_alloc_func(VALUE klass)
1846 rb_alloc_func_t allocator;
1848 if (RCLASS_SUPER(klass) == 0 && klass != rb_cBasicObject) {
1849 rb_raise(rb_eTypeError, "can't instantiate uninitialized class");
1851 if (FL_TEST(klass, FL_SINGLETON)) {
1852 rb_raise(rb_eTypeError, "can't create instance of singleton class");
1854 allocator = rb_get_alloc_func(klass);
1855 if (!allocator) {
1856 rb_undefined_alloc(klass);
1858 return allocator;
1861 static VALUE
1862 class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass)
1864 VALUE obj;
1866 RUBY_DTRACE_CREATE_HOOK(OBJECT, rb_class2name(klass));
1868 obj = (*allocator)(klass);
1870 if (rb_obj_class(obj) != rb_class_real(klass)) {
1871 rb_raise(rb_eTypeError, "wrong instance allocation");
1873 return obj;
1876 VALUE
1877 rb_obj_alloc(VALUE klass)
1879 Check_Type(klass, T_CLASS);
1880 return rb_class_alloc(klass);
1884 * call-seq:
1885 * class.new(args, ...) -> obj
1887 * Calls #allocate to create a new object of <i>class</i>'s class,
1888 * then invokes that object's #initialize method, passing it
1889 * <i>args</i>. This is the method that ends up getting called
1890 * whenever an object is constructed using <code>.new</code>.
1894 VALUE
1895 rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass)
1897 VALUE obj;
1899 obj = rb_class_alloc(klass);
1900 rb_obj_call_init_kw(obj, argc, argv, RB_PASS_CALLED_KEYWORDS);
1902 return obj;
1905 VALUE
1906 rb_class_new_instance_kw(int argc, const VALUE *argv, VALUE klass, int kw_splat)
1908 VALUE obj;
1909 Check_Type(klass, T_CLASS);
1911 obj = rb_class_alloc(klass);
1912 rb_obj_call_init_kw(obj, argc, argv, kw_splat);
1914 return obj;
1917 VALUE
1918 rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
1920 VALUE obj;
1921 Check_Type(klass, T_CLASS);
1923 obj = rb_class_alloc(klass);
1924 rb_obj_call_init_kw(obj, argc, argv, RB_NO_KEYWORDS);
1926 return obj;
1930 * call-seq:
1931 * class.superclass -> a_super_class or nil
1933 * Returns the superclass of <i>class</i>, or <code>nil</code>.
1935 * File.superclass #=> IO
1936 * IO.superclass #=> Object
1937 * Object.superclass #=> BasicObject
1938 * class Foo; end
1939 * class Bar < Foo; end
1940 * Bar.superclass #=> Foo
1942 * Returns nil when the given class does not have a parent class:
1944 * BasicObject.superclass #=> nil
1947 * Returns the superclass of \a klass. Equivalent to \c Class\#superclass in Ruby.
1949 * It skips modules.
1950 * \param[in] klass a Class object
1951 * \return the superclass, or \c Qnil if \a klass does not have a parent class.
1952 * \sa rb_class_get_superclass
1956 VALUE
1957 rb_class_superclass(VALUE klass)
1959 VALUE super = RCLASS_SUPER(klass);
1961 if (!super) {
1962 if (klass == rb_cBasicObject) return Qnil;
1963 rb_raise(rb_eTypeError, "uninitialized class");
1965 while (RB_TYPE_P(super, T_ICLASS)) {
1966 super = RCLASS_SUPER(super);
1968 if (!super) {
1969 return Qnil;
1971 return super;
1974 VALUE
1975 rb_class_get_superclass(VALUE klass)
1977 return RCLASS(klass)->super;
1980 static const char bad_instance_name[] = "`%1$s' is not allowed as an instance variable name";
1981 static const char bad_class_name[] = "`%1$s' is not allowed as a class variable name";
1982 static const char bad_const_name[] = "wrong constant name %1$s";
1983 static const char bad_attr_name[] = "invalid attribute name `%1$s'";
1984 #define wrong_constant_name bad_const_name
1986 /*! \private */
1987 #define id_for_var(obj, name, type) id_for_setter(obj, name, type, bad_##type##_name)
1988 /*! \private */
1989 #define id_for_setter(obj, name, type, message) \
1990 check_setter_id(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message))
1991 static ID
1992 check_setter_id(VALUE obj, VALUE *pname,
1993 int (*valid_id_p)(ID), int (*valid_name_p)(VALUE),
1994 const char *message, size_t message_len)
1996 ID id = rb_check_id(pname);
1997 VALUE name = *pname;
1999 if (id ? !valid_id_p(id) : !valid_name_p(name)) {
2000 rb_name_err_raise_str(rb_fstring_new(message, message_len),
2001 obj, name);
2003 return id;
2006 static int
2007 rb_is_attr_name(VALUE name)
2009 return rb_is_local_name(name) || rb_is_const_name(name);
2012 static int
2013 rb_is_attr_id(ID id)
2015 return rb_is_local_id(id) || rb_is_const_id(id);
2018 static ID
2019 id_for_attr(VALUE obj, VALUE name)
2021 ID id = id_for_var(obj, name, attr);
2022 if (!id) id = rb_intern_str(name);
2023 return id;
2027 * call-seq:
2028 * attr_reader(symbol, ...) -> array
2029 * attr(symbol, ...) -> array
2030 * attr_reader(string, ...) -> array
2031 * attr(string, ...) -> array
2033 * Creates instance variables and corresponding methods that return the
2034 * value of each instance variable. Equivalent to calling
2035 * ``<code>attr</code><i>:name</i>'' on each name in turn.
2036 * String arguments are converted to symbols.
2037 * Returns an array of defined method names as symbols.
2040 static VALUE
2041 rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass)
2043 int i;
2044 VALUE names = rb_ary_new2(argc);
2046 for (i=0; i<argc; i++) {
2047 ID id = id_for_attr(klass, argv[i]);
2048 rb_attr(klass, id, TRUE, FALSE, TRUE);
2049 rb_ary_push(names, ID2SYM(id));
2051 return names;
2055 * call-seq:
2056 * attr(name, ...) -> array
2057 * attr(name, true) -> array
2058 * attr(name, false) -> array
2060 * The first form is equivalent to #attr_reader.
2061 * The second form is equivalent to <code>attr_accessor(name)</code> but deprecated.
2062 * The last form is equivalent to <code>attr_reader(name)</code> but deprecated.
2063 * Returns an array of defined method names as symbols.
2065 * \private
2066 * \todo can be static?
2069 VALUE
2070 rb_mod_attr(int argc, VALUE *argv, VALUE klass)
2072 if (argc == 2 && (argv[1] == Qtrue || argv[1] == Qfalse)) {
2073 ID id = id_for_attr(klass, argv[0]);
2074 VALUE names = rb_ary_new();
2076 rb_category_warning(RB_WARN_CATEGORY_DEPRECATED, "optional boolean argument is obsoleted");
2077 rb_attr(klass, id, 1, RTEST(argv[1]), TRUE);
2078 rb_ary_push(names, ID2SYM(id));
2079 if (argv[1] == Qtrue) rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2080 return names;
2082 return rb_mod_attr_reader(argc, argv, klass);
2086 * call-seq:
2087 * attr_writer(symbol, ...) -> array
2088 * attr_writer(string, ...) -> array
2090 * Creates an accessor method to allow assignment to the attribute
2091 * <i>symbol</i><code>.id2name</code>.
2092 * String arguments are converted to symbols.
2093 * Returns an array of defined method names as symbols.
2096 static VALUE
2097 rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass)
2099 int i;
2100 VALUE names = rb_ary_new2(argc);
2102 for (i=0; i<argc; i++) {
2103 ID id = id_for_attr(klass, argv[i]);
2104 rb_attr(klass, id, FALSE, TRUE, TRUE);
2105 rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2107 return names;
2111 * call-seq:
2112 * attr_accessor(symbol, ...) -> array
2113 * attr_accessor(string, ...) -> array
2115 * Defines a named attribute for this module, where the name is
2116 * <i>symbol.</i><code>id2name</code>, creating an instance variable
2117 * (<code>@name</code>) and a corresponding access method to read it.
2118 * Also creates a method called <code>name=</code> to set the attribute.
2119 * String arguments are converted to symbols.
2120 * Returns an array of defined method names as symbols.
2122 * module Mod
2123 * attr_accessor(:one, :two) #=> [:one, :one=, :two, :two=]
2124 * end
2125 * Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
2128 static VALUE
2129 rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass)
2131 int i;
2132 VALUE names = rb_ary_new2(argc * 2);
2134 for (i=0; i<argc; i++) {
2135 ID id = id_for_attr(klass, argv[i]);
2137 rb_attr(klass, id, TRUE, TRUE, TRUE);
2138 rb_ary_push(names, ID2SYM(id));
2139 rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2141 return names;
2145 * call-seq:
2146 * mod.const_get(sym, inherit=true) -> obj
2147 * mod.const_get(str, inherit=true) -> obj
2149 * Checks for a constant with the given name in <i>mod</i>.
2150 * If +inherit+ is set, the lookup will also search
2151 * the ancestors (and +Object+ if <i>mod</i> is a +Module+).
2153 * The value of the constant is returned if a definition is found,
2154 * otherwise a +NameError+ is raised.
2156 * Math.const_get(:PI) #=> 3.14159265358979
2158 * This method will recursively look up constant names if a namespaced
2159 * class name is provided. For example:
2161 * module Foo; class Bar; end end
2162 * Object.const_get 'Foo::Bar'
2164 * The +inherit+ flag is respected on each lookup. For example:
2166 * module Foo
2167 * class Bar
2168 * VAL = 10
2169 * end
2171 * class Baz < Bar; end
2172 * end
2174 * Object.const_get 'Foo::Baz::VAL' # => 10
2175 * Object.const_get 'Foo::Baz::VAL', false # => NameError
2177 * If the argument is not a valid constant name a +NameError+ will be
2178 * raised with a warning "wrong constant name".
2180 * Object.const_get 'foobar' #=> NameError: wrong constant name foobar
2184 static VALUE
2185 rb_mod_const_get(int argc, VALUE *argv, VALUE mod)
2187 VALUE name, recur;
2188 rb_encoding *enc;
2189 const char *pbeg, *p, *path, *pend;
2190 ID id;
2192 rb_check_arity(argc, 1, 2);
2193 name = argv[0];
2194 recur = (argc == 1) ? Qtrue : argv[1];
2196 if (SYMBOL_P(name)) {
2197 if (!rb_is_const_sym(name)) goto wrong_name;
2198 id = rb_check_id(&name);
2199 if (!id) return rb_const_missing(mod, name);
2200 return RTEST(recur) ? rb_const_get(mod, id) : rb_const_get_at(mod, id);
2203 path = StringValuePtr(name);
2204 enc = rb_enc_get(name);
2206 if (!rb_enc_asciicompat(enc)) {
2207 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2210 pbeg = p = path;
2211 pend = path + RSTRING_LEN(name);
2213 if (p >= pend || !*p) {
2214 goto wrong_name;
2217 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2218 mod = rb_cObject;
2219 p += 2;
2220 pbeg = p;
2223 while (p < pend) {
2224 VALUE part;
2225 long len, beglen;
2227 while (p < pend && *p != ':') p++;
2229 if (pbeg == p) goto wrong_name;
2231 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2232 beglen = pbeg-path;
2234 if (p < pend && p[0] == ':') {
2235 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2236 p += 2;
2237 pbeg = p;
2240 if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2241 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2242 QUOTE(name));
2245 if (!id) {
2246 part = rb_str_subseq(name, beglen, len);
2247 OBJ_FREEZE(part);
2248 if (!rb_is_const_name(part)) {
2249 name = part;
2250 goto wrong_name;
2252 else if (!rb_method_basic_definition_p(CLASS_OF(mod), id_const_missing)) {
2253 part = rb_str_intern(part);
2254 mod = rb_const_missing(mod, part);
2255 continue;
2257 else {
2258 rb_mod_const_missing(mod, part);
2261 if (!rb_is_const_id(id)) {
2262 name = ID2SYM(id);
2263 goto wrong_name;
2265 #if 0
2266 mod = rb_const_get_0(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2267 #else
2268 if (!RTEST(recur)) {
2269 mod = rb_const_get_at(mod, id);
2271 else if (beglen == 0) {
2272 mod = rb_const_get(mod, id);
2274 else {
2275 mod = rb_const_get_from(mod, id);
2277 #endif
2280 return mod;
2282 wrong_name:
2283 rb_name_err_raise(wrong_constant_name, mod, name);
2284 UNREACHABLE_RETURN(Qundef);
2288 * call-seq:
2289 * mod.const_set(sym, obj) -> obj
2290 * mod.const_set(str, obj) -> obj
2292 * Sets the named constant to the given object, returning that object.
2293 * Creates a new constant if no constant with the given name previously
2294 * existed.
2296 * Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714
2297 * Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968
2299 * If +sym+ or +str+ is not a valid constant name a +NameError+ will be
2300 * raised with a warning "wrong constant name".
2302 * Object.const_set('foobar', 42) #=> NameError: wrong constant name foobar
2306 static VALUE
2307 rb_mod_const_set(VALUE mod, VALUE name, VALUE value)
2309 ID id = id_for_var(mod, name, const);
2310 if (!id) id = rb_intern_str(name);
2311 rb_const_set(mod, id, value);
2313 return value;
2317 * call-seq:
2318 * mod.const_defined?(sym, inherit=true) -> true or false
2319 * mod.const_defined?(str, inherit=true) -> true or false
2321 * Says whether _mod_ or its ancestors have a constant with the given name:
2323 * Float.const_defined?(:EPSILON) #=> true, found in Float itself
2324 * Float.const_defined?("String") #=> true, found in Object (ancestor)
2325 * BasicObject.const_defined?(:Hash) #=> false
2327 * If _mod_ is a +Module+, additionally +Object+ and its ancestors are checked:
2329 * Math.const_defined?(:String) #=> true, found in Object
2331 * In each of the checked classes or modules, if the constant is not present
2332 * but there is an autoload for it, +true+ is returned directly without
2333 * autoloading:
2335 * module Admin
2336 * autoload :User, 'admin/user'
2337 * end
2338 * Admin.const_defined?(:User) #=> true
2340 * If the constant is not found the callback +const_missing+ is *not* called
2341 * and the method returns +false+.
2343 * If +inherit+ is false, the lookup only checks the constants in the receiver:
2345 * IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor)
2346 * IO.const_defined?(:SYNC, false) #=> false, not found in IO itself
2348 * In this case, the same logic for autoloading applies.
2350 * If the argument is not a valid constant name a +NameError+ is raised with the
2351 * message "wrong constant name _name_":
2353 * Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar
2357 static VALUE
2358 rb_mod_const_defined(int argc, VALUE *argv, VALUE mod)
2360 VALUE name, recur;
2361 rb_encoding *enc;
2362 const char *pbeg, *p, *path, *pend;
2363 ID id;
2365 rb_check_arity(argc, 1, 2);
2366 name = argv[0];
2367 recur = (argc == 1) ? Qtrue : argv[1];
2369 if (SYMBOL_P(name)) {
2370 if (!rb_is_const_sym(name)) goto wrong_name;
2371 id = rb_check_id(&name);
2372 if (!id) return Qfalse;
2373 return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id);
2376 path = StringValuePtr(name);
2377 enc = rb_enc_get(name);
2379 if (!rb_enc_asciicompat(enc)) {
2380 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2383 pbeg = p = path;
2384 pend = path + RSTRING_LEN(name);
2386 if (p >= pend || !*p) {
2387 goto wrong_name;
2390 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2391 mod = rb_cObject;
2392 p += 2;
2393 pbeg = p;
2396 while (p < pend) {
2397 VALUE part;
2398 long len, beglen;
2400 while (p < pend && *p != ':') p++;
2402 if (pbeg == p) goto wrong_name;
2404 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2405 beglen = pbeg-path;
2407 if (p < pend && p[0] == ':') {
2408 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2409 p += 2;
2410 pbeg = p;
2413 if (!id) {
2414 part = rb_str_subseq(name, beglen, len);
2415 OBJ_FREEZE(part);
2416 if (!rb_is_const_name(part)) {
2417 name = part;
2418 goto wrong_name;
2420 else {
2421 return Qfalse;
2424 if (!rb_is_const_id(id)) {
2425 name = ID2SYM(id);
2426 goto wrong_name;
2429 #if 0
2430 mod = rb_const_search(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2431 if (mod == Qundef) return Qfalse;
2432 #else
2433 if (!RTEST(recur)) {
2434 if (!rb_const_defined_at(mod, id))
2435 return Qfalse;
2436 if (p == pend) return Qtrue;
2437 mod = rb_const_get_at(mod, id);
2439 else if (beglen == 0) {
2440 if (!rb_const_defined(mod, id))
2441 return Qfalse;
2442 if (p == pend) return Qtrue;
2443 mod = rb_const_get(mod, id);
2445 else {
2446 if (!rb_const_defined_from(mod, id))
2447 return Qfalse;
2448 if (p == pend) return Qtrue;
2449 mod = rb_const_get_from(mod, id);
2451 #endif
2453 if (p < pend && !RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2454 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2455 QUOTE(name));
2459 return Qtrue;
2461 wrong_name:
2462 rb_name_err_raise(wrong_constant_name, mod, name);
2463 UNREACHABLE_RETURN(Qundef);
2467 * call-seq:
2468 * mod.const_source_location(sym, inherit=true) -> [String, Integer]
2469 * mod.const_source_location(str, inherit=true) -> [String, Integer]
2471 * Returns the Ruby source filename and line number containing the definition
2472 * of the constant specified. If the named constant is not found, +nil+ is returned.
2473 * If the constant is found, but its source location can not be extracted
2474 * (constant is defined in C code), empty array is returned.
2476 * _inherit_ specifies whether to lookup in <code>mod.ancestors</code> (+true+
2477 * by default).
2479 * # test.rb:
2480 * class A # line 1
2481 * C1 = 1
2482 * C2 = 2
2483 * end
2485 * module M # line 6
2486 * C3 = 3
2487 * end
2489 * class B < A # line 10
2490 * include M
2491 * C4 = 4
2492 * end
2494 * class A # continuation of A definition
2495 * C2 = 8 # constant redefinition; warned yet allowed
2496 * end
2498 * p B.const_source_location('C4') # => ["test.rb", 12]
2499 * p B.const_source_location('C3') # => ["test.rb", 7]
2500 * p B.const_source_location('C1') # => ["test.rb", 2]
2502 * p B.const_source_location('C3', false) # => nil -- don't lookup in ancestors
2504 * p A.const_source_location('C2') # => ["test.rb", 16] -- actual (last) definition place
2506 * p Object.const_source_location('B') # => ["test.rb", 10] -- top-level constant could be looked through Object
2507 * p Object.const_source_location('A') # => ["test.rb", 1] -- class reopening is NOT considered new definition
2509 * p B.const_source_location('A') # => ["test.rb", 1] -- because Object is in ancestors
2510 * p M.const_source_location('A') # => ["test.rb", 1] -- Object is not ancestor, but additionally checked for modules
2512 * p Object.const_source_location('A::C1') # => ["test.rb", 2] -- nesting is supported
2513 * p Object.const_source_location('String') # => [] -- constant is defined in C code
2517 static VALUE
2518 rb_mod_const_source_location(int argc, VALUE *argv, VALUE mod)
2520 VALUE name, recur, loc = Qnil;
2521 rb_encoding *enc;
2522 const char *pbeg, *p, *path, *pend;
2523 ID id;
2525 rb_check_arity(argc, 1, 2);
2526 name = argv[0];
2527 recur = (argc == 1) ? Qtrue : argv[1];
2529 if (SYMBOL_P(name)) {
2530 if (!rb_is_const_sym(name)) goto wrong_name;
2531 id = rb_check_id(&name);
2532 if (!id) return Qnil;
2533 return RTEST(recur) ? rb_const_source_location(mod, id) : rb_const_source_location_at(mod, id);
2536 path = StringValuePtr(name);
2537 enc = rb_enc_get(name);
2539 if (!rb_enc_asciicompat(enc)) {
2540 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2543 pbeg = p = path;
2544 pend = path + RSTRING_LEN(name);
2546 if (p >= pend || !*p) {
2547 goto wrong_name;
2550 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2551 mod = rb_cObject;
2552 p += 2;
2553 pbeg = p;
2556 while (p < pend) {
2557 VALUE part;
2558 long len, beglen;
2560 while (p < pend && *p != ':') p++;
2562 if (pbeg == p) goto wrong_name;
2564 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2565 beglen = pbeg-path;
2567 if (p < pend && p[0] == ':') {
2568 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2569 p += 2;
2570 pbeg = p;
2573 if (!id) {
2574 part = rb_str_subseq(name, beglen, len);
2575 OBJ_FREEZE(part);
2576 if (!rb_is_const_name(part)) {
2577 name = part;
2578 goto wrong_name;
2580 else {
2581 return Qnil;
2584 if (!rb_is_const_id(id)) {
2585 name = ID2SYM(id);
2586 goto wrong_name;
2588 if (p < pend) {
2589 if (RTEST(recur)) {
2590 mod = rb_const_get(mod, id);
2592 else {
2593 mod = rb_const_get_at(mod, id);
2595 if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2596 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2597 QUOTE(name));
2600 else {
2601 if (RTEST(recur)) {
2602 loc = rb_const_source_location(mod, id);
2604 else {
2605 loc = rb_const_source_location_at(mod, id);
2607 break;
2609 recur = Qfalse;
2612 return loc;
2614 wrong_name:
2615 rb_name_err_raise(wrong_constant_name, mod, name);
2616 UNREACHABLE_RETURN(Qundef);
2620 * call-seq:
2621 * obj.instance_variable_get(symbol) -> obj
2622 * obj.instance_variable_get(string) -> obj
2624 * Returns the value of the given instance variable, or nil if the
2625 * instance variable is not set. The <code>@</code> part of the
2626 * variable name should be included for regular instance
2627 * variables. Throws a NameError exception if the
2628 * supplied symbol is not valid as an instance variable name.
2629 * String arguments are converted to symbols.
2631 * class Fred
2632 * def initialize(p1, p2)
2633 * @a, @b = p1, p2
2634 * end
2635 * end
2636 * fred = Fred.new('cat', 99)
2637 * fred.instance_variable_get(:@a) #=> "cat"
2638 * fred.instance_variable_get("@b") #=> 99
2641 static VALUE
2642 rb_obj_ivar_get(VALUE obj, VALUE iv)
2644 ID id = id_for_var(obj, iv, instance);
2646 if (!id) {
2647 return Qnil;
2649 return rb_ivar_get(obj, id);
2653 * call-seq:
2654 * obj.instance_variable_set(symbol, obj) -> obj
2655 * obj.instance_variable_set(string, obj) -> obj
2657 * Sets the instance variable named by <i>symbol</i> to the given
2658 * object. This may circumvent the encapsulation intended by
2659 * the author of the class, so it should be used with care.
2660 * The variable does not have to exist prior to this call.
2661 * If the instance variable name is passed as a string, that string
2662 * is converted to a symbol.
2664 * class Fred
2665 * def initialize(p1, p2)
2666 * @a, @b = p1, p2
2667 * end
2668 * end
2669 * fred = Fred.new('cat', 99)
2670 * fred.instance_variable_set(:@a, 'dog') #=> "dog"
2671 * fred.instance_variable_set(:@c, 'cat') #=> "cat"
2672 * fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
2675 static VALUE
2676 rb_obj_ivar_set(VALUE obj, VALUE iv, VALUE val)
2678 ID id = id_for_var(obj, iv, instance);
2679 if (!id) id = rb_intern_str(iv);
2680 return rb_ivar_set(obj, id, val);
2684 * call-seq:
2685 * obj.instance_variable_defined?(symbol) -> true or false
2686 * obj.instance_variable_defined?(string) -> true or false
2688 * Returns <code>true</code> if the given instance variable is
2689 * defined in <i>obj</i>.
2690 * String arguments are converted to symbols.
2692 * class Fred
2693 * def initialize(p1, p2)
2694 * @a, @b = p1, p2
2695 * end
2696 * end
2697 * fred = Fred.new('cat', 99)
2698 * fred.instance_variable_defined?(:@a) #=> true
2699 * fred.instance_variable_defined?("@b") #=> true
2700 * fred.instance_variable_defined?("@c") #=> false
2703 static VALUE
2704 rb_obj_ivar_defined(VALUE obj, VALUE iv)
2706 ID id = id_for_var(obj, iv, instance);
2708 if (!id) {
2709 return Qfalse;
2711 return rb_ivar_defined(obj, id);
2715 * call-seq:
2716 * mod.class_variable_get(symbol) -> obj
2717 * mod.class_variable_get(string) -> obj
2719 * Returns the value of the given class variable (or throws a
2720 * NameError exception). The <code>@@</code> part of the
2721 * variable name should be included for regular class variables.
2722 * String arguments are converted to symbols.
2724 * class Fred
2725 * @@foo = 99
2726 * end
2727 * Fred.class_variable_get(:@@foo) #=> 99
2730 static VALUE
2731 rb_mod_cvar_get(VALUE obj, VALUE iv)
2733 ID id = id_for_var(obj, iv, class);
2735 if (!id) {
2736 rb_name_err_raise("uninitialized class variable %1$s in %2$s",
2737 obj, iv);
2739 return rb_cvar_get(obj, id);
2743 * call-seq:
2744 * obj.class_variable_set(symbol, obj) -> obj
2745 * obj.class_variable_set(string, obj) -> obj
2747 * Sets the class variable named by <i>symbol</i> to the given
2748 * object.
2749 * If the class variable name is passed as a string, that string
2750 * is converted to a symbol.
2752 * class Fred
2753 * @@foo = 99
2754 * def foo
2755 * @@foo
2756 * end
2757 * end
2758 * Fred.class_variable_set(:@@foo, 101) #=> 101
2759 * Fred.new.foo #=> 101
2762 static VALUE
2763 rb_mod_cvar_set(VALUE obj, VALUE iv, VALUE val)
2765 ID id = id_for_var(obj, iv, class);
2766 if (!id) id = rb_intern_str(iv);
2767 rb_cvar_set(obj, id, val);
2768 return val;
2772 * call-seq:
2773 * obj.class_variable_defined?(symbol) -> true or false
2774 * obj.class_variable_defined?(string) -> true or false
2776 * Returns <code>true</code> if the given class variable is defined
2777 * in <i>obj</i>.
2778 * String arguments are converted to symbols.
2780 * class Fred
2781 * @@foo = 99
2782 * end
2783 * Fred.class_variable_defined?(:@@foo) #=> true
2784 * Fred.class_variable_defined?(:@@bar) #=> false
2787 static VALUE
2788 rb_mod_cvar_defined(VALUE obj, VALUE iv)
2790 ID id = id_for_var(obj, iv, class);
2792 if (!id) {
2793 return Qfalse;
2795 return rb_cvar_defined(obj, id);
2799 * call-seq:
2800 * mod.singleton_class? -> true or false
2802 * Returns <code>true</code> if <i>mod</i> is a singleton class or
2803 * <code>false</code> if it is an ordinary class or module.
2805 * class C
2806 * end
2807 * C.singleton_class? #=> false
2808 * C.singleton_class.singleton_class? #=> true
2811 static VALUE
2812 rb_mod_singleton_p(VALUE klass)
2814 return RBOOL(RB_TYPE_P(klass, T_CLASS) && FL_TEST(klass, FL_SINGLETON));
2817 /*! \private */
2818 static const struct conv_method_tbl {
2819 const char method[6];
2820 unsigned short id;
2821 } conv_method_names[] = {
2822 #define M(n) {#n, (unsigned short)idTo_##n}
2823 M(int),
2824 M(ary),
2825 M(str),
2826 M(sym),
2827 M(hash),
2828 M(proc),
2829 M(io),
2830 M(a),
2831 M(s),
2832 M(i),
2833 M(f),
2834 M(r),
2835 #undef M
2837 #define IMPLICIT_CONVERSIONS 7
2839 static int
2840 conv_method_index(const char *method)
2842 static const char prefix[] = "to_";
2844 if (strncmp(prefix, method, sizeof(prefix)-1) == 0) {
2845 const char *const meth = &method[sizeof(prefix)-1];
2846 int i;
2847 for (i=0; i < numberof(conv_method_names); i++) {
2848 if (conv_method_names[i].method[0] == meth[0] &&
2849 strcmp(conv_method_names[i].method, meth) == 0) {
2850 return i;
2854 return numberof(conv_method_names);
2857 static VALUE
2858 convert_type_with_id(VALUE val, const char *tname, ID method, int raise, int index)
2860 VALUE r = rb_check_funcall(val, method, 0, 0);
2861 if (r == Qundef) {
2862 if (raise) {
2863 const char *msg =
2864 ((index < 0 ? conv_method_index(rb_id2name(method)) : index)
2865 < IMPLICIT_CONVERSIONS) ?
2866 "no implicit conversion of" : "can't convert";
2867 const char *cname = NIL_P(val) ? "nil" :
2868 val == Qtrue ? "true" :
2869 val == Qfalse ? "false" :
2870 NULL;
2871 if (cname)
2872 rb_raise(rb_eTypeError, "%s %s into %s", msg, cname, tname);
2873 rb_raise(rb_eTypeError, "%s %"PRIsVALUE" into %s", msg,
2874 rb_obj_class(val),
2875 tname);
2877 return Qnil;
2879 return r;
2882 static VALUE
2883 convert_type(VALUE val, const char *tname, const char *method, int raise)
2885 int i = conv_method_index(method);
2886 ID m = i < numberof(conv_method_names) ?
2887 conv_method_names[i].id : rb_intern(method);
2888 return convert_type_with_id(val, tname, m, raise, i);
2891 /*! \private */
2892 NORETURN(static void conversion_mismatch(VALUE, const char *, const char *, VALUE));
2893 static void
2894 conversion_mismatch(VALUE val, const char *tname, const char *method, VALUE result)
2896 VALUE cname = rb_obj_class(val);
2897 rb_raise(rb_eTypeError,
2898 "can't convert %"PRIsVALUE" to %s (%"PRIsVALUE"#%s gives %"PRIsVALUE")",
2899 cname, tname, cname, method, rb_obj_class(result));
2902 VALUE
2903 rb_convert_type(VALUE val, int type, const char *tname, const char *method)
2905 VALUE v;
2907 if (TYPE(val) == type) return val;
2908 v = convert_type(val, tname, method, TRUE);
2909 if (TYPE(v) != type) {
2910 conversion_mismatch(val, tname, method, v);
2912 return v;
2915 /*! \private */
2916 VALUE
2917 rb_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
2919 VALUE v;
2921 if (TYPE(val) == type) return val;
2922 v = convert_type_with_id(val, tname, method, TRUE, -1);
2923 if (TYPE(v) != type) {
2924 conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v);
2926 return v;
2929 VALUE
2930 rb_check_convert_type(VALUE val, int type, const char *tname, const char *method)
2932 VALUE v;
2934 /* always convert T_DATA */
2935 if (TYPE(val) == type && type != T_DATA) return val;
2936 v = convert_type(val, tname, method, FALSE);
2937 if (NIL_P(v)) return Qnil;
2938 if (TYPE(v) != type) {
2939 conversion_mismatch(val, tname, method, v);
2941 return v;
2944 /*! \private */
2945 MJIT_FUNC_EXPORTED VALUE
2946 rb_check_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
2948 VALUE v;
2950 /* always convert T_DATA */
2951 if (TYPE(val) == type && type != T_DATA) return val;
2952 v = convert_type_with_id(val, tname, method, FALSE, -1);
2953 if (NIL_P(v)) return Qnil;
2954 if (TYPE(v) != type) {
2955 conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v);
2957 return v;
2960 #define try_to_int(val, mid, raise) \
2961 convert_type_with_id(val, "Integer", mid, raise, -1)
2963 ALWAYS_INLINE(static VALUE rb_to_integer_with_id_exception(VALUE val, const char *method, ID mid, int raise));
2964 /* Integer specific rb_check_convert_type_with_id */
2965 static inline VALUE
2966 rb_to_integer_with_id_exception(VALUE val, const char *method, ID mid, int raise)
2968 VALUE v;
2970 if (RB_INTEGER_TYPE_P(val)) return val;
2971 v = try_to_int(val, mid, raise);
2972 if (!raise && NIL_P(v)) return Qnil;
2973 if (!RB_INTEGER_TYPE_P(v)) {
2974 conversion_mismatch(val, "Integer", method, v);
2976 return v;
2978 #define rb_to_integer(val, method, mid) \
2979 rb_to_integer_with_id_exception(val, method, mid, TRUE)
2981 VALUE
2982 rb_check_to_integer(VALUE val, const char *method)
2984 VALUE v;
2986 if (RB_INTEGER_TYPE_P(val)) return val;
2987 v = convert_type(val, "Integer", method, FALSE);
2988 if (!RB_INTEGER_TYPE_P(v)) {
2989 return Qnil;
2991 return v;
2994 VALUE
2995 rb_to_int(VALUE val)
2997 return rb_to_integer(val, "to_int", idTo_int);
3000 VALUE
3001 rb_check_to_int(VALUE val)
3003 if (RB_INTEGER_TYPE_P(val)) return val;
3004 val = try_to_int(val, idTo_int, FALSE);
3005 if (RB_INTEGER_TYPE_P(val)) return val;
3006 return Qnil;
3009 static VALUE
3010 rb_check_to_i(VALUE val)
3012 if (RB_INTEGER_TYPE_P(val)) return val;
3013 val = try_to_int(val, idTo_i, FALSE);
3014 if (RB_INTEGER_TYPE_P(val)) return val;
3015 return Qnil;
3018 static VALUE
3019 rb_convert_to_integer(VALUE val, int base, int raise_exception)
3021 VALUE tmp;
3023 if (base) {
3024 tmp = rb_check_string_type(val);
3026 if (! NIL_P(tmp)) {
3027 val = tmp;
3029 else if (! raise_exception) {
3030 return Qnil;
3032 else {
3033 rb_raise(rb_eArgError, "base specified for non string value");
3036 if (RB_FLOAT_TYPE_P(val)) {
3037 double f = RFLOAT_VALUE(val);
3038 if (!raise_exception && !isfinite(f)) return Qnil;
3039 if (FIXABLE(f)) return LONG2FIX((long)f);
3040 return rb_dbl2big(f);
3042 else if (RB_INTEGER_TYPE_P(val)) {
3043 return val;
3045 else if (RB_TYPE_P(val, T_STRING)) {
3046 return rb_str_convert_to_inum(val, base, TRUE, raise_exception);
3048 else if (NIL_P(val)) {
3049 if (!raise_exception) return Qnil;
3050 rb_raise(rb_eTypeError, "can't convert nil into Integer");
3053 tmp = rb_protect(rb_check_to_int, val, NULL);
3054 if (RB_INTEGER_TYPE_P(tmp)) return tmp;
3055 rb_set_errinfo(Qnil);
3057 if (!raise_exception) {
3058 VALUE result = rb_protect(rb_check_to_i, val, NULL);
3059 rb_set_errinfo(Qnil);
3060 return result;
3063 return rb_to_integer(val, "to_i", idTo_i);
3066 VALUE
3067 rb_Integer(VALUE val)
3069 return rb_convert_to_integer(val, 0, TRUE);
3072 VALUE
3073 rb_check_integer_type(VALUE val)
3075 return rb_to_integer_with_id_exception(val, "to_int", idTo_int, FALSE);
3079 rb_bool_expected(VALUE obj, const char *flagname)
3081 switch (obj) {
3082 case Qtrue: case Qfalse:
3083 break;
3084 default:
3085 rb_raise(rb_eArgError, "expected true or false as %s: %+"PRIsVALUE,
3086 flagname, obj);
3088 return obj != Qfalse;
3092 rb_opts_exception_p(VALUE opts, int default_value)
3094 static const ID kwds[1] = {idException};
3095 VALUE exception;
3096 if (rb_get_kwargs(opts, kwds, 0, 1, &exception))
3097 return rb_bool_expected(exception, "exception");
3098 return default_value;
3101 #define opts_exception_p(opts) rb_opts_exception_p((opts), TRUE)
3104 * call-seq:
3105 * Integer(arg, base=0, exception: true) -> integer or nil
3107 * Converts <i>arg</i> to an Integer.
3108 * Numeric types are converted directly (with floating point numbers
3109 * being truncated). <i>base</i> (0, or between 2 and 36) is a base for
3110 * integer string representation. If <i>arg</i> is a String,
3111 * when <i>base</i> is omitted or equals zero, radix indicators
3112 * (<code>0</code>, <code>0b</code>, and <code>0x</code>) are honored.
3113 * In any case, strings should consist only of one or more digits, except
3114 * for that a sign, one underscore between two digits, and leading/trailing
3115 * spaces are optional. This behavior is different from that of
3116 * String#to_i. Non string values will be converted by first
3117 * trying <code>to_int</code>, then <code>to_i</code>.
3119 * Passing <code>nil</code> raises a TypeError, while passing a String that
3120 * does not conform with numeric representation raises an ArgumentError.
3121 * This behavior can be altered by passing <code>exception: false</code>,
3122 * in this case a not convertible value will return <code>nil</code>.
3124 * Integer(123.999) #=> 123
3125 * Integer("0x1a") #=> 26
3126 * Integer(Time.new) #=> 1204973019
3127 * Integer("0930", 10) #=> 930
3128 * Integer("111", 2) #=> 7
3129 * Integer(" +1_0 ") #=> 10
3130 * Integer(nil) #=> TypeError: can't convert nil into Integer
3131 * Integer("x") #=> ArgumentError: invalid value for Integer(): "x"
3133 * Integer("x", exception: false) #=> nil
3137 static VALUE
3138 rb_f_integer(int argc, VALUE *argv, VALUE obj)
3140 VALUE arg = Qnil, opts = Qnil;
3141 int base = 0;
3143 if (argc > 1) {
3144 int narg = 1;
3145 VALUE vbase = rb_check_to_int(argv[1]);
3146 if (!NIL_P(vbase)) {
3147 base = NUM2INT(vbase);
3148 narg = 2;
3150 if (argc > narg) {
3151 VALUE hash = rb_check_hash_type(argv[argc-1]);
3152 if (!NIL_P(hash)) {
3153 opts = rb_extract_keywords(&hash);
3154 if (!hash) --argc;
3158 rb_check_arity(argc, 1, 2);
3159 arg = argv[0];
3161 return rb_convert_to_integer(arg, base, opts_exception_p(opts));
3164 static double
3165 rb_cstr_to_dbl_raise(const char *p, int badcheck, int raise, int *error)
3167 const char *q;
3168 char *end;
3169 double d;
3170 const char *ellipsis = "";
3171 int w;
3172 enum {max_width = 20};
3173 #define OutOfRange() ((end - p > max_width) ? \
3174 (w = max_width, ellipsis = "...") : \
3175 (w = (int)(end - p), ellipsis = ""))
3177 if (!p) return 0.0;
3178 q = p;
3179 while (ISSPACE(*p)) p++;
3181 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3182 return 0.0;
3185 d = strtod(p, &end);
3186 if (errno == ERANGE) {
3187 OutOfRange();
3188 rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3189 errno = 0;
3191 if (p == end) {
3192 if (badcheck) {
3193 goto bad;
3195 return d;
3197 if (*end) {
3198 char buf[DBL_DIG * 4 + 10];
3199 char *n = buf;
3200 char *const init_e = buf + DBL_DIG * 4;
3201 char *e = init_e;
3202 char prev = 0;
3203 int dot_seen = FALSE;
3205 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3206 if (*p == '0') {
3207 prev = *n++ = '0';
3208 while (*++p == '0');
3210 while (p < end && n < e) prev = *n++ = *p++;
3211 while (*p) {
3212 if (*p == '_') {
3213 /* remove an underscore between digits */
3214 if (n == buf || !ISDIGIT(prev) || (++p, !ISDIGIT(*p))) {
3215 if (badcheck) goto bad;
3216 break;
3219 prev = *p++;
3220 if (e == init_e && (prev == 'e' || prev == 'E' || prev == 'p' || prev == 'P')) {
3221 e = buf + sizeof(buf) - 1;
3222 *n++ = prev;
3223 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3224 if (*p == '0') {
3225 prev = *n++ = '0';
3226 while (*++p == '0');
3228 continue;
3230 else if (ISSPACE(prev)) {
3231 while (ISSPACE(*p)) ++p;
3232 if (*p) {
3233 if (badcheck) goto bad;
3234 break;
3237 else if (prev == '.' ? dot_seen++ : !ISDIGIT(prev)) {
3238 if (badcheck) goto bad;
3239 break;
3241 if (n < e) *n++ = prev;
3243 *n = '\0';
3244 p = buf;
3246 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3247 return 0.0;
3250 d = strtod(p, &end);
3251 if (errno == ERANGE) {
3252 OutOfRange();
3253 rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3254 errno = 0;
3256 if (badcheck) {
3257 if (!end || p == end) goto bad;
3258 while (*end && ISSPACE(*end)) end++;
3259 if (*end) goto bad;
3262 if (errno == ERANGE) {
3263 errno = 0;
3264 OutOfRange();
3265 rb_raise(rb_eArgError, "Float %.*s%s out of range", w, q, ellipsis);
3267 return d;
3269 bad:
3270 if (raise) {
3271 rb_invalid_str(q, "Float()");
3272 UNREACHABLE_RETURN(nan(""));
3274 else {
3275 if (error) *error = 1;
3276 return 0.0;
3280 double
3281 rb_cstr_to_dbl(const char *p, int badcheck)
3283 return rb_cstr_to_dbl_raise(p, badcheck, TRUE, NULL);
3286 static double
3287 rb_str_to_dbl_raise(VALUE str, int badcheck, int raise, int *error)
3289 char *s;
3290 long len;
3291 double ret;
3292 VALUE v = 0;
3294 StringValue(str);
3295 s = RSTRING_PTR(str);
3296 len = RSTRING_LEN(str);
3297 if (s) {
3298 if (badcheck && memchr(s, '\0', len)) {
3299 if (raise)
3300 rb_raise(rb_eArgError, "string for Float contains null byte");
3301 else {
3302 if (error) *error = 1;
3303 return 0.0;
3306 if (s[len]) { /* no sentinel somehow */
3307 char *p = ALLOCV(v, (size_t)len + 1);
3308 MEMCPY(p, s, char, len);
3309 p[len] = '\0';
3310 s = p;
3313 ret = rb_cstr_to_dbl_raise(s, badcheck, raise, error);
3314 if (v)
3315 ALLOCV_END(v);
3316 return ret;
3319 FUNC_MINIMIZED(double rb_str_to_dbl(VALUE str, int badcheck));
3321 double
3322 rb_str_to_dbl(VALUE str, int badcheck)
3324 return rb_str_to_dbl_raise(str, badcheck, TRUE, NULL);
3327 /*! \cond INTERNAL_MACRO */
3328 #define fix2dbl_without_to_f(x) (double)FIX2LONG(x)
3329 #define big2dbl_without_to_f(x) rb_big2dbl(x)
3330 #define int2dbl_without_to_f(x) \
3331 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : big2dbl_without_to_f(x))
3332 #define num2dbl_without_to_f(x) \
3333 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : \
3334 RB_BIGNUM_TYPE_P(x) ? big2dbl_without_to_f(x) : \
3335 (Check_Type(x, T_FLOAT), RFLOAT_VALUE(x)))
3336 static inline double
3337 rat2dbl_without_to_f(VALUE x)
3339 VALUE num = rb_rational_num(x);
3340 VALUE den = rb_rational_den(x);
3341 return num2dbl_without_to_f(num) / num2dbl_without_to_f(den);
3344 #define special_const_to_float(val, pre, post) \
3345 switch (val) { \
3346 case Qnil: \
3347 rb_raise_static(rb_eTypeError, pre "nil" post); \
3348 case Qtrue: \
3349 rb_raise_static(rb_eTypeError, pre "true" post); \
3350 case Qfalse: \
3351 rb_raise_static(rb_eTypeError, pre "false" post); \
3353 /*! \endcond */
3355 static inline void
3356 conversion_to_float(VALUE val)
3358 special_const_to_float(val, "can't convert ", " into Float");
3361 static inline void
3362 implicit_conversion_to_float(VALUE val)
3364 special_const_to_float(val, "no implicit conversion to float from ", "");
3367 static int
3368 to_float(VALUE *valp, int raise_exception)
3370 VALUE val = *valp;
3371 if (SPECIAL_CONST_P(val)) {
3372 if (FIXNUM_P(val)) {
3373 *valp = DBL2NUM(fix2dbl_without_to_f(val));
3374 return T_FLOAT;
3376 else if (FLONUM_P(val)) {
3377 return T_FLOAT;
3379 else if (raise_exception) {
3380 conversion_to_float(val);
3383 else {
3384 int type = BUILTIN_TYPE(val);
3385 switch (type) {
3386 case T_FLOAT:
3387 return T_FLOAT;
3388 case T_BIGNUM:
3389 *valp = DBL2NUM(big2dbl_without_to_f(val));
3390 return T_FLOAT;
3391 case T_RATIONAL:
3392 *valp = DBL2NUM(rat2dbl_without_to_f(val));
3393 return T_FLOAT;
3394 case T_STRING:
3395 return T_STRING;
3398 return T_NONE;
3401 static VALUE
3402 convert_type_to_float_protected(VALUE val)
3404 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3407 static VALUE
3408 rb_convert_to_float(VALUE val, int raise_exception)
3410 switch (to_float(&val, raise_exception)) {
3411 case T_FLOAT:
3412 return val;
3413 case T_STRING:
3414 if (!raise_exception) {
3415 int e = 0;
3416 double x = rb_str_to_dbl_raise(val, TRUE, raise_exception, &e);
3417 return e ? Qnil : DBL2NUM(x);
3419 return DBL2NUM(rb_str_to_dbl(val, TRUE));
3420 case T_NONE:
3421 if (SPECIAL_CONST_P(val) && !raise_exception)
3422 return Qnil;
3425 if (!raise_exception) {
3426 int state;
3427 VALUE result = rb_protect(convert_type_to_float_protected, val, &state);
3428 if (state) rb_set_errinfo(Qnil);
3429 return result;
3432 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3435 FUNC_MINIMIZED(VALUE rb_Float(VALUE val));
3437 VALUE
3438 rb_Float(VALUE val)
3440 return rb_convert_to_float(val, TRUE);
3443 static VALUE
3444 rb_f_float1(rb_execution_context_t *ec, VALUE obj, VALUE arg)
3446 return rb_convert_to_float(arg, TRUE);
3449 static VALUE
3450 rb_f_float(rb_execution_context_t *ec, VALUE obj, VALUE arg, VALUE opts)
3452 int exception = rb_bool_expected(opts, "exception");
3453 return rb_convert_to_float(arg, exception);
3456 static VALUE
3457 numeric_to_float(VALUE val)
3459 if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3460 rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into Float",
3461 rb_obj_class(val));
3463 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3466 VALUE
3467 rb_to_float(VALUE val)
3469 switch (to_float(&val, TRUE)) {
3470 case T_FLOAT:
3471 return val;
3473 return numeric_to_float(val);
3476 VALUE
3477 rb_check_to_float(VALUE val)
3479 if (RB_FLOAT_TYPE_P(val)) return val;
3480 if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3481 return Qnil;
3483 return rb_check_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3486 static inline int
3487 basic_to_f_p(VALUE klass)
3489 return rb_method_basic_definition_p(klass, id_to_f);
3492 /*! \private */
3493 double
3494 rb_num_to_dbl(VALUE val)
3496 if (SPECIAL_CONST_P(val)) {
3497 if (FIXNUM_P(val)) {
3498 if (basic_to_f_p(rb_cInteger))
3499 return fix2dbl_without_to_f(val);
3501 else if (FLONUM_P(val)) {
3502 return rb_float_flonum_value(val);
3504 else {
3505 conversion_to_float(val);
3508 else {
3509 switch (BUILTIN_TYPE(val)) {
3510 case T_FLOAT:
3511 return rb_float_noflonum_value(val);
3512 case T_BIGNUM:
3513 if (basic_to_f_p(rb_cInteger))
3514 return big2dbl_without_to_f(val);
3515 break;
3516 case T_RATIONAL:
3517 if (basic_to_f_p(rb_cRational))
3518 return rat2dbl_without_to_f(val);
3519 break;
3520 default:
3521 break;
3524 val = numeric_to_float(val);
3525 return RFLOAT_VALUE(val);
3528 double
3529 rb_num2dbl(VALUE val)
3531 if (SPECIAL_CONST_P(val)) {
3532 if (FIXNUM_P(val)) {
3533 return fix2dbl_without_to_f(val);
3535 else if (FLONUM_P(val)) {
3536 return rb_float_flonum_value(val);
3538 else {
3539 implicit_conversion_to_float(val);
3542 else {
3543 switch (BUILTIN_TYPE(val)) {
3544 case T_FLOAT:
3545 return rb_float_noflonum_value(val);
3546 case T_BIGNUM:
3547 return big2dbl_without_to_f(val);
3548 case T_RATIONAL:
3549 return rat2dbl_without_to_f(val);
3550 case T_STRING:
3551 rb_raise(rb_eTypeError, "no implicit conversion to float from string");
3552 default:
3553 break;
3556 val = rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3557 return RFLOAT_VALUE(val);
3560 VALUE
3561 rb_String(VALUE val)
3563 VALUE tmp = rb_check_string_type(val);
3564 if (NIL_P(tmp))
3565 tmp = rb_convert_type_with_id(val, T_STRING, "String", idTo_s);
3566 return tmp;
3571 * call-seq:
3572 * String(arg) -> string
3574 * Returns <i>arg</i> as a String.
3576 * First tries to call its <code>to_str</code> method, then its <code>to_s</code> method.
3578 * String(self) #=> "main"
3579 * String(self.class) #=> "Object"
3580 * String(123456) #=> "123456"
3583 static VALUE
3584 rb_f_string(VALUE obj, VALUE arg)
3586 return rb_String(arg);
3589 VALUE
3590 rb_Array(VALUE val)
3592 VALUE tmp = rb_check_array_type(val);
3594 if (NIL_P(tmp)) {
3595 tmp = rb_check_to_array(val);
3596 if (NIL_P(tmp)) {
3597 return rb_ary_new3(1, val);
3600 return tmp;
3604 * call-seq:
3605 * Array(arg) -> array
3607 * Returns +arg+ as an Array.
3609 * First tries to call <code>to_ary</code> on +arg+, then <code>to_a</code>.
3610 * If +arg+ does not respond to <code>to_ary</code> or <code>to_a</code>,
3611 * returns an Array of length 1 containing +arg+.
3613 * If <code>to_ary</code> or <code>to_a</code> returns something other than
3614 * an Array, raises a TypeError.
3616 * Array(["a", "b"]) #=> ["a", "b"]
3617 * Array(1..5) #=> [1, 2, 3, 4, 5]
3618 * Array(key: :value) #=> [[:key, :value]]
3619 * Array(nil) #=> []
3620 * Array(1) #=> [1]
3623 static VALUE
3624 rb_f_array(VALUE obj, VALUE arg)
3626 return rb_Array(arg);
3630 * Equivalent to \c Kernel\#Hash in Ruby
3632 VALUE
3633 rb_Hash(VALUE val)
3635 VALUE tmp;
3637 if (NIL_P(val)) return rb_hash_new();
3638 tmp = rb_check_hash_type(val);
3639 if (NIL_P(tmp)) {
3640 if (RB_TYPE_P(val, T_ARRAY) && RARRAY_LEN(val) == 0)
3641 return rb_hash_new();
3642 rb_raise(rb_eTypeError, "can't convert %s into Hash", rb_obj_classname(val));
3644 return tmp;
3648 * call-seq:
3649 * Hash(arg) -> hash
3651 * Converts <i>arg</i> to a Hash by calling
3652 * <i>arg</i><code>.to_hash</code>. Returns an empty Hash when
3653 * <i>arg</i> is <tt>nil</tt> or <tt>[]</tt>.
3655 * Hash([]) #=> {}
3656 * Hash(nil) #=> {}
3657 * Hash(key: :value) #=> {:key => :value}
3658 * Hash([1, 2, 3]) #=> TypeError
3661 static VALUE
3662 rb_f_hash(VALUE obj, VALUE arg)
3664 return rb_Hash(arg);
3667 /*! \private */
3668 struct dig_method {
3669 VALUE klass;
3670 int basic;
3673 static ID id_dig;
3675 static int
3676 dig_basic_p(VALUE obj, struct dig_method *cache)
3678 VALUE klass = RBASIC_CLASS(obj);
3679 if (klass != cache->klass) {
3680 cache->klass = klass;
3681 cache->basic = rb_method_basic_definition_p(klass, id_dig);
3683 return cache->basic;
3686 static void
3687 no_dig_method(int found, VALUE recv, ID mid, int argc, const VALUE *argv, VALUE data)
3689 if (!found) {
3690 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not have #dig method",
3691 CLASS_OF(data));
3695 /*! \private */
3696 VALUE
3697 rb_obj_dig(int argc, VALUE *argv, VALUE obj, VALUE notfound)
3699 struct dig_method hash = {Qnil}, ary = {Qnil}, strt = {Qnil};
3701 for (; argc > 0; ++argv, --argc) {
3702 if (NIL_P(obj)) return notfound;
3703 if (!SPECIAL_CONST_P(obj)) {
3704 switch (BUILTIN_TYPE(obj)) {
3705 case T_HASH:
3706 if (dig_basic_p(obj, &hash)) {
3707 obj = rb_hash_aref(obj, *argv);
3708 continue;
3710 break;
3711 case T_ARRAY:
3712 if (dig_basic_p(obj, &ary)) {
3713 obj = rb_ary_at(obj, *argv);
3714 continue;
3716 break;
3717 case T_STRUCT:
3718 if (dig_basic_p(obj, &strt)) {
3719 obj = rb_struct_lookup(obj, *argv);
3720 continue;
3722 break;
3723 default:
3724 break;
3727 return rb_check_funcall_with_hook_kw(obj, id_dig, argc, argv,
3728 no_dig_method, obj,
3729 RB_NO_KEYWORDS);
3731 return obj;
3735 * call-seq:
3736 * format(format_string [, arguments...] ) -> string
3737 * sprintf(format_string [, arguments...] ) -> string
3739 * Returns the string resulting from applying <i>format_string</i> to
3740 * any additional arguments. Within the format string, any characters
3741 * other than format sequences are copied to the result.
3743 * The syntax of a format sequence is as follows.
3745 * %[flags][width][.precision]type
3747 * A format
3748 * sequence consists of a percent sign, followed by optional flags,
3749 * width, and precision indicators, then terminated with a field type
3750 * character. The field type controls how the corresponding
3751 * <code>sprintf</code> argument is to be interpreted, while the flags
3752 * modify that interpretation.
3754 * The field type characters are:
3756 * Field | Integer Format
3757 * ------+--------------------------------------------------------------
3758 * b | Convert argument as a binary number.
3759 * | Negative numbers will be displayed as a two's complement
3760 * | prefixed with `..1'.
3761 * B | Equivalent to `b', but uses an uppercase 0B for prefix
3762 * | in the alternative format by #.
3763 * d | Convert argument as a decimal number.
3764 * i | Identical to `d'.
3765 * o | Convert argument as an octal number.
3766 * | Negative numbers will be displayed as a two's complement
3767 * | prefixed with `..7'.
3768 * u | Identical to `d'.
3769 * x | Convert argument as a hexadecimal number.
3770 * | Negative numbers will be displayed as a two's complement
3771 * | prefixed with `..f' (representing an infinite string of
3772 * | leading 'ff's).
3773 * X | Equivalent to `x', but uses uppercase letters.
3775 * Field | Float Format
3776 * ------+--------------------------------------------------------------
3777 * e | Convert floating point argument into exponential notation
3778 * | with one digit before the decimal point as [-]d.dddddde[+-]dd.
3779 * | The precision specifies the number of digits after the decimal
3780 * | point (defaulting to six).
3781 * E | Equivalent to `e', but uses an uppercase E to indicate
3782 * | the exponent.
3783 * f | Convert floating point argument as [-]ddd.dddddd,
3784 * | where the precision specifies the number of digits after
3785 * | the decimal point.
3786 * g | Convert a floating point number using exponential form
3787 * | if the exponent is less than -4 or greater than or
3788 * | equal to the precision, or in dd.dddd form otherwise.
3789 * | The precision specifies the number of significant digits.
3790 * G | Equivalent to `g', but use an uppercase `E' in exponent form.
3791 * a | Convert floating point argument as [-]0xh.hhhhp[+-]dd,
3792 * | which is consisted from optional sign, "0x", fraction part
3793 * | as hexadecimal, "p", and exponential part as decimal.
3794 * A | Equivalent to `a', but use uppercase `X' and `P'.
3796 * Field | Other Format
3797 * ------+--------------------------------------------------------------
3798 * c | Argument is the numeric code for a single character or
3799 * | a single character string itself.
3800 * p | The valuing of argument.inspect.
3801 * s | Argument is a string to be substituted. If the format
3802 * | sequence contains a precision, at most that many characters
3803 * | will be copied.
3804 * % | A percent sign itself will be displayed. No argument taken.
3806 * The flags modifies the behavior of the formats.
3807 * The flag characters are:
3809 * Flag | Applies to | Meaning
3810 * ---------+---------------+-----------------------------------------
3811 * space | bBdiouxX | Leave a space at the start of
3812 * | aAeEfgG | non-negative numbers.
3813 * | (numeric fmt) | For `o', `x', `X', `b' and `B', use
3814 * | | a minus sign with absolute value for
3815 * | | negative values.
3816 * ---------+---------------+-----------------------------------------
3817 * (digit)$ | all | Specifies the absolute argument number
3818 * | | for this field. Absolute and relative
3819 * | | argument numbers cannot be mixed in a
3820 * | | sprintf string.
3821 * ---------+---------------+-----------------------------------------
3822 * # | bBoxX | Use an alternative format.
3823 * | aAeEfgG | For the conversions `o', increase the precision
3824 * | | until the first digit will be `0' if
3825 * | | it is not formatted as complements.
3826 * | | For the conversions `x', `X', `b' and `B'
3827 * | | on non-zero, prefix the result with ``0x'',
3828 * | | ``0X'', ``0b'' and ``0B'', respectively.
3829 * | | For `a', `A', `e', `E', `f', `g', and 'G',
3830 * | | force a decimal point to be added,
3831 * | | even if no digits follow.
3832 * | | For `g' and 'G', do not remove trailing zeros.
3833 * ---------+---------------+-----------------------------------------
3834 * + | bBdiouxX | Add a leading plus sign to non-negative
3835 * | aAeEfgG | numbers.
3836 * | (numeric fmt) | For `o', `x', `X', `b' and `B', use
3837 * | | a minus sign with absolute value for
3838 * | | negative values.
3839 * ---------+---------------+-----------------------------------------
3840 * - | all | Left-justify the result of this conversion.
3841 * ---------+---------------+-----------------------------------------
3842 * 0 (zero) | bBdiouxX | Pad with zeros, not spaces.
3843 * | aAeEfgG | For `o', `x', `X', `b' and `B', radix-1
3844 * | (numeric fmt) | is used for negative numbers formatted as
3845 * | | complements.
3846 * ---------+---------------+-----------------------------------------
3847 * * | all | Use the next argument as the field width.
3848 * | | If negative, left-justify the result. If the
3849 * | | asterisk is followed by a number and a dollar
3850 * | | sign, use the indicated argument as the width.
3852 * Examples of flags:
3854 * # `+' and space flag specifies the sign of non-negative numbers.
3855 * sprintf("%d", 123) #=> "123"
3856 * sprintf("%+d", 123) #=> "+123"
3857 * sprintf("% d", 123) #=> " 123"
3859 * # `#' flag for `o' increases number of digits to show `0'.
3860 * # `+' and space flag changes format of negative numbers.
3861 * sprintf("%o", 123) #=> "173"
3862 * sprintf("%#o", 123) #=> "0173"
3863 * sprintf("%+o", -123) #=> "-173"
3864 * sprintf("%o", -123) #=> "..7605"
3865 * sprintf("%#o", -123) #=> "..7605"
3867 * # `#' flag for `x' add a prefix `0x' for non-zero numbers.
3868 * # `+' and space flag disables complements for negative numbers.
3869 * sprintf("%x", 123) #=> "7b"
3870 * sprintf("%#x", 123) #=> "0x7b"
3871 * sprintf("%+x", -123) #=> "-7b"
3872 * sprintf("%x", -123) #=> "..f85"
3873 * sprintf("%#x", -123) #=> "0x..f85"
3874 * sprintf("%#x", 0) #=> "0"
3876 * # `#' for `X' uses the prefix `0X'.
3877 * sprintf("%X", 123) #=> "7B"
3878 * sprintf("%#X", 123) #=> "0X7B"
3880 * # `#' flag for `b' add a prefix `0b' for non-zero numbers.
3881 * # `+' and space flag disables complements for negative numbers.
3882 * sprintf("%b", 123) #=> "1111011"
3883 * sprintf("%#b", 123) #=> "0b1111011"
3884 * sprintf("%+b", -123) #=> "-1111011"
3885 * sprintf("%b", -123) #=> "..10000101"
3886 * sprintf("%#b", -123) #=> "0b..10000101"
3887 * sprintf("%#b", 0) #=> "0"
3889 * # `#' for `B' uses the prefix `0B'.
3890 * sprintf("%B", 123) #=> "1111011"
3891 * sprintf("%#B", 123) #=> "0B1111011"
3893 * # `#' for `e' forces to show the decimal point.
3894 * sprintf("%.0e", 1) #=> "1e+00"
3895 * sprintf("%#.0e", 1) #=> "1.e+00"
3897 * # `#' for `f' forces to show the decimal point.
3898 * sprintf("%.0f", 1234) #=> "1234"
3899 * sprintf("%#.0f", 1234) #=> "1234."
3901 * # `#' for `g' forces to show the decimal point.
3902 * # It also disables stripping lowest zeros.
3903 * sprintf("%g", 123.4) #=> "123.4"
3904 * sprintf("%#g", 123.4) #=> "123.400"
3905 * sprintf("%g", 123456) #=> "123456"
3906 * sprintf("%#g", 123456) #=> "123456."
3908 * The field width is an optional integer, followed optionally by a
3909 * period and a precision. The width specifies the minimum number of
3910 * characters that will be written to the result for this field.
3912 * Examples of width:
3914 * # padding is done by spaces, width=20
3915 * # 0 or radix-1. <------------------>
3916 * sprintf("%20d", 123) #=> " 123"
3917 * sprintf("%+20d", 123) #=> " +123"
3918 * sprintf("%020d", 123) #=> "00000000000000000123"
3919 * sprintf("%+020d", 123) #=> "+0000000000000000123"
3920 * sprintf("% 020d", 123) #=> " 0000000000000000123"
3921 * sprintf("%-20d", 123) #=> "123 "
3922 * sprintf("%-+20d", 123) #=> "+123 "
3923 * sprintf("%- 20d", 123) #=> " 123 "
3924 * sprintf("%020x", -123) #=> "..ffffffffffffffff85"
3926 * For
3927 * numeric fields, the precision controls the number of decimal places
3928 * displayed. For string fields, the precision determines the maximum
3929 * number of characters to be copied from the string. (Thus, the format
3930 * sequence <code>%10.10s</code> will always contribute exactly ten
3931 * characters to the result.)
3933 * Examples of precisions:
3935 * # precision for `d', 'o', 'x' and 'b' is
3936 * # minimum number of digits <------>
3937 * sprintf("%20.8d", 123) #=> " 00000123"
3938 * sprintf("%20.8o", 123) #=> " 00000173"
3939 * sprintf("%20.8x", 123) #=> " 0000007b"
3940 * sprintf("%20.8b", 123) #=> " 01111011"
3941 * sprintf("%20.8d", -123) #=> " -00000123"
3942 * sprintf("%20.8o", -123) #=> " ..777605"
3943 * sprintf("%20.8x", -123) #=> " ..ffff85"
3944 * sprintf("%20.8b", -11) #=> " ..110101"
3946 * # "0x" and "0b" for `#x' and `#b' is not counted for
3947 * # precision but "0" for `#o' is counted. <------>
3948 * sprintf("%#20.8d", 123) #=> " 00000123"
3949 * sprintf("%#20.8o", 123) #=> " 00000173"
3950 * sprintf("%#20.8x", 123) #=> " 0x0000007b"
3951 * sprintf("%#20.8b", 123) #=> " 0b01111011"
3952 * sprintf("%#20.8d", -123) #=> " -00000123"
3953 * sprintf("%#20.8o", -123) #=> " ..777605"
3954 * sprintf("%#20.8x", -123) #=> " 0x..ffff85"
3955 * sprintf("%#20.8b", -11) #=> " 0b..110101"
3957 * # precision for `e' is number of
3958 * # digits after the decimal point <------>
3959 * sprintf("%20.8e", 1234.56789) #=> " 1.23456789e+03"
3961 * # precision for `f' is number of
3962 * # digits after the decimal point <------>
3963 * sprintf("%20.8f", 1234.56789) #=> " 1234.56789000"
3965 * # precision for `g' is number of
3966 * # significant digits <------->
3967 * sprintf("%20.8g", 1234.56789) #=> " 1234.5679"
3969 * # <------->
3970 * sprintf("%20.8g", 123456789) #=> " 1.2345679e+08"
3972 * # precision for `s' is
3973 * # maximum number of characters <------>
3974 * sprintf("%20.8s", "string test") #=> " string t"
3976 * Examples:
3978 * sprintf("%d %04x", 123, 123) #=> "123 007b"
3979 * sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'"
3980 * sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello"
3981 * sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8"
3982 * sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23"
3983 * sprintf("%u", -123) #=> "-123"
3985 * For more complex formatting, Ruby supports a reference by name.
3986 * %<name>s style uses format style, but %{name} style doesn't.
3988 * Examples:
3989 * sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 })
3990 * #=> 1 : 2.000000
3991 * sprintf("%{foo}f", { :foo => 1 })
3992 * # => "1f"
3995 static VALUE
3996 f_sprintf(int c, const VALUE *v, VALUE _)
3998 return rb_f_sprintf(c, v);
4002 * Document-class: Class
4004 * Classes in Ruby are first-class objects---each is an instance of
4005 * class Class.
4007 * Typically, you create a new class by using:
4009 * class Name
4010 * # some code describing the class behavior
4011 * end
4013 * When a new class is created, an object of type Class is initialized and
4014 * assigned to a global constant (Name in this case).
4016 * When <code>Name.new</code> is called to create a new object, the
4017 * #new method in Class is run by default.
4018 * This can be demonstrated by overriding #new in Class:
4020 * class Class
4021 * alias old_new new
4022 * def new(*args)
4023 * print "Creating a new ", self.name, "\n"
4024 * old_new(*args)
4025 * end
4026 * end
4028 * class Name
4029 * end
4031 * n = Name.new
4033 * <em>produces:</em>
4035 * Creating a new Name
4037 * Classes, modules, and objects are interrelated. In the diagram
4038 * that follows, the vertical arrows represent inheritance, and the
4039 * parentheses metaclasses. All metaclasses are instances
4040 * of the class `Class'.
4041 * +---------+ +-...
4042 * | | |
4043 * BasicObject-----|-->(BasicObject)-------|-...
4044 * ^ | ^ |
4045 * | | | |
4046 * Object---------|----->(Object)---------|-...
4047 * ^ | ^ |
4048 * | | | |
4049 * +-------+ | +--------+ |
4050 * | | | | | |
4051 * | Module-|---------|--->(Module)-|-...
4052 * | ^ | | ^ |
4053 * | | | | | |
4054 * | Class-|---------|---->(Class)-|-...
4055 * | ^ | | ^ |
4056 * | +---+ | +----+
4057 * | |
4058 * obj--->OtherClass---------->(OtherClass)-----------...
4063 /* Document-class: BasicObject
4065 * BasicObject is the parent class of all classes in Ruby. It's an explicit
4066 * blank class.
4068 * BasicObject can be used for creating object hierarchies independent of
4069 * Ruby's object hierarchy, proxy objects like the Delegator class, or other
4070 * uses where namespace pollution from Ruby's methods and classes must be
4071 * avoided.
4073 * To avoid polluting BasicObject for other users an appropriately named
4074 * subclass of BasicObject should be created instead of directly modifying
4075 * BasicObject:
4077 * class MyObjectSystem < BasicObject
4078 * end
4080 * BasicObject does not include Kernel (for methods like +puts+) and
4081 * BasicObject is outside of the namespace of the standard library so common
4082 * classes will not be found without using a full class path.
4084 * A variety of strategies can be used to provide useful portions of the
4085 * standard library to subclasses of BasicObject. A subclass could
4086 * <code>include Kernel</code> to obtain +puts+, +exit+, etc. A custom
4087 * Kernel-like module could be created and included or delegation can be used
4088 * via #method_missing:
4090 * class MyObjectSystem < BasicObject
4091 * DELEGATE = [:puts, :p]
4093 * def method_missing(name, *args, &block)
4094 * return super unless DELEGATE.include? name
4095 * ::Kernel.send(name, *args, &block)
4096 * end
4098 * def respond_to_missing?(name, include_private = false)
4099 * DELEGATE.include?(name) or super
4100 * end
4101 * end
4103 * Access to classes and modules from the Ruby standard library can be
4104 * obtained in a BasicObject subclass by referencing the desired constant
4105 * from the root like <code>::File</code> or <code>::Enumerator</code>.
4106 * Like #method_missing, #const_missing can be used to delegate constant
4107 * lookup to +Object+:
4109 * class MyObjectSystem < BasicObject
4110 * def self.const_missing(name)
4111 * ::Object.const_get(name)
4112 * end
4113 * end
4115 * === What's Here
4117 * These are the methods defined for \BasicObject:
4119 * - ::new:: Returns a new \BasicObject instance.
4120 * - {!}[#method-i-21]:: Returns the boolean negation of +self+: +true+ or +false+.
4121 * - {!=}[#method-i-21-3D]:: Returns whether +self+ and the given object
4122 * are _not_ equal.
4123 * - {==}[#method-i-3D-3D]:: Returns whether +self+ and the given object
4124 * are equivalent.
4125 * - {__id__}[#method-i-__id__]:: Returns the integer object identifier for +self+.
4126 * - {__send__}[#method-i-__send__]:: Calls the method identified by the given symbol.
4127 * - #equal?:: Returns whether +self+ and the given object are the same object.
4128 * - #instance_eval:: Evaluates the given string or block in the context of +self+.
4129 * - #instance_exec:: Executes the given block in the context of +self+,
4130 * passing the given arguments.
4131 * - #method_missing:: Method called when an undefined method is called on +self+.
4132 * - #singleton_method_added:: Method called when a singleton method
4133 * is added to +self+.
4134 * - #singleton_method_removed:: Method called when a singleton method
4135 * is added removed from +self+.
4136 * - #singleton_method_undefined:: Method called when a singleton method
4137 * is undefined in +self+.
4141 /* Document-class: Object
4143 * Object is the default root of all Ruby objects. Object inherits from
4144 * BasicObject which allows creating alternate object hierarchies. Methods
4145 * on Object are available to all classes unless explicitly overridden.
4147 * Object mixes in the Kernel module, making the built-in kernel functions
4148 * globally accessible. Although the instance methods of Object are defined
4149 * by the Kernel module, we have chosen to document them here for clarity.
4151 * When referencing constants in classes inheriting from Object you do not
4152 * need to use the full namespace. For example, referencing +File+ inside
4153 * +YourClass+ will find the top-level File class.
4155 * In the descriptions of Object's methods, the parameter <i>symbol</i> refers
4156 * to a symbol, which is either a quoted string or a Symbol (such as
4157 * <code>:name</code>).
4159 * == What's Here
4161 * First, what's elsewhere. \Class \Object:
4163 * - Inherits from {class BasicObject}[BasicObject.html#class-BasicObject-label-What-27s+Here].
4164 * - Includes {module Kernel}[Kernel.html#module-Kernel-label-What-27s+Here].
4166 * Here, class \Object provides methods for:
4168 * - {Querying}[#class-Object-label-Querying]
4169 * - {Instance Variables}[#class-Object-label-Instance+Variables]
4170 * - {Other}[#class-Object-label-Other]
4172 * === Querying
4174 * - {!~}[#method-i-21~]:: Returns +true+ if +self+ does not match the given object,
4175 * otherwise +false+.
4176 * - {<=>}[#method-i-3C-3D-3E]:: Returns 0 if +self+ and the given object +object+
4177 * are the same object, or if
4178 * <tt>self == object</tt>; otherwise returns +nil+.
4179 * - #===:: Implements case equality, effectively the same as calling #==.
4180 * - #eql?:: Implements hash equality, effectively the same as calling #==.
4181 * - #kind_of? (aliased as #is_a?):: Returns whether given argument is an ancestor
4182 * of the singleton class of +self+.
4183 * - #instance_of?:: Returns whether +self+ is an instance of the given class.
4184 * - #instance_variable_defined?:: Returns whether the given instance variable
4185 * is defined in +self+.
4186 * - #method:: Returns the Method object for the given method in +self+.
4187 * - #methods:: Returns an array of symbol names of public and protected methods
4188 * in +self+.
4189 * - #nil?:: Returns +false+. (Only +nil+ responds +true+ to method <tt>nil?</tt>.)
4190 * - #object_id:: Returns an integer corresponding to +self+ that is unique
4191 * for the current process
4192 * - #private_methods:: Returns an array of the symbol names
4193 * of the private methods in +self+.
4194 * - #protected_methods:: Returns an array of the symbol names
4195 * of the protected methods in +self+.
4196 * - #public_method:: Returns the Method object for the given public method in +self+.
4197 * - #public_methods:: Returns an array of the symbol names
4198 * of the public methods in +self+.
4199 * - #respond_to?:: Returns whether +self+ responds to the given method.
4200 * - #singleton_class:: Returns the singleton class of +self+.
4201 * - #singleton_method:: Returns the Method object for the given singleton method
4202 * in +self+.
4203 * - #singleton_methods:: Returns an array of the symbol names
4204 * of the singleton methods in +self+.
4206 * - #define_singleton_method:: Defines a singleton method in +self+
4207 * for the given symbol method-name and block or proc.
4208 * - #extend:: Includes the given modules in the singleton class of +self+.
4209 * - #public_send:: Calls the given public method in +self+ with the given argument.
4210 * - #send:: Calls the given method in +self+ with the given argument.
4212 * === Instance Variables
4214 * - #instance_variable_get:: Returns the value of the given instance variable
4215 * in +self+, or +nil+ if the instance variable is not set.
4216 * - #instance_variable_set:: Sets the value of the given instance variable in +self+
4217 * to the given object.
4218 * - #instance_variables:: Returns an array of the symbol names
4219 * of the instance variables in +self+.
4220 * - #remove_instance_variable:: Removes the named instance variable from +self+.
4222 * === Other
4224 * - #clone:: Returns a shallow copy of +self+, including singleton class
4225 * and frozen state.
4226 * - #define_singleton_method:: Defines a singleton method in +self+
4227 * for the given symbol method-name and block or proc.
4228 * - #display:: Prints +self+ to the given \IO stream or <tt>$stdout</tt>.
4229 * - #dup:: Returns a shallow unfrozen copy of +self+.
4230 * - #enum_for (aliased as #to_enum):: Returns an Enumerator for +self+
4231 * using the using the given method,
4232 * arguments, and block.
4233 * - #extend:: Includes the given modules in the singleton class of +self+.
4234 * - #freeze:: Prevents further modifications to +self+.
4235 * - #hash:: Returns the integer hash value for +self+.
4236 * - #inspect:: Returns a human-readable string representation of +self+.
4237 * - #itself:: Returns +self+.
4238 * - #public_send:: Calls the given public method in +self+ with the given argument.
4239 * - #send:: Calls the given method in +self+ with the given argument.
4240 * - #to_s:: Returns a string representation of +self+.
4246 * \private
4247 * Initializes the world of objects and classes.
4249 * At first, the function bootstraps the class hierarchy.
4250 * It initializes the most fundamental classes and their metaclasses.
4251 * - \c BasicObject
4252 * - \c Object
4253 * - \c Module
4254 * - \c Class
4255 * After the bootstrap step, the class hierarchy becomes as the following
4256 * diagram.
4258 * \image html boottime-classes.png
4260 * Then, the function defines classes, modules and methods as usual.
4261 * \ingroup class
4265 void
4266 InitVM_Object(void)
4268 Init_class_hierarchy();
4270 #if 0
4271 // teach RDoc about these classes
4272 rb_cBasicObject = rb_define_class("BasicObject", Qnil);
4273 rb_cObject = rb_define_class("Object", rb_cBasicObject);
4274 rb_cModule = rb_define_class("Module", rb_cObject);
4275 rb_cClass = rb_define_class("Class", rb_cModule);
4276 rb_cRefinement = rb_define_class("Refinement", rb_cModule);
4277 #endif
4279 rb_define_private_method(rb_cBasicObject, "initialize", rb_obj_initialize, 0);
4280 rb_define_alloc_func(rb_cBasicObject, rb_class_allocate_instance);
4281 rb_define_method(rb_cBasicObject, "==", rb_obj_equal, 1);
4282 rb_define_method(rb_cBasicObject, "equal?", rb_obj_equal, 1);
4283 rb_define_method(rb_cBasicObject, "!", rb_obj_not, 0);
4284 rb_define_method(rb_cBasicObject, "!=", rb_obj_not_equal, 1);
4286 rb_define_private_method(rb_cBasicObject, "singleton_method_added", rb_obj_singleton_method_added, 1);
4287 rb_define_private_method(rb_cBasicObject, "singleton_method_removed", rb_obj_singleton_method_removed, 1);
4288 rb_define_private_method(rb_cBasicObject, "singleton_method_undefined", rb_obj_singleton_method_undefined, 1);
4290 /* Document-module: Kernel
4292 * The Kernel module is included by class Object, so its methods are
4293 * available in every Ruby object.
4295 * The Kernel instance methods are documented in class Object while the
4296 * module methods are documented here. These methods are called without a
4297 * receiver and thus can be called in functional form:
4299 * sprintf "%.1f", 1.234 #=> "1.2"
4301 * == What's Here
4303 * \Module \Kernel provides methods that are useful for:
4305 * - {Converting}[#module-Kernel-label-Converting]
4306 * - {Querying}[#module-Kernel-label-Querying]
4307 * - {Exiting}[#module-Kernel-label-Exiting]
4308 * - {Exceptions}[#module-Kernel-label-Exceptions]
4309 * - {IO}[#module-Kernel-label-IO]
4310 * - {Procs}[#module-Kernel-label-Procs]
4311 * - {Tracing}[#module-Kernel-label-Tracing]
4312 * - {Subprocesses}[#module-Kernel-label-Subprocesses]
4313 * - {Loading}[#module-Kernel-label-Loading]
4314 * - {Yielding}[#module-Kernel-label-Yielding]
4315 * - {Random Values}[#module-Kernel-label-Random+Values]
4316 * - {Other}[#module-Kernel-label-Other]
4318 * === Converting
4320 * - {#Array}[#method-i-Array]:: Returns an Array based on the given argument.
4321 * - {#Complex}[#method-i-Complex]:: Returns a Complex based on the given arguments.
4322 * - {#Float}[#method-i-Float]:: Returns a Float based on the given arguments.
4323 * - {#Hash}[#method-i-Hash]:: Returns a Hash based on the given argument.
4324 * - {#Integer}[#method-i-Integer]:: Returns an Integer based on the given arguments.
4325 * - {#Rational}[#method-i-Rational]:: Returns a Rational
4326 * based on the given arguments.
4327 * - {#String}[#method-i-String]:: Returns a String based on the given argument.
4329 * === Querying
4331 * - {#__callee__}[#method-i-__callee__]:: Returns the called name
4332 * of the current method as a symbol.
4333 * - {#__dir__}[#method-i-__dir__]:: Returns the path to the directory
4334 * from which the current method is called.
4335 * - {#__method__}[#method-i-__method__]:: Returns the name
4336 * of the current method as a symbol.
4337 * - #autoload?:: Returns the file to be loaded when the given module is referenced.
4338 * - #binding:: Returns a Binding for the context at the point of call.
4339 * - #block_given?:: Returns +true+ if a block was passed to the calling method.
4340 * - #caller:: Returns the current execution stack as an array of strings.
4341 * - #caller_locations:: Returns the current execution stack as an array
4342 * of Thread::Backtrace::Location objects.
4343 * - #class:: Returns the class of +self+.
4344 * - #frozen?:: Returns whether +self+ is frozen.
4345 * - #global_variables:: Returns an array of global variables as symbols.
4346 * - #local_variables:: Returns an array of local variables as symbols.
4347 * - #test:: Performs specified tests on the given single file or pair of files.
4349 * === Exiting
4351 * - #abort:: Exits the current process after printing the given arguments.
4352 * - #at_exit:: Executes the given block when the process exits.
4353 * - #exit:: Exits the current process after calling any registered
4354 * +at_exit+ handlers.
4355 * - #exit!:: Exits the current process without calling any registered
4356 * +at_exit+ handlers.
4358 * === Exceptions
4360 * - #catch:: Executes the given block, possibly catching a thrown object.
4361 * - #raise (aliased as #fail):: Raises an exception based on the given arguments.
4362 * - #throw:: Returns from the active catch block waiting for the given tag.
4365 * === \IO
4367 * - #gets:: Returns and assigns to <tt>$_</tt> the next line from the current input.
4368 * - #open:: Creates an IO object connected to the given stream, file, or subprocess.
4369 * - #p:: Prints the given objects' inspect output to the standard output.
4370 * - #pp:: Prints the given objects in pretty form.
4371 * - #print:: Prints the given objects to standard output without a newline.
4372 * - #printf:: Prints the string resulting from applying the given format string
4373 * to any additional arguments.
4374 * - #putc:: Equivalent to <tt.$stdout.putc(object)</tt> for the given object.
4375 * - #puts:: Equivalent to <tt>$stdout.puts(*objects)</tt> for the given objects.
4376 * - #readline:: Similar to #gets, but raises an exception at the end of file.
4377 * - #readlines:: Returns an array of the remaining lines from the current input.
4378 * - #select:: Same as IO.select.
4380 * === Procs
4382 * - #lambda:: Returns a lambda proc for the given block.
4383 * - #proc:: Returns a new Proc; equivalent to Proc.new.
4385 * === Tracing
4387 * - #set_trace_func:: Sets the given proc as the handler for tracing,
4388 * or disables tracing if given +nil+.
4389 * - #trace_var:: Starts tracing assignments to the given global variable.
4390 * - #untrace_var:: Disables tracing of assignments to the given global variable.
4392 * === Subprocesses
4394 * - #`cmd`:: Returns the standard output of running +cmd+ in a subshell.
4395 * - #exec:: Replaces current process with a new process.
4396 * - #fork:: Forks the current process into two processes.
4397 * - #spawn:: Executes the given command and returns its pid without waiting
4398 * for completion.
4399 * - #system:: Executes the given command in a subshell.
4401 * === Loading
4403 * - #autoload:: Registers the given file to be loaded when the given constant
4404 * is first referenced.
4405 * - #load:: Loads the given Ruby file.
4406 * - #require:: Loads the given Ruby file unless it has already been loaded.
4407 * - #require_relative:: Loads the Ruby file path relative to the calling file,
4408 * unless it has already been loaded.
4410 * === Yielding
4412 * - #tap:: Yields +self+ to the given block; returns +self+.
4413 * - #then (aliased as #yield_self):: Yields +self+ to the block
4414 * and returns the result of the block.
4416 * === \Random Values
4418 * - #rand:: Returns a pseudo-random floating point number
4419 * strictly between 0.0 and 1.0.
4420 * - #srand:: Seeds the pseudo-random number generator with the given number.
4422 * === Other
4424 * - #eval:: Evaluates the given string as Ruby code.
4425 * - #loop:: Repeatedly executes the given block.
4426 * - #sleep:: Suspends the current thread for the given number of seconds.
4427 * - #sprintf (aliased as #format):: Returns the string resulting from applying
4428 * the given format string
4429 * to any additional arguments.
4430 * - #syscall:: Runs an operating system call.
4431 * - #trap:: Specifies the handling of system signals.
4432 * - #warn:: Issue a warning based on the given messages and options.
4435 rb_mKernel = rb_define_module("Kernel");
4436 rb_include_module(rb_cObject, rb_mKernel);
4437 rb_define_private_method(rb_cClass, "inherited", rb_obj_class_inherited, 1);
4438 rb_define_private_method(rb_cModule, "included", rb_obj_mod_included, 1);
4439 rb_define_private_method(rb_cModule, "extended", rb_obj_mod_extended, 1);
4440 rb_define_private_method(rb_cModule, "prepended", rb_obj_mod_prepended, 1);
4441 rb_define_private_method(rb_cModule, "method_added", rb_obj_mod_method_added, 1);
4442 rb_define_private_method(rb_cModule, "method_removed", rb_obj_mod_method_removed, 1);
4443 rb_define_private_method(rb_cModule, "method_undefined", rb_obj_mod_method_undefined, 1);
4445 rb_define_method(rb_mKernel, "nil?", rb_false, 0);
4446 rb_define_method(rb_mKernel, "===", case_equal, 1);
4447 rb_define_method(rb_mKernel, "=~", rb_obj_match, 1);
4448 rb_define_method(rb_mKernel, "!~", rb_obj_not_match, 1);
4449 rb_define_method(rb_mKernel, "eql?", rb_obj_equal, 1);
4450 rb_define_method(rb_mKernel, "hash", rb_obj_hash, 0); /* in hash.c */
4451 rb_define_method(rb_mKernel, "<=>", rb_obj_cmp, 1);
4453 rb_define_method(rb_mKernel, "singleton_class", rb_obj_singleton_class, 0);
4454 rb_define_method(rb_mKernel, "dup", rb_obj_dup, 0);
4455 rb_define_method(rb_mKernel, "itself", rb_obj_itself, 0);
4456 rb_define_method(rb_mKernel, "initialize_copy", rb_obj_init_copy, 1);
4457 rb_define_method(rb_mKernel, "initialize_dup", rb_obj_init_dup_clone, 1);
4458 rb_define_method(rb_mKernel, "initialize_clone", rb_obj_init_clone, -1);
4460 rb_define_method(rb_mKernel, "freeze", rb_obj_freeze, 0);
4462 rb_define_method(rb_mKernel, "to_s", rb_any_to_s, 0);
4463 rb_define_method(rb_mKernel, "inspect", rb_obj_inspect, 0);
4464 rb_define_method(rb_mKernel, "methods", rb_obj_methods, -1); /* in class.c */
4465 rb_define_method(rb_mKernel, "singleton_methods", rb_obj_singleton_methods, -1); /* in class.c */
4466 rb_define_method(rb_mKernel, "protected_methods", rb_obj_protected_methods, -1); /* in class.c */
4467 rb_define_method(rb_mKernel, "private_methods", rb_obj_private_methods, -1); /* in class.c */
4468 rb_define_method(rb_mKernel, "public_methods", rb_obj_public_methods, -1); /* in class.c */
4469 rb_define_method(rb_mKernel, "instance_variables", rb_obj_instance_variables, 0); /* in variable.c */
4470 rb_define_method(rb_mKernel, "instance_variable_get", rb_obj_ivar_get, 1);
4471 rb_define_method(rb_mKernel, "instance_variable_set", rb_obj_ivar_set, 2);
4472 rb_define_method(rb_mKernel, "instance_variable_defined?", rb_obj_ivar_defined, 1);
4473 rb_define_method(rb_mKernel, "remove_instance_variable",
4474 rb_obj_remove_instance_variable, 1); /* in variable.c */
4476 rb_define_method(rb_mKernel, "instance_of?", rb_obj_is_instance_of, 1);
4477 rb_define_method(rb_mKernel, "kind_of?", rb_obj_is_kind_of, 1);
4478 rb_define_method(rb_mKernel, "is_a?", rb_obj_is_kind_of, 1);
4480 rb_define_global_function("sprintf", f_sprintf, -1);
4481 rb_define_global_function("format", f_sprintf, -1);
4483 rb_define_global_function("Integer", rb_f_integer, -1);
4485 rb_define_global_function("String", rb_f_string, 1);
4486 rb_define_global_function("Array", rb_f_array, 1);
4487 rb_define_global_function("Hash", rb_f_hash, 1);
4489 rb_cNilClass = rb_define_class("NilClass", rb_cObject);
4490 rb_cNilClass_to_s = rb_fstring_enc_lit("", rb_usascii_encoding());
4491 rb_gc_register_mark_object(rb_cNilClass_to_s);
4492 rb_define_method(rb_cNilClass, "to_s", rb_nil_to_s, 0);
4493 rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0);
4494 rb_define_method(rb_cNilClass, "to_h", nil_to_h, 0);
4495 rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0);
4496 rb_define_method(rb_cNilClass, "=~", nil_match, 1);
4497 rb_define_method(rb_cNilClass, "&", false_and, 1);
4498 rb_define_method(rb_cNilClass, "|", false_or, 1);
4499 rb_define_method(rb_cNilClass, "^", false_xor, 1);
4500 rb_define_method(rb_cNilClass, "===", case_equal, 1);
4502 rb_define_method(rb_cNilClass, "nil?", rb_true, 0);
4503 rb_undef_alloc_func(rb_cNilClass);
4504 rb_undef_method(CLASS_OF(rb_cNilClass), "new");
4506 rb_define_method(rb_cModule, "freeze", rb_mod_freeze, 0);
4507 rb_define_method(rb_cModule, "===", rb_mod_eqq, 1);
4508 rb_define_method(rb_cModule, "==", rb_obj_equal, 1);
4509 rb_define_method(rb_cModule, "<=>", rb_mod_cmp, 1);
4510 rb_define_method(rb_cModule, "<", rb_mod_lt, 1);
4511 rb_define_method(rb_cModule, "<=", rb_class_inherited_p, 1);
4512 rb_define_method(rb_cModule, ">", rb_mod_gt, 1);
4513 rb_define_method(rb_cModule, ">=", rb_mod_ge, 1);
4514 rb_define_method(rb_cModule, "initialize_copy", rb_mod_init_copy, 1); /* in class.c */
4515 rb_define_method(rb_cModule, "to_s", rb_mod_to_s, 0);
4516 rb_define_alias(rb_cModule, "inspect", "to_s");
4517 rb_define_method(rb_cModule, "included_modules", rb_mod_included_modules, 0); /* in class.c */
4518 rb_define_method(rb_cModule, "include?", rb_mod_include_p, 1); /* in class.c */
4519 rb_define_method(rb_cModule, "name", rb_mod_name, 0); /* in variable.c */
4520 rb_define_method(rb_cModule, "ancestors", rb_mod_ancestors, 0); /* in class.c */
4522 rb_define_method(rb_cModule, "attr", rb_mod_attr, -1);
4523 rb_define_method(rb_cModule, "attr_reader", rb_mod_attr_reader, -1);
4524 rb_define_method(rb_cModule, "attr_writer", rb_mod_attr_writer, -1);
4525 rb_define_method(rb_cModule, "attr_accessor", rb_mod_attr_accessor, -1);
4527 rb_define_alloc_func(rb_cModule, rb_module_s_alloc);
4528 rb_undef_method(rb_singleton_class(rb_cModule), "allocate");
4529 rb_define_method(rb_cModule, "initialize", rb_mod_initialize, 0);
4530 rb_define_method(rb_cModule, "initialize_clone", rb_mod_initialize_clone, -1);
4531 rb_define_method(rb_cModule, "instance_methods", rb_class_instance_methods, -1); /* in class.c */
4532 rb_define_method(rb_cModule, "public_instance_methods",
4533 rb_class_public_instance_methods, -1); /* in class.c */
4534 rb_define_method(rb_cModule, "protected_instance_methods",
4535 rb_class_protected_instance_methods, -1); /* in class.c */
4536 rb_define_method(rb_cModule, "private_instance_methods",
4537 rb_class_private_instance_methods, -1); /* in class.c */
4539 rb_define_method(rb_cModule, "constants", rb_mod_constants, -1); /* in variable.c */
4540 rb_define_method(rb_cModule, "const_get", rb_mod_const_get, -1);
4541 rb_define_method(rb_cModule, "const_set", rb_mod_const_set, 2);
4542 rb_define_method(rb_cModule, "const_defined?", rb_mod_const_defined, -1);
4543 rb_define_method(rb_cModule, "const_source_location", rb_mod_const_source_location, -1);
4544 rb_define_private_method(rb_cModule, "remove_const",
4545 rb_mod_remove_const, 1); /* in variable.c */
4546 rb_define_method(rb_cModule, "const_missing",
4547 rb_mod_const_missing, 1); /* in variable.c */
4548 rb_define_method(rb_cModule, "class_variables",
4549 rb_mod_class_variables, -1); /* in variable.c */
4550 rb_define_method(rb_cModule, "remove_class_variable",
4551 rb_mod_remove_cvar, 1); /* in variable.c */
4552 rb_define_method(rb_cModule, "class_variable_get", rb_mod_cvar_get, 1);
4553 rb_define_method(rb_cModule, "class_variable_set", rb_mod_cvar_set, 2);
4554 rb_define_method(rb_cModule, "class_variable_defined?", rb_mod_cvar_defined, 1);
4555 rb_define_method(rb_cModule, "public_constant", rb_mod_public_constant, -1); /* in variable.c */
4556 rb_define_method(rb_cModule, "private_constant", rb_mod_private_constant, -1); /* in variable.c */
4557 rb_define_method(rb_cModule, "deprecate_constant", rb_mod_deprecate_constant, -1); /* in variable.c */
4558 rb_define_method(rb_cModule, "singleton_class?", rb_mod_singleton_p, 0);
4560 rb_define_method(rb_singleton_class(rb_cClass), "allocate", rb_class_alloc_m, 0);
4561 rb_define_method(rb_cClass, "allocate", rb_class_alloc_m, 0);
4562 rb_define_method(rb_cClass, "new", rb_class_new_instance_pass_kw, -1);
4563 rb_define_method(rb_cClass, "initialize", rb_class_initialize, -1);
4564 rb_define_method(rb_cClass, "superclass", rb_class_superclass, 0);
4565 rb_define_method(rb_cClass, "subclasses", rb_class_subclasses, 0); /* in class.c */
4566 rb_define_alloc_func(rb_cClass, rb_class_s_alloc);
4567 rb_undef_method(rb_cClass, "extend_object");
4568 rb_undef_method(rb_cClass, "append_features");
4569 rb_undef_method(rb_cClass, "prepend_features");
4571 rb_cTrueClass = rb_define_class("TrueClass", rb_cObject);
4572 rb_cTrueClass_to_s = rb_fstring_enc_lit("true", rb_usascii_encoding());
4573 rb_gc_register_mark_object(rb_cTrueClass_to_s);
4574 rb_define_method(rb_cTrueClass, "to_s", rb_true_to_s, 0);
4575 rb_define_alias(rb_cTrueClass, "inspect", "to_s");
4576 rb_define_method(rb_cTrueClass, "&", true_and, 1);
4577 rb_define_method(rb_cTrueClass, "|", true_or, 1);
4578 rb_define_method(rb_cTrueClass, "^", true_xor, 1);
4579 rb_define_method(rb_cTrueClass, "===", case_equal, 1);
4580 rb_undef_alloc_func(rb_cTrueClass);
4581 rb_undef_method(CLASS_OF(rb_cTrueClass), "new");
4583 rb_cFalseClass = rb_define_class("FalseClass", rb_cObject);
4584 rb_cFalseClass_to_s = rb_fstring_enc_lit("false", rb_usascii_encoding());
4585 rb_gc_register_mark_object(rb_cFalseClass_to_s);
4586 rb_define_method(rb_cFalseClass, "to_s", rb_false_to_s, 0);
4587 rb_define_alias(rb_cFalseClass, "inspect", "to_s");
4588 rb_define_method(rb_cFalseClass, "&", false_and, 1);
4589 rb_define_method(rb_cFalseClass, "|", false_or, 1);
4590 rb_define_method(rb_cFalseClass, "^", false_xor, 1);
4591 rb_define_method(rb_cFalseClass, "===", case_equal, 1);
4592 rb_undef_alloc_func(rb_cFalseClass);
4593 rb_undef_method(CLASS_OF(rb_cFalseClass), "new");
4596 #include "kernel.rbinc"
4597 #include "nilclass.rbinc"
4599 void
4600 Init_Object(void)
4602 id_dig = rb_intern_const("dig");
4603 InitVM(Object);
4607 * \}