Fix typos [ci skip]
[ruby-80x24.org.git] / object.c
blob430f7eafd0514c65317c9e4b634f678ad9bf0bb3
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.tainted? -> false
1107 * Returns false. This method is deprecated and will be removed in Ruby 3.2.
1110 VALUE
1111 rb_obj_tainted(VALUE obj)
1113 rb_warn_deprecated_to_remove_at(3.2, "Object#tainted?", NULL);
1114 return Qfalse;
1118 * call-seq:
1119 * obj.taint -> obj
1121 * Returns object. This method is deprecated and will be removed in Ruby 3.2.
1124 VALUE
1125 rb_obj_taint(VALUE obj)
1127 rb_warn_deprecated_to_remove_at(3.2, "Object#taint", NULL);
1128 return obj;
1133 * call-seq:
1134 * obj.untaint -> obj
1136 * Returns object. This method is deprecated and will be removed in Ruby 3.2.
1139 VALUE
1140 rb_obj_untaint(VALUE obj)
1142 rb_warn_deprecated_to_remove_at(3.2, "Object#untaint", NULL);
1143 return obj;
1147 * call-seq:
1148 * obj.untrusted? -> false
1150 * Returns false. This method is deprecated and will be removed in Ruby 3.2.
1153 VALUE
1154 rb_obj_untrusted(VALUE obj)
1156 rb_warn_deprecated_to_remove_at(3.2, "Object#untrusted?", NULL);
1157 return Qfalse;
1161 * call-seq:
1162 * obj.untrust -> obj
1164 * Returns object. This method is deprecated and will be removed in Ruby 3.2.
1167 VALUE
1168 rb_obj_untrust(VALUE obj)
1170 rb_warn_deprecated_to_remove_at(3.2, "Object#untrust", NULL);
1171 return obj;
1176 * call-seq:
1177 * obj.trust -> obj
1179 * Returns object. This method is deprecated and will be removed in Ruby 3.2.
1182 VALUE
1183 rb_obj_trust(VALUE obj)
1185 rb_warn_deprecated_to_remove_at(3.2, "Object#trust", NULL);
1186 return obj;
1189 void
1190 rb_obj_infect(VALUE victim, VALUE carrier)
1192 rb_warn_deprecated_to_remove_at(3.2, "rb_obj_infect", NULL);
1196 * call-seq:
1197 * obj.freeze -> obj
1199 * Prevents further modifications to <i>obj</i>. A
1200 * FrozenError will be raised if modification is attempted.
1201 * There is no way to unfreeze a frozen object. See also
1202 * Object#frozen?.
1204 * This method returns self.
1206 * a = [ "a", "b", "c" ]
1207 * a.freeze
1208 * a << "z"
1210 * <em>produces:</em>
1212 * prog.rb:3:in `<<': can't modify frozen Array (FrozenError)
1213 * from prog.rb:3
1215 * Objects of the following classes are always frozen: Integer,
1216 * Float, Symbol.
1219 VALUE
1220 rb_obj_freeze(VALUE obj)
1222 if (!OBJ_FROZEN(obj)) {
1223 OBJ_FREEZE(obj);
1224 if (SPECIAL_CONST_P(obj)) {
1225 rb_bug("special consts should be frozen.");
1228 return obj;
1231 VALUE
1232 rb_obj_frozen_p(VALUE obj)
1234 return RBOOL(OBJ_FROZEN(obj));
1239 * Document-class: NilClass
1241 * The class of the singleton object <code>nil</code>.
1245 * call-seq:
1246 * nil.to_s -> ""
1248 * Always returns the empty string.
1251 MJIT_FUNC_EXPORTED VALUE
1252 rb_nil_to_s(VALUE obj)
1254 return rb_cNilClass_to_s;
1258 * Document-method: to_a
1260 * call-seq:
1261 * nil.to_a -> []
1263 * Always returns an empty array.
1265 * nil.to_a #=> []
1268 static VALUE
1269 nil_to_a(VALUE obj)
1271 return rb_ary_new2(0);
1275 * Document-method: to_h
1277 * call-seq:
1278 * nil.to_h -> {}
1280 * Always returns an empty hash.
1282 * nil.to_h #=> {}
1285 static VALUE
1286 nil_to_h(VALUE obj)
1288 return rb_hash_new();
1292 * call-seq:
1293 * nil.inspect -> "nil"
1295 * Always returns the string "nil".
1298 static VALUE
1299 nil_inspect(VALUE obj)
1301 return rb_usascii_str_new2("nil");
1305 * call-seq:
1306 * nil =~ other -> nil
1308 * Dummy pattern matching -- always returns nil.
1311 static VALUE
1312 nil_match(VALUE obj1, VALUE obj2)
1314 return Qnil;
1317 /***********************************************************************
1318 * Document-class: TrueClass
1320 * The global value <code>true</code> is the only instance of class
1321 * TrueClass and represents a logically true value in
1322 * boolean expressions. The class provides operators allowing
1323 * <code>true</code> to be used in logical expressions.
1328 * call-seq:
1329 * true.to_s -> "true"
1331 * The string representation of <code>true</code> is "true".
1334 MJIT_FUNC_EXPORTED VALUE
1335 rb_true_to_s(VALUE obj)
1337 return rb_cTrueClass_to_s;
1342 * call-seq:
1343 * true & obj -> true or false
1345 * And---Returns <code>false</code> if <i>obj</i> is
1346 * <code>nil</code> or <code>false</code>, <code>true</code> otherwise.
1349 static VALUE
1350 true_and(VALUE obj, VALUE obj2)
1352 return RBOOL(RTEST(obj2));
1356 * call-seq:
1357 * true | obj -> true
1359 * Or---Returns <code>true</code>. As <i>obj</i> is an argument to
1360 * a method call, it is always evaluated; there is no short-circuit
1361 * evaluation in this case.
1363 * true | puts("or")
1364 * true || puts("logical or")
1366 * <em>produces:</em>
1368 * or
1371 static VALUE
1372 true_or(VALUE obj, VALUE obj2)
1374 return Qtrue;
1379 * call-seq:
1380 * true ^ obj -> !obj
1382 * Exclusive Or---Returns <code>true</code> if <i>obj</i> is
1383 * <code>nil</code> or <code>false</code>, <code>false</code>
1384 * otherwise.
1387 static VALUE
1388 true_xor(VALUE obj, VALUE obj2)
1390 return RTEST(obj2)?Qfalse:Qtrue;
1395 * Document-class: FalseClass
1397 * The global value <code>false</code> is the only instance of class
1398 * FalseClass and represents a logically false value in
1399 * boolean expressions. The class provides operators allowing
1400 * <code>false</code> to participate correctly in logical expressions.
1405 * call-seq:
1406 * false.to_s -> "false"
1408 * The string representation of <code>false</code> is "false".
1411 MJIT_FUNC_EXPORTED VALUE
1412 rb_false_to_s(VALUE obj)
1414 return rb_cFalseClass_to_s;
1418 * call-seq:
1419 * false & obj -> false
1420 * nil & obj -> false
1422 * And---Returns <code>false</code>. <i>obj</i> is always
1423 * evaluated as it is the argument to a method call---there is no
1424 * short-circuit evaluation in this case.
1427 static VALUE
1428 false_and(VALUE obj, VALUE obj2)
1430 return Qfalse;
1435 * call-seq:
1436 * false | obj -> true or false
1437 * nil | obj -> true or false
1439 * Or---Returns <code>false</code> if <i>obj</i> is
1440 * <code>nil</code> or <code>false</code>; <code>true</code> otherwise.
1443 #define false_or true_and
1446 * call-seq:
1447 * false ^ obj -> true or false
1448 * nil ^ obj -> true or false
1450 * Exclusive Or---If <i>obj</i> is <code>nil</code> or
1451 * <code>false</code>, returns <code>false</code>; otherwise, returns
1452 * <code>true</code>.
1456 #define false_xor true_and
1459 * call-seq:
1460 * nil.nil? -> true
1462 * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1465 static VALUE
1466 rb_true(VALUE obj)
1468 return Qtrue;
1472 * call-seq:
1473 * obj.nil? -> true or false
1475 * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1477 * Object.new.nil? #=> false
1478 * nil.nil? #=> true
1482 MJIT_FUNC_EXPORTED VALUE
1483 rb_false(VALUE obj)
1485 return Qfalse;
1490 * call-seq:
1491 * obj =~ other -> nil
1493 * This method is deprecated.
1495 * This is not only useless but also troublesome because it may hide a
1496 * type error.
1499 static VALUE
1500 rb_obj_match(VALUE obj1, VALUE obj2)
1502 if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) {
1503 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "deprecated Object#=~ is called on %"PRIsVALUE
1504 "; it always returns nil", rb_obj_class(obj1));
1506 return Qnil;
1510 * call-seq:
1511 * obj !~ other -> true or false
1513 * Returns true if two objects do not match (using the <i>=~</i>
1514 * method), otherwise false.
1517 static VALUE
1518 rb_obj_not_match(VALUE obj1, VALUE obj2)
1520 VALUE result = rb_funcall(obj1, id_match, 1, obj2);
1521 return RTEST(result) ? Qfalse : Qtrue;
1526 * call-seq:
1527 * obj <=> other -> 0 or nil
1529 * Returns 0 if +obj+ and +other+ are the same object
1530 * or <code>obj == other</code>, otherwise nil.
1532 * The #<=> is used by various methods to compare objects, for example
1533 * Enumerable#sort, Enumerable#max etc.
1535 * Your implementation of #<=> should return one of the following values: -1, 0,
1536 * 1 or nil. -1 means self is smaller than other. 0 means self is equal to other.
1537 * 1 means self is bigger than other. Nil means the two values could not be
1538 * compared.
1540 * When you define #<=>, you can include Comparable to gain the
1541 * methods #<=, #<, #==, #>=, #> and #between?.
1543 static VALUE
1544 rb_obj_cmp(VALUE obj1, VALUE obj2)
1546 if (rb_equal(obj1, obj2))
1547 return INT2FIX(0);
1548 return Qnil;
1551 /***********************************************************************
1553 * Document-class: Module
1555 * A Module is a collection of methods and constants. The
1556 * methods in a module may be instance methods or module methods.
1557 * Instance methods appear as methods in a class when the module is
1558 * included, module methods do not. Conversely, module methods may be
1559 * called without creating an encapsulating object, while instance
1560 * methods may not. (See Module#module_function.)
1562 * In the descriptions that follow, the parameter <i>sym</i> refers
1563 * to a symbol, which is either a quoted string or a
1564 * Symbol (such as <code>:name</code>).
1566 * module Mod
1567 * include Math
1568 * CONST = 1
1569 * def meth
1570 * # ...
1571 * end
1572 * end
1573 * Mod.class #=> Module
1574 * Mod.constants #=> [:CONST, :PI, :E]
1575 * Mod.instance_methods #=> [:meth]
1580 * call-seq:
1581 * mod.to_s -> string
1583 * Returns a string representing this module or class. For basic
1584 * classes and modules, this is the name. For singletons, we
1585 * show information on the thing we're attached to as well.
1588 MJIT_FUNC_EXPORTED VALUE
1589 rb_mod_to_s(VALUE klass)
1591 ID id_defined_at;
1592 VALUE refined_class, defined_at;
1594 if (FL_TEST(klass, FL_SINGLETON)) {
1595 VALUE s = rb_usascii_str_new2("#<Class:");
1596 VALUE v = rb_ivar_get(klass, id__attached__);
1598 if (CLASS_OR_MODULE_P(v)) {
1599 rb_str_append(s, rb_inspect(v));
1601 else {
1602 rb_str_append(s, rb_any_to_s(v));
1604 rb_str_cat2(s, ">");
1606 return s;
1608 refined_class = rb_refinement_module_get_refined_class(klass);
1609 if (!NIL_P(refined_class)) {
1610 VALUE s = rb_usascii_str_new2("#<refinement:");
1612 rb_str_concat(s, rb_inspect(refined_class));
1613 rb_str_cat2(s, "@");
1614 CONST_ID(id_defined_at, "__defined_at__");
1615 defined_at = rb_attr_get(klass, id_defined_at);
1616 rb_str_concat(s, rb_inspect(defined_at));
1617 rb_str_cat2(s, ">");
1618 return s;
1620 return rb_class_name(klass);
1624 * call-seq:
1625 * mod.freeze -> mod
1627 * Prevents further modifications to <i>mod</i>.
1629 * This method returns self.
1632 static VALUE
1633 rb_mod_freeze(VALUE mod)
1635 rb_class_name(mod);
1636 return rb_obj_freeze(mod);
1640 * call-seq:
1641 * mod === obj -> true or false
1643 * Case Equality---Returns <code>true</code> if <i>obj</i> is an
1644 * instance of <i>mod</i> or an instance of one of <i>mod</i>'s descendants.
1645 * Of limited use for modules, but can be used in <code>case</code> statements
1646 * to classify objects by class.
1649 static VALUE
1650 rb_mod_eqq(VALUE mod, VALUE arg)
1652 return rb_obj_is_kind_of(arg, mod);
1656 * call-seq:
1657 * mod <= other -> true, false, or nil
1659 * Returns true if <i>mod</i> is a subclass of <i>other</i> or
1660 * is the same as <i>other</i>. Returns
1661 * <code>nil</code> if there's no relationship between the two.
1662 * (Think of the relationship in terms of the class definition:
1663 * "class A < B" implies "A < B".)
1666 VALUE
1667 rb_class_inherited_p(VALUE mod, VALUE arg)
1669 if (mod == arg) return Qtrue;
1670 if (!CLASS_OR_MODULE_P(arg) && !RB_TYPE_P(arg, T_ICLASS)) {
1671 rb_raise(rb_eTypeError, "compared with non class/module");
1673 if (class_search_ancestor(mod, RCLASS_ORIGIN(arg))) {
1674 return Qtrue;
1676 /* not mod < arg; check if mod > arg */
1677 if (class_search_ancestor(arg, mod)) {
1678 return Qfalse;
1680 return Qnil;
1684 * call-seq:
1685 * mod < other -> true, false, or nil
1687 * Returns true if <i>mod</i> is a subclass of <i>other</i>. Returns
1688 * <code>nil</code> if there's no relationship between the two.
1689 * (Think of the relationship in terms of the class definition:
1690 * "class A < B" implies "A < B".)
1694 static VALUE
1695 rb_mod_lt(VALUE mod, VALUE arg)
1697 if (mod == arg) return Qfalse;
1698 return rb_class_inherited_p(mod, arg);
1703 * call-seq:
1704 * mod >= other -> true, false, or nil
1706 * Returns true if <i>mod</i> is an ancestor of <i>other</i>, or the
1707 * two modules are the same. Returns
1708 * <code>nil</code> if there's no relationship between the two.
1709 * (Think of the relationship in terms of the class definition:
1710 * "class A < B" implies "B > A".)
1714 static VALUE
1715 rb_mod_ge(VALUE mod, VALUE arg)
1717 if (!CLASS_OR_MODULE_P(arg)) {
1718 rb_raise(rb_eTypeError, "compared with non class/module");
1721 return rb_class_inherited_p(arg, mod);
1725 * call-seq:
1726 * mod > other -> true, false, or nil
1728 * Returns true if <i>mod</i> is an ancestor of <i>other</i>. Returns
1729 * <code>nil</code> if there's no relationship between the two.
1730 * (Think of the relationship in terms of the class definition:
1731 * "class A < B" implies "B > A".)
1735 static VALUE
1736 rb_mod_gt(VALUE mod, VALUE arg)
1738 if (mod == arg) return Qfalse;
1739 return rb_mod_ge(mod, arg);
1743 * call-seq:
1744 * module <=> other_module -> -1, 0, +1, or nil
1746 * Comparison---Returns -1, 0, +1 or nil depending on whether +module+
1747 * includes +other_module+, they are the same, or if +module+ is included by
1748 * +other_module+.
1750 * Returns +nil+ if +module+ has no relationship with +other_module+, if
1751 * +other_module+ is not a module, or if the two values are incomparable.
1754 static VALUE
1755 rb_mod_cmp(VALUE mod, VALUE arg)
1757 VALUE cmp;
1759 if (mod == arg) return INT2FIX(0);
1760 if (!CLASS_OR_MODULE_P(arg)) {
1761 return Qnil;
1764 cmp = rb_class_inherited_p(mod, arg);
1765 if (NIL_P(cmp)) return Qnil;
1766 if (cmp) {
1767 return INT2FIX(-1);
1769 return INT2FIX(1);
1772 static VALUE rb_mod_initialize_exec(VALUE module);
1775 * call-seq:
1776 * Module.new -> mod
1777 * Module.new {|mod| block } -> mod
1779 * Creates a new anonymous module. If a block is given, it is passed
1780 * the module object, and the block is evaluated in the context of this
1781 * module like #module_eval.
1783 * fred = Module.new do
1784 * def meth1
1785 * "hello"
1786 * end
1787 * def meth2
1788 * "bye"
1789 * end
1790 * end
1791 * a = "my string"
1792 * a.extend(fred) #=> "my string"
1793 * a.meth1 #=> "hello"
1794 * a.meth2 #=> "bye"
1796 * Assign the module to a constant (name starting uppercase) if you
1797 * want to treat it like a regular module.
1800 static VALUE
1801 rb_mod_initialize(VALUE module)
1803 rb_module_check_initializable(module);
1804 return rb_mod_initialize_exec(module);
1807 static VALUE
1808 rb_mod_initialize_exec(VALUE module)
1810 if (rb_block_given_p()) {
1811 rb_mod_module_exec(1, &module, module);
1813 return Qnil;
1816 /* :nodoc: */
1817 static VALUE
1818 rb_mod_initialize_clone(int argc, VALUE* argv, VALUE clone)
1820 VALUE ret, orig, opts;
1821 rb_scan_args(argc, argv, "1:", &orig, &opts);
1822 ret = rb_obj_init_clone(argc, argv, clone);
1823 if (OBJ_FROZEN(orig))
1824 rb_class_name(clone);
1825 return ret;
1829 * call-seq:
1830 * Class.new(super_class=Object) -> a_class
1831 * Class.new(super_class=Object) { |mod| ... } -> a_class
1833 * Creates a new anonymous (unnamed) class with the given superclass
1834 * (or Object if no parameter is given). You can give a
1835 * class a name by assigning the class object to a constant.
1837 * If a block is given, it is passed the class object, and the block
1838 * is evaluated in the context of this class like
1839 * #class_eval.
1841 * fred = Class.new do
1842 * def meth1
1843 * "hello"
1844 * end
1845 * def meth2
1846 * "bye"
1847 * end
1848 * end
1850 * a = fred.new #=> #<#<Class:0x100381890>:0x100376b98>
1851 * a.meth1 #=> "hello"
1852 * a.meth2 #=> "bye"
1854 * Assign the class to a constant (name starting uppercase) if you
1855 * want to treat it like a regular class.
1858 static VALUE
1859 rb_class_initialize(int argc, VALUE *argv, VALUE klass)
1861 VALUE super;
1863 if (RCLASS_SUPER(klass) != 0 || klass == rb_cBasicObject) {
1864 rb_raise(rb_eTypeError, "already initialized class");
1866 if (rb_check_arity(argc, 0, 1) == 0) {
1867 super = rb_cObject;
1869 else {
1870 super = argv[0];
1871 rb_check_inheritable(super);
1872 if (super != rb_cBasicObject && !RCLASS_SUPER(super)) {
1873 rb_raise(rb_eTypeError, "can't inherit uninitialized class");
1876 RCLASS_SET_SUPER(klass, super);
1877 rb_make_metaclass(klass, RBASIC(super)->klass);
1878 rb_class_inherited(super, klass);
1879 rb_mod_initialize_exec(klass);
1881 return klass;
1884 /*! \private */
1885 void
1886 rb_undefined_alloc(VALUE klass)
1888 rb_raise(rb_eTypeError, "allocator undefined for %"PRIsVALUE,
1889 klass);
1892 static rb_alloc_func_t class_get_alloc_func(VALUE klass);
1893 static VALUE class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass);
1896 * call-seq:
1897 * class.allocate() -> obj
1899 * Allocates space for a new object of <i>class</i>'s class and does not
1900 * call initialize on the new instance. The returned object must be an
1901 * instance of <i>class</i>.
1903 * klass = Class.new do
1904 * def initialize(*args)
1905 * @initialized = true
1906 * end
1908 * def initialized?
1909 * @initialized || false
1910 * end
1911 * end
1913 * klass.allocate.initialized? #=> false
1917 static VALUE
1918 rb_class_alloc_m(VALUE klass)
1920 rb_alloc_func_t allocator = class_get_alloc_func(klass);
1921 if (!rb_obj_respond_to(klass, rb_intern("allocate"), 1)) {
1922 rb_raise(rb_eTypeError, "calling %"PRIsVALUE".allocate is prohibited",
1923 klass);
1925 return class_call_alloc_func(allocator, klass);
1928 static VALUE
1929 rb_class_alloc(VALUE klass)
1931 rb_alloc_func_t allocator = class_get_alloc_func(klass);
1932 return class_call_alloc_func(allocator, klass);
1935 static rb_alloc_func_t
1936 class_get_alloc_func(VALUE klass)
1938 rb_alloc_func_t allocator;
1940 if (RCLASS_SUPER(klass) == 0 && klass != rb_cBasicObject) {
1941 rb_raise(rb_eTypeError, "can't instantiate uninitialized class");
1943 if (FL_TEST(klass, FL_SINGLETON)) {
1944 rb_raise(rb_eTypeError, "can't create instance of singleton class");
1946 allocator = rb_get_alloc_func(klass);
1947 if (!allocator) {
1948 rb_undefined_alloc(klass);
1950 return allocator;
1953 static VALUE
1954 class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass)
1956 VALUE obj;
1958 RUBY_DTRACE_CREATE_HOOK(OBJECT, rb_class2name(klass));
1960 obj = (*allocator)(klass);
1962 if (rb_obj_class(obj) != rb_class_real(klass)) {
1963 rb_raise(rb_eTypeError, "wrong instance allocation");
1965 return obj;
1968 VALUE
1969 rb_obj_alloc(VALUE klass)
1971 Check_Type(klass, T_CLASS);
1972 return rb_class_alloc(klass);
1976 * call-seq:
1977 * class.new(args, ...) -> obj
1979 * Calls #allocate to create a new object of <i>class</i>'s class,
1980 * then invokes that object's #initialize method, passing it
1981 * <i>args</i>. This is the method that ends up getting called
1982 * whenever an object is constructed using <code>.new</code>.
1986 VALUE
1987 rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass)
1989 VALUE obj;
1991 obj = rb_class_alloc(klass);
1992 rb_obj_call_init_kw(obj, argc, argv, RB_PASS_CALLED_KEYWORDS);
1994 return obj;
1997 VALUE
1998 rb_class_new_instance_kw(int argc, const VALUE *argv, VALUE klass, int kw_splat)
2000 VALUE obj;
2001 Check_Type(klass, T_CLASS);
2003 obj = rb_class_alloc(klass);
2004 rb_obj_call_init_kw(obj, argc, argv, kw_splat);
2006 return obj;
2009 VALUE
2010 rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
2012 VALUE obj;
2013 Check_Type(klass, T_CLASS);
2015 obj = rb_class_alloc(klass);
2016 rb_obj_call_init_kw(obj, argc, argv, RB_NO_KEYWORDS);
2018 return obj;
2022 * call-seq:
2023 * class.superclass -> a_super_class or nil
2025 * Returns the superclass of <i>class</i>, or <code>nil</code>.
2027 * File.superclass #=> IO
2028 * IO.superclass #=> Object
2029 * Object.superclass #=> BasicObject
2030 * class Foo; end
2031 * class Bar < Foo; end
2032 * Bar.superclass #=> Foo
2034 * Returns nil when the given class does not have a parent class:
2036 * BasicObject.superclass #=> nil
2039 * Returns the superclass of \a klass. Equivalent to \c Class\#superclass in Ruby.
2041 * It skips modules.
2042 * \param[in] klass a Class object
2043 * \return the superclass, or \c Qnil if \a klass does not have a parent class.
2044 * \sa rb_class_get_superclass
2048 VALUE
2049 rb_class_superclass(VALUE klass)
2051 VALUE super = RCLASS_SUPER(klass);
2053 if (!super) {
2054 if (klass == rb_cBasicObject) return Qnil;
2055 rb_raise(rb_eTypeError, "uninitialized class");
2057 while (RB_TYPE_P(super, T_ICLASS)) {
2058 super = RCLASS_SUPER(super);
2060 if (!super) {
2061 return Qnil;
2063 return super;
2066 VALUE
2067 rb_class_get_superclass(VALUE klass)
2069 return RCLASS(klass)->super;
2072 static const char bad_instance_name[] = "`%1$s' is not allowed as an instance variable name";
2073 static const char bad_class_name[] = "`%1$s' is not allowed as a class variable name";
2074 static const char bad_const_name[] = "wrong constant name %1$s";
2075 static const char bad_attr_name[] = "invalid attribute name `%1$s'";
2076 #define wrong_constant_name bad_const_name
2078 /*! \private */
2079 #define id_for_var(obj, name, type) id_for_setter(obj, name, type, bad_##type##_name)
2080 /*! \private */
2081 #define id_for_setter(obj, name, type, message) \
2082 check_setter_id(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message))
2083 static ID
2084 check_setter_id(VALUE obj, VALUE *pname,
2085 int (*valid_id_p)(ID), int (*valid_name_p)(VALUE),
2086 const char *message, size_t message_len)
2088 ID id = rb_check_id(pname);
2089 VALUE name = *pname;
2091 if (id ? !valid_id_p(id) : !valid_name_p(name)) {
2092 rb_name_err_raise_str(rb_fstring_new(message, message_len),
2093 obj, name);
2095 return id;
2098 static int
2099 rb_is_attr_name(VALUE name)
2101 return rb_is_local_name(name) || rb_is_const_name(name);
2104 static int
2105 rb_is_attr_id(ID id)
2107 return rb_is_local_id(id) || rb_is_const_id(id);
2110 static ID
2111 id_for_attr(VALUE obj, VALUE name)
2113 ID id = id_for_var(obj, name, attr);
2114 if (!id) id = rb_intern_str(name);
2115 return id;
2119 * call-seq:
2120 * attr_reader(symbol, ...) -> array
2121 * attr(symbol, ...) -> array
2122 * attr_reader(string, ...) -> array
2123 * attr(string, ...) -> array
2125 * Creates instance variables and corresponding methods that return the
2126 * value of each instance variable. Equivalent to calling
2127 * ``<code>attr</code><i>:name</i>'' on each name in turn.
2128 * String arguments are converted to symbols.
2129 * Returns an array of defined method names as symbols.
2132 static VALUE
2133 rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass)
2135 int i;
2136 VALUE names = rb_ary_new2(argc);
2138 for (i=0; i<argc; i++) {
2139 ID id = id_for_attr(klass, argv[i]);
2140 rb_attr(klass, id, TRUE, FALSE, TRUE);
2141 rb_ary_push(names, ID2SYM(id));
2143 return names;
2147 * call-seq:
2148 * attr(name, ...) -> array
2149 * attr(name, true) -> array
2150 * attr(name, false) -> array
2152 * The first form is equivalent to #attr_reader.
2153 * The second form is equivalent to <code>attr_accessor(name)</code> but deprecated.
2154 * The last form is equivalent to <code>attr_reader(name)</code> but deprecated.
2155 * Returns an array of defined method names as symbols.
2157 * \private
2158 * \todo can be static?
2161 VALUE
2162 rb_mod_attr(int argc, VALUE *argv, VALUE klass)
2164 if (argc == 2 && (argv[1] == Qtrue || argv[1] == Qfalse)) {
2165 ID id = id_for_attr(klass, argv[0]);
2166 VALUE names = rb_ary_new();
2168 rb_category_warning(RB_WARN_CATEGORY_DEPRECATED, "optional boolean argument is obsoleted");
2169 rb_attr(klass, id, 1, RTEST(argv[1]), TRUE);
2170 rb_ary_push(names, ID2SYM(id));
2171 if (argv[1] == Qtrue) rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2172 return names;
2174 return rb_mod_attr_reader(argc, argv, klass);
2178 * call-seq:
2179 * attr_writer(symbol, ...) -> array
2180 * attr_writer(string, ...) -> array
2182 * Creates an accessor method to allow assignment to the attribute
2183 * <i>symbol</i><code>.id2name</code>.
2184 * String arguments are converted to symbols.
2185 * Returns an array of defined method names as symbols.
2188 static VALUE
2189 rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass)
2191 int i;
2192 VALUE names = rb_ary_new2(argc);
2194 for (i=0; i<argc; i++) {
2195 ID id = id_for_attr(klass, argv[i]);
2196 rb_attr(klass, id, FALSE, TRUE, TRUE);
2197 rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2199 return names;
2203 * call-seq:
2204 * attr_accessor(symbol, ...) -> array
2205 * attr_accessor(string, ...) -> array
2207 * Defines a named attribute for this module, where the name is
2208 * <i>symbol.</i><code>id2name</code>, creating an instance variable
2209 * (<code>@name</code>) and a corresponding access method to read it.
2210 * Also creates a method called <code>name=</code> to set the attribute.
2211 * String arguments are converted to symbols.
2212 * Returns an array of defined method names as symbols.
2214 * module Mod
2215 * attr_accessor(:one, :two) #=> [:one, :one=, :two, :two=]
2216 * end
2217 * Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
2220 static VALUE
2221 rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass)
2223 int i;
2224 VALUE names = rb_ary_new2(argc * 2);
2226 for (i=0; i<argc; i++) {
2227 ID id = id_for_attr(klass, argv[i]);
2229 rb_attr(klass, id, TRUE, TRUE, TRUE);
2230 rb_ary_push(names, ID2SYM(id));
2231 rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2233 return names;
2237 * call-seq:
2238 * mod.const_get(sym, inherit=true) -> obj
2239 * mod.const_get(str, inherit=true) -> obj
2241 * Checks for a constant with the given name in <i>mod</i>.
2242 * If +inherit+ is set, the lookup will also search
2243 * the ancestors (and +Object+ if <i>mod</i> is a +Module+).
2245 * The value of the constant is returned if a definition is found,
2246 * otherwise a +NameError+ is raised.
2248 * Math.const_get(:PI) #=> 3.14159265358979
2250 * This method will recursively look up constant names if a namespaced
2251 * class name is provided. For example:
2253 * module Foo; class Bar; end end
2254 * Object.const_get 'Foo::Bar'
2256 * The +inherit+ flag is respected on each lookup. For example:
2258 * module Foo
2259 * class Bar
2260 * VAL = 10
2261 * end
2263 * class Baz < Bar; end
2264 * end
2266 * Object.const_get 'Foo::Baz::VAL' # => 10
2267 * Object.const_get 'Foo::Baz::VAL', false # => NameError
2269 * If the argument is not a valid constant name a +NameError+ will be
2270 * raised with a warning "wrong constant name".
2272 * Object.const_get 'foobar' #=> NameError: wrong constant name foobar
2276 static VALUE
2277 rb_mod_const_get(int argc, VALUE *argv, VALUE mod)
2279 VALUE name, recur;
2280 rb_encoding *enc;
2281 const char *pbeg, *p, *path, *pend;
2282 ID id;
2284 rb_check_arity(argc, 1, 2);
2285 name = argv[0];
2286 recur = (argc == 1) ? Qtrue : argv[1];
2288 if (SYMBOL_P(name)) {
2289 if (!rb_is_const_sym(name)) goto wrong_name;
2290 id = rb_check_id(&name);
2291 if (!id) return rb_const_missing(mod, name);
2292 return RTEST(recur) ? rb_const_get(mod, id) : rb_const_get_at(mod, id);
2295 path = StringValuePtr(name);
2296 enc = rb_enc_get(name);
2298 if (!rb_enc_asciicompat(enc)) {
2299 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2302 pbeg = p = path;
2303 pend = path + RSTRING_LEN(name);
2305 if (p >= pend || !*p) {
2306 goto wrong_name;
2309 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2310 mod = rb_cObject;
2311 p += 2;
2312 pbeg = p;
2315 while (p < pend) {
2316 VALUE part;
2317 long len, beglen;
2319 while (p < pend && *p != ':') p++;
2321 if (pbeg == p) goto wrong_name;
2323 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2324 beglen = pbeg-path;
2326 if (p < pend && p[0] == ':') {
2327 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2328 p += 2;
2329 pbeg = p;
2332 if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2333 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2334 QUOTE(name));
2337 if (!id) {
2338 part = rb_str_subseq(name, beglen, len);
2339 OBJ_FREEZE(part);
2340 if (!rb_is_const_name(part)) {
2341 name = part;
2342 goto wrong_name;
2344 else if (!rb_method_basic_definition_p(CLASS_OF(mod), id_const_missing)) {
2345 part = rb_str_intern(part);
2346 mod = rb_const_missing(mod, part);
2347 continue;
2349 else {
2350 rb_mod_const_missing(mod, part);
2353 if (!rb_is_const_id(id)) {
2354 name = ID2SYM(id);
2355 goto wrong_name;
2357 #if 0
2358 mod = rb_const_get_0(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2359 #else
2360 if (!RTEST(recur)) {
2361 mod = rb_const_get_at(mod, id);
2363 else if (beglen == 0) {
2364 mod = rb_const_get(mod, id);
2366 else {
2367 mod = rb_const_get_from(mod, id);
2369 #endif
2372 return mod;
2374 wrong_name:
2375 rb_name_err_raise(wrong_constant_name, mod, name);
2376 UNREACHABLE_RETURN(Qundef);
2380 * call-seq:
2381 * mod.const_set(sym, obj) -> obj
2382 * mod.const_set(str, obj) -> obj
2384 * Sets the named constant to the given object, returning that object.
2385 * Creates a new constant if no constant with the given name previously
2386 * existed.
2388 * Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714
2389 * Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968
2391 * If +sym+ or +str+ is not a valid constant name a +NameError+ will be
2392 * raised with a warning "wrong constant name".
2394 * Object.const_set('foobar', 42) #=> NameError: wrong constant name foobar
2398 static VALUE
2399 rb_mod_const_set(VALUE mod, VALUE name, VALUE value)
2401 ID id = id_for_var(mod, name, const);
2402 if (!id) id = rb_intern_str(name);
2403 rb_const_set(mod, id, value);
2405 return value;
2409 * call-seq:
2410 * mod.const_defined?(sym, inherit=true) -> true or false
2411 * mod.const_defined?(str, inherit=true) -> true or false
2413 * Says whether _mod_ or its ancestors have a constant with the given name:
2415 * Float.const_defined?(:EPSILON) #=> true, found in Float itself
2416 * Float.const_defined?("String") #=> true, found in Object (ancestor)
2417 * BasicObject.const_defined?(:Hash) #=> false
2419 * If _mod_ is a +Module+, additionally +Object+ and its ancestors are checked:
2421 * Math.const_defined?(:String) #=> true, found in Object
2423 * In each of the checked classes or modules, if the constant is not present
2424 * but there is an autoload for it, +true+ is returned directly without
2425 * autoloading:
2427 * module Admin
2428 * autoload :User, 'admin/user'
2429 * end
2430 * Admin.const_defined?(:User) #=> true
2432 * If the constant is not found the callback +const_missing+ is *not* called
2433 * and the method returns +false+.
2435 * If +inherit+ is false, the lookup only checks the constants in the receiver:
2437 * IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor)
2438 * IO.const_defined?(:SYNC, false) #=> false, not found in IO itself
2440 * In this case, the same logic for autoloading applies.
2442 * If the argument is not a valid constant name a +NameError+ is raised with the
2443 * message "wrong constant name _name_":
2445 * Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar
2449 static VALUE
2450 rb_mod_const_defined(int argc, VALUE *argv, VALUE mod)
2452 VALUE name, recur;
2453 rb_encoding *enc;
2454 const char *pbeg, *p, *path, *pend;
2455 ID id;
2457 rb_check_arity(argc, 1, 2);
2458 name = argv[0];
2459 recur = (argc == 1) ? Qtrue : argv[1];
2461 if (SYMBOL_P(name)) {
2462 if (!rb_is_const_sym(name)) goto wrong_name;
2463 id = rb_check_id(&name);
2464 if (!id) return Qfalse;
2465 return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id);
2468 path = StringValuePtr(name);
2469 enc = rb_enc_get(name);
2471 if (!rb_enc_asciicompat(enc)) {
2472 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2475 pbeg = p = path;
2476 pend = path + RSTRING_LEN(name);
2478 if (p >= pend || !*p) {
2479 goto wrong_name;
2482 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2483 mod = rb_cObject;
2484 p += 2;
2485 pbeg = p;
2488 while (p < pend) {
2489 VALUE part;
2490 long len, beglen;
2492 while (p < pend && *p != ':') p++;
2494 if (pbeg == p) goto wrong_name;
2496 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2497 beglen = pbeg-path;
2499 if (p < pend && p[0] == ':') {
2500 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2501 p += 2;
2502 pbeg = p;
2505 if (!id) {
2506 part = rb_str_subseq(name, beglen, len);
2507 OBJ_FREEZE(part);
2508 if (!rb_is_const_name(part)) {
2509 name = part;
2510 goto wrong_name;
2512 else {
2513 return Qfalse;
2516 if (!rb_is_const_id(id)) {
2517 name = ID2SYM(id);
2518 goto wrong_name;
2521 #if 0
2522 mod = rb_const_search(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2523 if (mod == Qundef) return Qfalse;
2524 #else
2525 if (!RTEST(recur)) {
2526 if (!rb_const_defined_at(mod, id))
2527 return Qfalse;
2528 if (p == pend) return Qtrue;
2529 mod = rb_const_get_at(mod, id);
2531 else if (beglen == 0) {
2532 if (!rb_const_defined(mod, id))
2533 return Qfalse;
2534 if (p == pend) return Qtrue;
2535 mod = rb_const_get(mod, id);
2537 else {
2538 if (!rb_const_defined_from(mod, id))
2539 return Qfalse;
2540 if (p == pend) return Qtrue;
2541 mod = rb_const_get_from(mod, id);
2543 #endif
2545 if (p < pend && !RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2546 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2547 QUOTE(name));
2551 return Qtrue;
2553 wrong_name:
2554 rb_name_err_raise(wrong_constant_name, mod, name);
2555 UNREACHABLE_RETURN(Qundef);
2559 * call-seq:
2560 * mod.const_source_location(sym, inherit=true) -> [String, Integer]
2561 * mod.const_source_location(str, inherit=true) -> [String, Integer]
2563 * Returns the Ruby source filename and line number containing the definition
2564 * of the constant specified. If the named constant is not found, +nil+ is returned.
2565 * If the constant is found, but its source location can not be extracted
2566 * (constant is defined in C code), empty array is returned.
2568 * _inherit_ specifies whether to lookup in <code>mod.ancestors</code> (+true+
2569 * by default).
2571 * # test.rb:
2572 * class A # line 1
2573 * C1 = 1
2574 * C2 = 2
2575 * end
2577 * module M # line 6
2578 * C3 = 3
2579 * end
2581 * class B < A # line 10
2582 * include M
2583 * C4 = 4
2584 * end
2586 * class A # continuation of A definition
2587 * C2 = 8 # constant redefinition; warned yet allowed
2588 * end
2590 * p B.const_source_location('C4') # => ["test.rb", 12]
2591 * p B.const_source_location('C3') # => ["test.rb", 7]
2592 * p B.const_source_location('C1') # => ["test.rb", 2]
2594 * p B.const_source_location('C3', false) # => nil -- don't lookup in ancestors
2596 * p A.const_source_location('C2') # => ["test.rb", 16] -- actual (last) definition place
2598 * p Object.const_source_location('B') # => ["test.rb", 10] -- top-level constant could be looked through Object
2599 * p Object.const_source_location('A') # => ["test.rb", 1] -- class reopening is NOT considered new definition
2601 * p B.const_source_location('A') # => ["test.rb", 1] -- because Object is in ancestors
2602 * p M.const_source_location('A') # => ["test.rb", 1] -- Object is not ancestor, but additionally checked for modules
2604 * p Object.const_source_location('A::C1') # => ["test.rb", 2] -- nesting is supported
2605 * p Object.const_source_location('String') # => [] -- constant is defined in C code
2609 static VALUE
2610 rb_mod_const_source_location(int argc, VALUE *argv, VALUE mod)
2612 VALUE name, recur, loc = Qnil;
2613 rb_encoding *enc;
2614 const char *pbeg, *p, *path, *pend;
2615 ID id;
2617 rb_check_arity(argc, 1, 2);
2618 name = argv[0];
2619 recur = (argc == 1) ? Qtrue : argv[1];
2621 if (SYMBOL_P(name)) {
2622 if (!rb_is_const_sym(name)) goto wrong_name;
2623 id = rb_check_id(&name);
2624 if (!id) return Qnil;
2625 return RTEST(recur) ? rb_const_source_location(mod, id) : rb_const_source_location_at(mod, id);
2628 path = StringValuePtr(name);
2629 enc = rb_enc_get(name);
2631 if (!rb_enc_asciicompat(enc)) {
2632 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2635 pbeg = p = path;
2636 pend = path + RSTRING_LEN(name);
2638 if (p >= pend || !*p) {
2639 goto wrong_name;
2642 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2643 mod = rb_cObject;
2644 p += 2;
2645 pbeg = p;
2648 while (p < pend) {
2649 VALUE part;
2650 long len, beglen;
2652 while (p < pend && *p != ':') p++;
2654 if (pbeg == p) goto wrong_name;
2656 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2657 beglen = pbeg-path;
2659 if (p < pend && p[0] == ':') {
2660 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2661 p += 2;
2662 pbeg = p;
2665 if (!id) {
2666 part = rb_str_subseq(name, beglen, len);
2667 OBJ_FREEZE(part);
2668 if (!rb_is_const_name(part)) {
2669 name = part;
2670 goto wrong_name;
2672 else {
2673 return Qnil;
2676 if (!rb_is_const_id(id)) {
2677 name = ID2SYM(id);
2678 goto wrong_name;
2680 if (p < pend) {
2681 if (RTEST(recur)) {
2682 mod = rb_const_get(mod, id);
2684 else {
2685 mod = rb_const_get_at(mod, id);
2687 if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2688 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2689 QUOTE(name));
2692 else {
2693 if (RTEST(recur)) {
2694 loc = rb_const_source_location(mod, id);
2696 else {
2697 loc = rb_const_source_location_at(mod, id);
2699 break;
2701 recur = Qfalse;
2704 return loc;
2706 wrong_name:
2707 rb_name_err_raise(wrong_constant_name, mod, name);
2708 UNREACHABLE_RETURN(Qundef);
2712 * call-seq:
2713 * obj.instance_variable_get(symbol) -> obj
2714 * obj.instance_variable_get(string) -> obj
2716 * Returns the value of the given instance variable, or nil if the
2717 * instance variable is not set. The <code>@</code> part of the
2718 * variable name should be included for regular instance
2719 * variables. Throws a NameError exception if the
2720 * supplied symbol is not valid as an instance variable name.
2721 * String arguments are converted to symbols.
2723 * class Fred
2724 * def initialize(p1, p2)
2725 * @a, @b = p1, p2
2726 * end
2727 * end
2728 * fred = Fred.new('cat', 99)
2729 * fred.instance_variable_get(:@a) #=> "cat"
2730 * fred.instance_variable_get("@b") #=> 99
2733 static VALUE
2734 rb_obj_ivar_get(VALUE obj, VALUE iv)
2736 ID id = id_for_var(obj, iv, instance);
2738 if (!id) {
2739 return Qnil;
2741 return rb_ivar_get(obj, id);
2745 * call-seq:
2746 * obj.instance_variable_set(symbol, obj) -> obj
2747 * obj.instance_variable_set(string, obj) -> obj
2749 * Sets the instance variable named by <i>symbol</i> to the given
2750 * object. This may circumvent the encapsulation intended by
2751 * the author of the class, so it should be used with care.
2752 * The variable does not have to exist prior to this call.
2753 * If the instance variable name is passed as a string, that string
2754 * is converted to a symbol.
2756 * class Fred
2757 * def initialize(p1, p2)
2758 * @a, @b = p1, p2
2759 * end
2760 * end
2761 * fred = Fred.new('cat', 99)
2762 * fred.instance_variable_set(:@a, 'dog') #=> "dog"
2763 * fred.instance_variable_set(:@c, 'cat') #=> "cat"
2764 * fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
2767 static VALUE
2768 rb_obj_ivar_set(VALUE obj, VALUE iv, VALUE val)
2770 ID id = id_for_var(obj, iv, instance);
2771 if (!id) id = rb_intern_str(iv);
2772 return rb_ivar_set(obj, id, val);
2776 * call-seq:
2777 * obj.instance_variable_defined?(symbol) -> true or false
2778 * obj.instance_variable_defined?(string) -> true or false
2780 * Returns <code>true</code> if the given instance variable is
2781 * defined in <i>obj</i>.
2782 * String arguments are converted to symbols.
2784 * class Fred
2785 * def initialize(p1, p2)
2786 * @a, @b = p1, p2
2787 * end
2788 * end
2789 * fred = Fred.new('cat', 99)
2790 * fred.instance_variable_defined?(:@a) #=> true
2791 * fred.instance_variable_defined?("@b") #=> true
2792 * fred.instance_variable_defined?("@c") #=> false
2795 static VALUE
2796 rb_obj_ivar_defined(VALUE obj, VALUE iv)
2798 ID id = id_for_var(obj, iv, instance);
2800 if (!id) {
2801 return Qfalse;
2803 return rb_ivar_defined(obj, id);
2807 * call-seq:
2808 * mod.class_variable_get(symbol) -> obj
2809 * mod.class_variable_get(string) -> obj
2811 * Returns the value of the given class variable (or throws a
2812 * NameError exception). The <code>@@</code> part of the
2813 * variable name should be included for regular class variables.
2814 * String arguments are converted to symbols.
2816 * class Fred
2817 * @@foo = 99
2818 * end
2819 * Fred.class_variable_get(:@@foo) #=> 99
2822 static VALUE
2823 rb_mod_cvar_get(VALUE obj, VALUE iv)
2825 ID id = id_for_var(obj, iv, class);
2827 if (!id) {
2828 rb_name_err_raise("uninitialized class variable %1$s in %2$s",
2829 obj, iv);
2831 return rb_cvar_get(obj, id);
2835 * call-seq:
2836 * obj.class_variable_set(symbol, obj) -> obj
2837 * obj.class_variable_set(string, obj) -> obj
2839 * Sets the class variable named by <i>symbol</i> to the given
2840 * object.
2841 * If the class variable name is passed as a string, that string
2842 * is converted to a symbol.
2844 * class Fred
2845 * @@foo = 99
2846 * def foo
2847 * @@foo
2848 * end
2849 * end
2850 * Fred.class_variable_set(:@@foo, 101) #=> 101
2851 * Fred.new.foo #=> 101
2854 static VALUE
2855 rb_mod_cvar_set(VALUE obj, VALUE iv, VALUE val)
2857 ID id = id_for_var(obj, iv, class);
2858 if (!id) id = rb_intern_str(iv);
2859 rb_cvar_set(obj, id, val);
2860 return val;
2864 * call-seq:
2865 * obj.class_variable_defined?(symbol) -> true or false
2866 * obj.class_variable_defined?(string) -> true or false
2868 * Returns <code>true</code> if the given class variable is defined
2869 * in <i>obj</i>.
2870 * String arguments are converted to symbols.
2872 * class Fred
2873 * @@foo = 99
2874 * end
2875 * Fred.class_variable_defined?(:@@foo) #=> true
2876 * Fred.class_variable_defined?(:@@bar) #=> false
2879 static VALUE
2880 rb_mod_cvar_defined(VALUE obj, VALUE iv)
2882 ID id = id_for_var(obj, iv, class);
2884 if (!id) {
2885 return Qfalse;
2887 return rb_cvar_defined(obj, id);
2891 * call-seq:
2892 * mod.singleton_class? -> true or false
2894 * Returns <code>true</code> if <i>mod</i> is a singleton class or
2895 * <code>false</code> if it is an ordinary class or module.
2897 * class C
2898 * end
2899 * C.singleton_class? #=> false
2900 * C.singleton_class.singleton_class? #=> true
2903 static VALUE
2904 rb_mod_singleton_p(VALUE klass)
2906 return RBOOL(RB_TYPE_P(klass, T_CLASS) && FL_TEST(klass, FL_SINGLETON));
2909 /*! \private */
2910 static const struct conv_method_tbl {
2911 const char method[6];
2912 unsigned short id;
2913 } conv_method_names[] = {
2914 #define M(n) {#n, (unsigned short)idTo_##n}
2915 M(int),
2916 M(ary),
2917 M(str),
2918 M(sym),
2919 M(hash),
2920 M(proc),
2921 M(io),
2922 M(a),
2923 M(s),
2924 M(i),
2925 M(f),
2926 M(r),
2927 #undef M
2929 #define IMPLICIT_CONVERSIONS 7
2931 static int
2932 conv_method_index(const char *method)
2934 static const char prefix[] = "to_";
2936 if (strncmp(prefix, method, sizeof(prefix)-1) == 0) {
2937 const char *const meth = &method[sizeof(prefix)-1];
2938 int i;
2939 for (i=0; i < numberof(conv_method_names); i++) {
2940 if (conv_method_names[i].method[0] == meth[0] &&
2941 strcmp(conv_method_names[i].method, meth) == 0) {
2942 return i;
2946 return numberof(conv_method_names);
2949 static VALUE
2950 convert_type_with_id(VALUE val, const char *tname, ID method, int raise, int index)
2952 VALUE r = rb_check_funcall(val, method, 0, 0);
2953 if (r == Qundef) {
2954 if (raise) {
2955 const char *msg =
2956 ((index < 0 ? conv_method_index(rb_id2name(method)) : index)
2957 < IMPLICIT_CONVERSIONS) ?
2958 "no implicit conversion of" : "can't convert";
2959 const char *cname = NIL_P(val) ? "nil" :
2960 val == Qtrue ? "true" :
2961 val == Qfalse ? "false" :
2962 NULL;
2963 if (cname)
2964 rb_raise(rb_eTypeError, "%s %s into %s", msg, cname, tname);
2965 rb_raise(rb_eTypeError, "%s %"PRIsVALUE" into %s", msg,
2966 rb_obj_class(val),
2967 tname);
2969 return Qnil;
2971 return r;
2974 static VALUE
2975 convert_type(VALUE val, const char *tname, const char *method, int raise)
2977 int i = conv_method_index(method);
2978 ID m = i < numberof(conv_method_names) ?
2979 conv_method_names[i].id : rb_intern(method);
2980 return convert_type_with_id(val, tname, m, raise, i);
2983 /*! \private */
2984 NORETURN(static void conversion_mismatch(VALUE, const char *, const char *, VALUE));
2985 static void
2986 conversion_mismatch(VALUE val, const char *tname, const char *method, VALUE result)
2988 VALUE cname = rb_obj_class(val);
2989 rb_raise(rb_eTypeError,
2990 "can't convert %"PRIsVALUE" to %s (%"PRIsVALUE"#%s gives %"PRIsVALUE")",
2991 cname, tname, cname, method, rb_obj_class(result));
2994 VALUE
2995 rb_convert_type(VALUE val, int type, const char *tname, const char *method)
2997 VALUE v;
2999 if (TYPE(val) == type) return val;
3000 v = convert_type(val, tname, method, TRUE);
3001 if (TYPE(v) != type) {
3002 conversion_mismatch(val, tname, method, v);
3004 return v;
3007 /*! \private */
3008 VALUE
3009 rb_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
3011 VALUE v;
3013 if (TYPE(val) == type) return val;
3014 v = convert_type_with_id(val, tname, method, TRUE, -1);
3015 if (TYPE(v) != type) {
3016 conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v);
3018 return v;
3021 VALUE
3022 rb_check_convert_type(VALUE val, int type, const char *tname, const char *method)
3024 VALUE v;
3026 /* always convert T_DATA */
3027 if (TYPE(val) == type && type != T_DATA) return val;
3028 v = convert_type(val, tname, method, FALSE);
3029 if (NIL_P(v)) return Qnil;
3030 if (TYPE(v) != type) {
3031 conversion_mismatch(val, tname, method, v);
3033 return v;
3036 /*! \private */
3037 MJIT_FUNC_EXPORTED VALUE
3038 rb_check_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
3040 VALUE v;
3042 /* always convert T_DATA */
3043 if (TYPE(val) == type && type != T_DATA) return val;
3044 v = convert_type_with_id(val, tname, method, FALSE, -1);
3045 if (NIL_P(v)) return Qnil;
3046 if (TYPE(v) != type) {
3047 conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v);
3049 return v;
3052 #define try_to_int(val, mid, raise) \
3053 convert_type_with_id(val, "Integer", mid, raise, -1)
3055 ALWAYS_INLINE(static VALUE rb_to_integer_with_id_exception(VALUE val, const char *method, ID mid, int raise));
3056 /* Integer specific rb_check_convert_type_with_id */
3057 static inline VALUE
3058 rb_to_integer_with_id_exception(VALUE val, const char *method, ID mid, int raise)
3060 VALUE v;
3062 if (RB_INTEGER_TYPE_P(val)) return val;
3063 v = try_to_int(val, mid, raise);
3064 if (!raise && NIL_P(v)) return Qnil;
3065 if (!RB_INTEGER_TYPE_P(v)) {
3066 conversion_mismatch(val, "Integer", method, v);
3068 return v;
3070 #define rb_to_integer(val, method, mid) \
3071 rb_to_integer_with_id_exception(val, method, mid, TRUE)
3073 VALUE
3074 rb_check_to_integer(VALUE val, const char *method)
3076 VALUE v;
3078 if (RB_INTEGER_TYPE_P(val)) return val;
3079 v = convert_type(val, "Integer", method, FALSE);
3080 if (!RB_INTEGER_TYPE_P(v)) {
3081 return Qnil;
3083 return v;
3086 VALUE
3087 rb_to_int(VALUE val)
3089 return rb_to_integer(val, "to_int", idTo_int);
3092 VALUE
3093 rb_check_to_int(VALUE val)
3095 if (RB_INTEGER_TYPE_P(val)) return val;
3096 val = try_to_int(val, idTo_int, FALSE);
3097 if (RB_INTEGER_TYPE_P(val)) return val;
3098 return Qnil;
3101 static VALUE
3102 rb_check_to_i(VALUE val)
3104 if (RB_INTEGER_TYPE_P(val)) return val;
3105 val = try_to_int(val, idTo_i, FALSE);
3106 if (RB_INTEGER_TYPE_P(val)) return val;
3107 return Qnil;
3110 static VALUE
3111 rb_convert_to_integer(VALUE val, int base, int raise_exception)
3113 VALUE tmp;
3115 if (base) {
3116 tmp = rb_check_string_type(val);
3118 if (! NIL_P(tmp)) {
3119 val = tmp;
3121 else if (! raise_exception) {
3122 return Qnil;
3124 else {
3125 rb_raise(rb_eArgError, "base specified for non string value");
3128 if (RB_FLOAT_TYPE_P(val)) {
3129 double f = RFLOAT_VALUE(val);
3130 if (!raise_exception && !isfinite(f)) return Qnil;
3131 if (FIXABLE(f)) return LONG2FIX((long)f);
3132 return rb_dbl2big(f);
3134 else if (RB_INTEGER_TYPE_P(val)) {
3135 return val;
3137 else if (RB_TYPE_P(val, T_STRING)) {
3138 return rb_str_convert_to_inum(val, base, TRUE, raise_exception);
3140 else if (NIL_P(val)) {
3141 if (!raise_exception) return Qnil;
3142 rb_raise(rb_eTypeError, "can't convert nil into Integer");
3145 tmp = rb_protect(rb_check_to_int, val, NULL);
3146 if (RB_INTEGER_TYPE_P(tmp)) return tmp;
3147 rb_set_errinfo(Qnil);
3149 if (!raise_exception) {
3150 VALUE result = rb_protect(rb_check_to_i, val, NULL);
3151 rb_set_errinfo(Qnil);
3152 return result;
3155 return rb_to_integer(val, "to_i", idTo_i);
3158 VALUE
3159 rb_Integer(VALUE val)
3161 return rb_convert_to_integer(val, 0, TRUE);
3164 VALUE
3165 rb_check_integer_type(VALUE val)
3167 return rb_to_integer_with_id_exception(val, "to_int", idTo_int, FALSE);
3171 rb_bool_expected(VALUE obj, const char *flagname)
3173 switch (obj) {
3174 case Qtrue: case Qfalse:
3175 break;
3176 default:
3177 rb_raise(rb_eArgError, "expected true or false as %s: %+"PRIsVALUE,
3178 flagname, obj);
3180 return obj != Qfalse;
3184 rb_opts_exception_p(VALUE opts, int default_value)
3186 static const ID kwds[1] = {idException};
3187 VALUE exception;
3188 if (rb_get_kwargs(opts, kwds, 0, 1, &exception))
3189 return rb_bool_expected(exception, "exception");
3190 return default_value;
3193 #define opts_exception_p(opts) rb_opts_exception_p((opts), TRUE)
3196 * call-seq:
3197 * Integer(arg, base=0, exception: true) -> integer or nil
3199 * Converts <i>arg</i> to an Integer.
3200 * Numeric types are converted directly (with floating point numbers
3201 * being truncated). <i>base</i> (0, or between 2 and 36) is a base for
3202 * integer string representation. If <i>arg</i> is a String,
3203 * when <i>base</i> is omitted or equals zero, radix indicators
3204 * (<code>0</code>, <code>0b</code>, and <code>0x</code>) are honored.
3205 * In any case, strings should consist only of one or more digits, except
3206 * for that a sign, one underscore between two digits, and leading/trailing
3207 * spaces are optional. This behavior is different from that of
3208 * String#to_i. Non string values will be converted by first
3209 * trying <code>to_int</code>, then <code>to_i</code>.
3211 * Passing <code>nil</code> raises a TypeError, while passing a String that
3212 * does not conform with numeric representation raises an ArgumentError.
3213 * This behavior can be altered by passing <code>exception: false</code>,
3214 * in this case a not convertible value will return <code>nil</code>.
3216 * Integer(123.999) #=> 123
3217 * Integer("0x1a") #=> 26
3218 * Integer(Time.new) #=> 1204973019
3219 * Integer("0930", 10) #=> 930
3220 * Integer("111", 2) #=> 7
3221 * Integer(" +1_0 ") #=> 10
3222 * Integer(nil) #=> TypeError: can't convert nil into Integer
3223 * Integer("x") #=> ArgumentError: invalid value for Integer(): "x"
3225 * Integer("x", exception: false) #=> nil
3229 static VALUE
3230 rb_f_integer(int argc, VALUE *argv, VALUE obj)
3232 VALUE arg = Qnil, opts = Qnil;
3233 int base = 0;
3235 if (argc > 1) {
3236 int narg = 1;
3237 VALUE vbase = rb_check_to_int(argv[1]);
3238 if (!NIL_P(vbase)) {
3239 base = NUM2INT(vbase);
3240 narg = 2;
3242 if (argc > narg) {
3243 VALUE hash = rb_check_hash_type(argv[argc-1]);
3244 if (!NIL_P(hash)) {
3245 opts = rb_extract_keywords(&hash);
3246 if (!hash) --argc;
3250 rb_check_arity(argc, 1, 2);
3251 arg = argv[0];
3253 return rb_convert_to_integer(arg, base, opts_exception_p(opts));
3256 static double
3257 rb_cstr_to_dbl_raise(const char *p, int badcheck, int raise, int *error)
3259 const char *q;
3260 char *end;
3261 double d;
3262 const char *ellipsis = "";
3263 int w;
3264 enum {max_width = 20};
3265 #define OutOfRange() ((end - p > max_width) ? \
3266 (w = max_width, ellipsis = "...") : \
3267 (w = (int)(end - p), ellipsis = ""))
3269 if (!p) return 0.0;
3270 q = p;
3271 while (ISSPACE(*p)) p++;
3273 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3274 return 0.0;
3277 d = strtod(p, &end);
3278 if (errno == ERANGE) {
3279 OutOfRange();
3280 rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3281 errno = 0;
3283 if (p == end) {
3284 if (badcheck) {
3285 goto bad;
3287 return d;
3289 if (*end) {
3290 char buf[DBL_DIG * 4 + 10];
3291 char *n = buf;
3292 char *const init_e = buf + DBL_DIG * 4;
3293 char *e = init_e;
3294 char prev = 0;
3295 int dot_seen = FALSE;
3297 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3298 if (*p == '0') {
3299 prev = *n++ = '0';
3300 while (*++p == '0');
3302 while (p < end && n < e) prev = *n++ = *p++;
3303 while (*p) {
3304 if (*p == '_') {
3305 /* remove an underscore between digits */
3306 if (n == buf || !ISDIGIT(prev) || (++p, !ISDIGIT(*p))) {
3307 if (badcheck) goto bad;
3308 break;
3311 prev = *p++;
3312 if (e == init_e && (prev == 'e' || prev == 'E' || prev == 'p' || prev == 'P')) {
3313 e = buf + sizeof(buf) - 1;
3314 *n++ = prev;
3315 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3316 if (*p == '0') {
3317 prev = *n++ = '0';
3318 while (*++p == '0');
3320 continue;
3322 else if (ISSPACE(prev)) {
3323 while (ISSPACE(*p)) ++p;
3324 if (*p) {
3325 if (badcheck) goto bad;
3326 break;
3329 else if (prev == '.' ? dot_seen++ : !ISDIGIT(prev)) {
3330 if (badcheck) goto bad;
3331 break;
3333 if (n < e) *n++ = prev;
3335 *n = '\0';
3336 p = buf;
3338 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3339 return 0.0;
3342 d = strtod(p, &end);
3343 if (errno == ERANGE) {
3344 OutOfRange();
3345 rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3346 errno = 0;
3348 if (badcheck) {
3349 if (!end || p == end) goto bad;
3350 while (*end && ISSPACE(*end)) end++;
3351 if (*end) goto bad;
3354 if (errno == ERANGE) {
3355 errno = 0;
3356 OutOfRange();
3357 rb_raise(rb_eArgError, "Float %.*s%s out of range", w, q, ellipsis);
3359 return d;
3361 bad:
3362 if (raise) {
3363 rb_invalid_str(q, "Float()");
3364 UNREACHABLE_RETURN(nan(""));
3366 else {
3367 if (error) *error = 1;
3368 return 0.0;
3372 double
3373 rb_cstr_to_dbl(const char *p, int badcheck)
3375 return rb_cstr_to_dbl_raise(p, badcheck, TRUE, NULL);
3378 static double
3379 rb_str_to_dbl_raise(VALUE str, int badcheck, int raise, int *error)
3381 char *s;
3382 long len;
3383 double ret;
3384 VALUE v = 0;
3386 StringValue(str);
3387 s = RSTRING_PTR(str);
3388 len = RSTRING_LEN(str);
3389 if (s) {
3390 if (badcheck && memchr(s, '\0', len)) {
3391 if (raise)
3392 rb_raise(rb_eArgError, "string for Float contains null byte");
3393 else {
3394 if (error) *error = 1;
3395 return 0.0;
3398 if (s[len]) { /* no sentinel somehow */
3399 char *p = ALLOCV(v, (size_t)len + 1);
3400 MEMCPY(p, s, char, len);
3401 p[len] = '\0';
3402 s = p;
3405 ret = rb_cstr_to_dbl_raise(s, badcheck, raise, error);
3406 if (v)
3407 ALLOCV_END(v);
3408 return ret;
3411 FUNC_MINIMIZED(double rb_str_to_dbl(VALUE str, int badcheck));
3413 double
3414 rb_str_to_dbl(VALUE str, int badcheck)
3416 return rb_str_to_dbl_raise(str, badcheck, TRUE, NULL);
3419 /*! \cond INTERNAL_MACRO */
3420 #define fix2dbl_without_to_f(x) (double)FIX2LONG(x)
3421 #define big2dbl_without_to_f(x) rb_big2dbl(x)
3422 #define int2dbl_without_to_f(x) \
3423 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : big2dbl_without_to_f(x))
3424 #define num2dbl_without_to_f(x) \
3425 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : \
3426 RB_BIGNUM_TYPE_P(x) ? big2dbl_without_to_f(x) : \
3427 (Check_Type(x, T_FLOAT), RFLOAT_VALUE(x)))
3428 static inline double
3429 rat2dbl_without_to_f(VALUE x)
3431 VALUE num = rb_rational_num(x);
3432 VALUE den = rb_rational_den(x);
3433 return num2dbl_without_to_f(num) / num2dbl_without_to_f(den);
3436 #define special_const_to_float(val, pre, post) \
3437 switch (val) { \
3438 case Qnil: \
3439 rb_raise_static(rb_eTypeError, pre "nil" post); \
3440 case Qtrue: \
3441 rb_raise_static(rb_eTypeError, pre "true" post); \
3442 case Qfalse: \
3443 rb_raise_static(rb_eTypeError, pre "false" post); \
3445 /*! \endcond */
3447 static inline void
3448 conversion_to_float(VALUE val)
3450 special_const_to_float(val, "can't convert ", " into Float");
3453 static inline void
3454 implicit_conversion_to_float(VALUE val)
3456 special_const_to_float(val, "no implicit conversion to float from ", "");
3459 static int
3460 to_float(VALUE *valp, int raise_exception)
3462 VALUE val = *valp;
3463 if (SPECIAL_CONST_P(val)) {
3464 if (FIXNUM_P(val)) {
3465 *valp = DBL2NUM(fix2dbl_without_to_f(val));
3466 return T_FLOAT;
3468 else if (FLONUM_P(val)) {
3469 return T_FLOAT;
3471 else if (raise_exception) {
3472 conversion_to_float(val);
3475 else {
3476 int type = BUILTIN_TYPE(val);
3477 switch (type) {
3478 case T_FLOAT:
3479 return T_FLOAT;
3480 case T_BIGNUM:
3481 *valp = DBL2NUM(big2dbl_without_to_f(val));
3482 return T_FLOAT;
3483 case T_RATIONAL:
3484 *valp = DBL2NUM(rat2dbl_without_to_f(val));
3485 return T_FLOAT;
3486 case T_STRING:
3487 return T_STRING;
3490 return T_NONE;
3493 static VALUE
3494 convert_type_to_float_protected(VALUE val)
3496 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3499 static VALUE
3500 rb_convert_to_float(VALUE val, int raise_exception)
3502 switch (to_float(&val, raise_exception)) {
3503 case T_FLOAT:
3504 return val;
3505 case T_STRING:
3506 if (!raise_exception) {
3507 int e = 0;
3508 double x = rb_str_to_dbl_raise(val, TRUE, raise_exception, &e);
3509 return e ? Qnil : DBL2NUM(x);
3511 return DBL2NUM(rb_str_to_dbl(val, TRUE));
3512 case T_NONE:
3513 if (SPECIAL_CONST_P(val) && !raise_exception)
3514 return Qnil;
3517 if (!raise_exception) {
3518 int state;
3519 VALUE result = rb_protect(convert_type_to_float_protected, val, &state);
3520 if (state) rb_set_errinfo(Qnil);
3521 return result;
3524 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3527 FUNC_MINIMIZED(VALUE rb_Float(VALUE val));
3529 VALUE
3530 rb_Float(VALUE val)
3532 return rb_convert_to_float(val, TRUE);
3535 static VALUE
3536 rb_f_float1(rb_execution_context_t *ec, VALUE obj, VALUE arg)
3538 return rb_convert_to_float(arg, TRUE);
3541 static VALUE
3542 rb_f_float(rb_execution_context_t *ec, VALUE obj, VALUE arg, VALUE opts)
3544 int exception = rb_bool_expected(opts, "exception");
3545 return rb_convert_to_float(arg, exception);
3548 static VALUE
3549 numeric_to_float(VALUE val)
3551 if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3552 rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into Float",
3553 rb_obj_class(val));
3555 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3558 VALUE
3559 rb_to_float(VALUE val)
3561 switch (to_float(&val, TRUE)) {
3562 case T_FLOAT:
3563 return val;
3565 return numeric_to_float(val);
3568 VALUE
3569 rb_check_to_float(VALUE val)
3571 if (RB_FLOAT_TYPE_P(val)) return val;
3572 if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3573 return Qnil;
3575 return rb_check_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3578 static inline int
3579 basic_to_f_p(VALUE klass)
3581 return rb_method_basic_definition_p(klass, id_to_f);
3584 /*! \private */
3585 double
3586 rb_num_to_dbl(VALUE val)
3588 if (SPECIAL_CONST_P(val)) {
3589 if (FIXNUM_P(val)) {
3590 if (basic_to_f_p(rb_cInteger))
3591 return fix2dbl_without_to_f(val);
3593 else if (FLONUM_P(val)) {
3594 return rb_float_flonum_value(val);
3596 else {
3597 conversion_to_float(val);
3600 else {
3601 switch (BUILTIN_TYPE(val)) {
3602 case T_FLOAT:
3603 return rb_float_noflonum_value(val);
3604 case T_BIGNUM:
3605 if (basic_to_f_p(rb_cInteger))
3606 return big2dbl_without_to_f(val);
3607 break;
3608 case T_RATIONAL:
3609 if (basic_to_f_p(rb_cRational))
3610 return rat2dbl_without_to_f(val);
3611 break;
3612 default:
3613 break;
3616 val = numeric_to_float(val);
3617 return RFLOAT_VALUE(val);
3620 double
3621 rb_num2dbl(VALUE val)
3623 if (SPECIAL_CONST_P(val)) {
3624 if (FIXNUM_P(val)) {
3625 return fix2dbl_without_to_f(val);
3627 else if (FLONUM_P(val)) {
3628 return rb_float_flonum_value(val);
3630 else {
3631 implicit_conversion_to_float(val);
3634 else {
3635 switch (BUILTIN_TYPE(val)) {
3636 case T_FLOAT:
3637 return rb_float_noflonum_value(val);
3638 case T_BIGNUM:
3639 return big2dbl_without_to_f(val);
3640 case T_RATIONAL:
3641 return rat2dbl_without_to_f(val);
3642 case T_STRING:
3643 rb_raise(rb_eTypeError, "no implicit conversion to float from string");
3644 default:
3645 break;
3648 val = rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3649 return RFLOAT_VALUE(val);
3652 VALUE
3653 rb_String(VALUE val)
3655 VALUE tmp = rb_check_string_type(val);
3656 if (NIL_P(tmp))
3657 tmp = rb_convert_type_with_id(val, T_STRING, "String", idTo_s);
3658 return tmp;
3663 * call-seq:
3664 * String(arg) -> string
3666 * Returns <i>arg</i> as a String.
3668 * First tries to call its <code>to_str</code> method, then its <code>to_s</code> method.
3670 * String(self) #=> "main"
3671 * String(self.class) #=> "Object"
3672 * String(123456) #=> "123456"
3675 static VALUE
3676 rb_f_string(VALUE obj, VALUE arg)
3678 return rb_String(arg);
3681 VALUE
3682 rb_Array(VALUE val)
3684 VALUE tmp = rb_check_array_type(val);
3686 if (NIL_P(tmp)) {
3687 tmp = rb_check_to_array(val);
3688 if (NIL_P(tmp)) {
3689 return rb_ary_new3(1, val);
3692 return tmp;
3696 * call-seq:
3697 * Array(arg) -> array
3699 * Returns +arg+ as an Array.
3701 * First tries to call <code>to_ary</code> on +arg+, then <code>to_a</code>.
3702 * If +arg+ does not respond to <code>to_ary</code> or <code>to_a</code>,
3703 * returns an Array of length 1 containing +arg+.
3705 * If <code>to_ary</code> or <code>to_a</code> returns something other than
3706 * an Array, raises a TypeError.
3708 * Array(["a", "b"]) #=> ["a", "b"]
3709 * Array(1..5) #=> [1, 2, 3, 4, 5]
3710 * Array(key: :value) #=> [[:key, :value]]
3711 * Array(nil) #=> []
3712 * Array(1) #=> [1]
3715 static VALUE
3716 rb_f_array(VALUE obj, VALUE arg)
3718 return rb_Array(arg);
3722 * Equivalent to \c Kernel\#Hash in Ruby
3724 VALUE
3725 rb_Hash(VALUE val)
3727 VALUE tmp;
3729 if (NIL_P(val)) return rb_hash_new();
3730 tmp = rb_check_hash_type(val);
3731 if (NIL_P(tmp)) {
3732 if (RB_TYPE_P(val, T_ARRAY) && RARRAY_LEN(val) == 0)
3733 return rb_hash_new();
3734 rb_raise(rb_eTypeError, "can't convert %s into Hash", rb_obj_classname(val));
3736 return tmp;
3740 * call-seq:
3741 * Hash(arg) -> hash
3743 * Converts <i>arg</i> to a Hash by calling
3744 * <i>arg</i><code>.to_hash</code>. Returns an empty Hash when
3745 * <i>arg</i> is <tt>nil</tt> or <tt>[]</tt>.
3747 * Hash([]) #=> {}
3748 * Hash(nil) #=> {}
3749 * Hash(key: :value) #=> {:key => :value}
3750 * Hash([1, 2, 3]) #=> TypeError
3753 static VALUE
3754 rb_f_hash(VALUE obj, VALUE arg)
3756 return rb_Hash(arg);
3759 /*! \private */
3760 struct dig_method {
3761 VALUE klass;
3762 int basic;
3765 static ID id_dig;
3767 static int
3768 dig_basic_p(VALUE obj, struct dig_method *cache)
3770 VALUE klass = RBASIC_CLASS(obj);
3771 if (klass != cache->klass) {
3772 cache->klass = klass;
3773 cache->basic = rb_method_basic_definition_p(klass, id_dig);
3775 return cache->basic;
3778 static void
3779 no_dig_method(int found, VALUE recv, ID mid, int argc, const VALUE *argv, VALUE data)
3781 if (!found) {
3782 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not have #dig method",
3783 CLASS_OF(data));
3787 /*! \private */
3788 VALUE
3789 rb_obj_dig(int argc, VALUE *argv, VALUE obj, VALUE notfound)
3791 struct dig_method hash = {Qnil}, ary = {Qnil}, strt = {Qnil};
3793 for (; argc > 0; ++argv, --argc) {
3794 if (NIL_P(obj)) return notfound;
3795 if (!SPECIAL_CONST_P(obj)) {
3796 switch (BUILTIN_TYPE(obj)) {
3797 case T_HASH:
3798 if (dig_basic_p(obj, &hash)) {
3799 obj = rb_hash_aref(obj, *argv);
3800 continue;
3802 break;
3803 case T_ARRAY:
3804 if (dig_basic_p(obj, &ary)) {
3805 obj = rb_ary_at(obj, *argv);
3806 continue;
3808 break;
3809 case T_STRUCT:
3810 if (dig_basic_p(obj, &strt)) {
3811 obj = rb_struct_lookup(obj, *argv);
3812 continue;
3814 break;
3815 default:
3816 break;
3819 return rb_check_funcall_with_hook_kw(obj, id_dig, argc, argv,
3820 no_dig_method, obj,
3821 RB_NO_KEYWORDS);
3823 return obj;
3827 * call-seq:
3828 * format(format_string [, arguments...] ) -> string
3829 * sprintf(format_string [, arguments...] ) -> string
3831 * Returns the string resulting from applying <i>format_string</i> to
3832 * any additional arguments. Within the format string, any characters
3833 * other than format sequences are copied to the result.
3835 * The syntax of a format sequence is as follows.
3837 * %[flags][width][.precision]type
3839 * A format
3840 * sequence consists of a percent sign, followed by optional flags,
3841 * width, and precision indicators, then terminated with a field type
3842 * character. The field type controls how the corresponding
3843 * <code>sprintf</code> argument is to be interpreted, while the flags
3844 * modify that interpretation.
3846 * The field type characters are:
3848 * Field | Integer Format
3849 * ------+--------------------------------------------------------------
3850 * b | Convert argument as a binary number.
3851 * | Negative numbers will be displayed as a two's complement
3852 * | prefixed with `..1'.
3853 * B | Equivalent to `b', but uses an uppercase 0B for prefix
3854 * | in the alternative format by #.
3855 * d | Convert argument as a decimal number.
3856 * i | Identical to `d'.
3857 * o | Convert argument as an octal number.
3858 * | Negative numbers will be displayed as a two's complement
3859 * | prefixed with `..7'.
3860 * u | Identical to `d'.
3861 * x | Convert argument as a hexadecimal number.
3862 * | Negative numbers will be displayed as a two's complement
3863 * | prefixed with `..f' (representing an infinite string of
3864 * | leading 'ff's).
3865 * X | Equivalent to `x', but uses uppercase letters.
3867 * Field | Float Format
3868 * ------+--------------------------------------------------------------
3869 * e | Convert floating point argument into exponential notation
3870 * | with one digit before the decimal point as [-]d.dddddde[+-]dd.
3871 * | The precision specifies the number of digits after the decimal
3872 * | point (defaulting to six).
3873 * E | Equivalent to `e', but uses an uppercase E to indicate
3874 * | the exponent.
3875 * f | Convert floating point argument as [-]ddd.dddddd,
3876 * | where the precision specifies the number of digits after
3877 * | the decimal point.
3878 * g | Convert a floating point number using exponential form
3879 * | if the exponent is less than -4 or greater than or
3880 * | equal to the precision, or in dd.dddd form otherwise.
3881 * | The precision specifies the number of significant digits.
3882 * G | Equivalent to `g', but use an uppercase `E' in exponent form.
3883 * a | Convert floating point argument as [-]0xh.hhhhp[+-]dd,
3884 * | which is consisted from optional sign, "0x", fraction part
3885 * | as hexadecimal, "p", and exponential part as decimal.
3886 * A | Equivalent to `a', but use uppercase `X' and `P'.
3888 * Field | Other Format
3889 * ------+--------------------------------------------------------------
3890 * c | Argument is the numeric code for a single character or
3891 * | a single character string itself.
3892 * p | The valuing of argument.inspect.
3893 * s | Argument is a string to be substituted. If the format
3894 * | sequence contains a precision, at most that many characters
3895 * | will be copied.
3896 * % | A percent sign itself will be displayed. No argument taken.
3898 * The flags modifies the behavior of the formats.
3899 * The flag characters are:
3901 * Flag | Applies to | Meaning
3902 * ---------+---------------+-----------------------------------------
3903 * space | bBdiouxX | Leave a space at the start of
3904 * | aAeEfgG | non-negative numbers.
3905 * | (numeric fmt) | For `o', `x', `X', `b' and `B', use
3906 * | | a minus sign with absolute value for
3907 * | | negative values.
3908 * ---------+---------------+-----------------------------------------
3909 * (digit)$ | all | Specifies the absolute argument number
3910 * | | for this field. Absolute and relative
3911 * | | argument numbers cannot be mixed in a
3912 * | | sprintf string.
3913 * ---------+---------------+-----------------------------------------
3914 * # | bBoxX | Use an alternative format.
3915 * | aAeEfgG | For the conversions `o', increase the precision
3916 * | | until the first digit will be `0' if
3917 * | | it is not formatted as complements.
3918 * | | For the conversions `x', `X', `b' and `B'
3919 * | | on non-zero, prefix the result with ``0x'',
3920 * | | ``0X'', ``0b'' and ``0B'', respectively.
3921 * | | For `a', `A', `e', `E', `f', `g', and 'G',
3922 * | | force a decimal point to be added,
3923 * | | even if no digits follow.
3924 * | | For `g' and 'G', do not remove trailing zeros.
3925 * ---------+---------------+-----------------------------------------
3926 * + | bBdiouxX | Add a leading plus sign to non-negative
3927 * | aAeEfgG | numbers.
3928 * | (numeric fmt) | For `o', `x', `X', `b' and `B', use
3929 * | | a minus sign with absolute value for
3930 * | | negative values.
3931 * ---------+---------------+-----------------------------------------
3932 * - | all | Left-justify the result of this conversion.
3933 * ---------+---------------+-----------------------------------------
3934 * 0 (zero) | bBdiouxX | Pad with zeros, not spaces.
3935 * | aAeEfgG | For `o', `x', `X', `b' and `B', radix-1
3936 * | (numeric fmt) | is used for negative numbers formatted as
3937 * | | complements.
3938 * ---------+---------------+-----------------------------------------
3939 * * | all | Use the next argument as the field width.
3940 * | | If negative, left-justify the result. If the
3941 * | | asterisk is followed by a number and a dollar
3942 * | | sign, use the indicated argument as the width.
3944 * Examples of flags:
3946 * # `+' and space flag specifies the sign of non-negative numbers.
3947 * sprintf("%d", 123) #=> "123"
3948 * sprintf("%+d", 123) #=> "+123"
3949 * sprintf("% d", 123) #=> " 123"
3951 * # `#' flag for `o' increases number of digits to show `0'.
3952 * # `+' and space flag changes format of negative numbers.
3953 * sprintf("%o", 123) #=> "173"
3954 * sprintf("%#o", 123) #=> "0173"
3955 * sprintf("%+o", -123) #=> "-173"
3956 * sprintf("%o", -123) #=> "..7605"
3957 * sprintf("%#o", -123) #=> "..7605"
3959 * # `#' flag for `x' add a prefix `0x' for non-zero numbers.
3960 * # `+' and space flag disables complements for negative numbers.
3961 * sprintf("%x", 123) #=> "7b"
3962 * sprintf("%#x", 123) #=> "0x7b"
3963 * sprintf("%+x", -123) #=> "-7b"
3964 * sprintf("%x", -123) #=> "..f85"
3965 * sprintf("%#x", -123) #=> "0x..f85"
3966 * sprintf("%#x", 0) #=> "0"
3968 * # `#' for `X' uses the prefix `0X'.
3969 * sprintf("%X", 123) #=> "7B"
3970 * sprintf("%#X", 123) #=> "0X7B"
3972 * # `#' flag for `b' add a prefix `0b' for non-zero numbers.
3973 * # `+' and space flag disables complements for negative numbers.
3974 * sprintf("%b", 123) #=> "1111011"
3975 * sprintf("%#b", 123) #=> "0b1111011"
3976 * sprintf("%+b", -123) #=> "-1111011"
3977 * sprintf("%b", -123) #=> "..10000101"
3978 * sprintf("%#b", -123) #=> "0b..10000101"
3979 * sprintf("%#b", 0) #=> "0"
3981 * # `#' for `B' uses the prefix `0B'.
3982 * sprintf("%B", 123) #=> "1111011"
3983 * sprintf("%#B", 123) #=> "0B1111011"
3985 * # `#' for `e' forces to show the decimal point.
3986 * sprintf("%.0e", 1) #=> "1e+00"
3987 * sprintf("%#.0e", 1) #=> "1.e+00"
3989 * # `#' for `f' forces to show the decimal point.
3990 * sprintf("%.0f", 1234) #=> "1234"
3991 * sprintf("%#.0f", 1234) #=> "1234."
3993 * # `#' for `g' forces to show the decimal point.
3994 * # It also disables stripping lowest zeros.
3995 * sprintf("%g", 123.4) #=> "123.4"
3996 * sprintf("%#g", 123.4) #=> "123.400"
3997 * sprintf("%g", 123456) #=> "123456"
3998 * sprintf("%#g", 123456) #=> "123456."
4000 * The field width is an optional integer, followed optionally by a
4001 * period and a precision. The width specifies the minimum number of
4002 * characters that will be written to the result for this field.
4004 * Examples of width:
4006 * # padding is done by spaces, width=20
4007 * # 0 or radix-1. <------------------>
4008 * sprintf("%20d", 123) #=> " 123"
4009 * sprintf("%+20d", 123) #=> " +123"
4010 * sprintf("%020d", 123) #=> "00000000000000000123"
4011 * sprintf("%+020d", 123) #=> "+0000000000000000123"
4012 * sprintf("% 020d", 123) #=> " 0000000000000000123"
4013 * sprintf("%-20d", 123) #=> "123 "
4014 * sprintf("%-+20d", 123) #=> "+123 "
4015 * sprintf("%- 20d", 123) #=> " 123 "
4016 * sprintf("%020x", -123) #=> "..ffffffffffffffff85"
4018 * For
4019 * numeric fields, the precision controls the number of decimal places
4020 * displayed. For string fields, the precision determines the maximum
4021 * number of characters to be copied from the string. (Thus, the format
4022 * sequence <code>%10.10s</code> will always contribute exactly ten
4023 * characters to the result.)
4025 * Examples of precisions:
4027 * # precision for `d', 'o', 'x' and 'b' is
4028 * # minimum number of digits <------>
4029 * sprintf("%20.8d", 123) #=> " 00000123"
4030 * sprintf("%20.8o", 123) #=> " 00000173"
4031 * sprintf("%20.8x", 123) #=> " 0000007b"
4032 * sprintf("%20.8b", 123) #=> " 01111011"
4033 * sprintf("%20.8d", -123) #=> " -00000123"
4034 * sprintf("%20.8o", -123) #=> " ..777605"
4035 * sprintf("%20.8x", -123) #=> " ..ffff85"
4036 * sprintf("%20.8b", -11) #=> " ..110101"
4038 * # "0x" and "0b" for `#x' and `#b' is not counted for
4039 * # precision but "0" for `#o' is counted. <------>
4040 * sprintf("%#20.8d", 123) #=> " 00000123"
4041 * sprintf("%#20.8o", 123) #=> " 00000173"
4042 * sprintf("%#20.8x", 123) #=> " 0x0000007b"
4043 * sprintf("%#20.8b", 123) #=> " 0b01111011"
4044 * sprintf("%#20.8d", -123) #=> " -00000123"
4045 * sprintf("%#20.8o", -123) #=> " ..777605"
4046 * sprintf("%#20.8x", -123) #=> " 0x..ffff85"
4047 * sprintf("%#20.8b", -11) #=> " 0b..110101"
4049 * # precision for `e' is number of
4050 * # digits after the decimal point <------>
4051 * sprintf("%20.8e", 1234.56789) #=> " 1.23456789e+03"
4053 * # precision for `f' is number of
4054 * # digits after the decimal point <------>
4055 * sprintf("%20.8f", 1234.56789) #=> " 1234.56789000"
4057 * # precision for `g' is number of
4058 * # significant digits <------->
4059 * sprintf("%20.8g", 1234.56789) #=> " 1234.5679"
4061 * # <------->
4062 * sprintf("%20.8g", 123456789) #=> " 1.2345679e+08"
4064 * # precision for `s' is
4065 * # maximum number of characters <------>
4066 * sprintf("%20.8s", "string test") #=> " string t"
4068 * Examples:
4070 * sprintf("%d %04x", 123, 123) #=> "123 007b"
4071 * sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'"
4072 * sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello"
4073 * sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8"
4074 * sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23"
4075 * sprintf("%u", -123) #=> "-123"
4077 * For more complex formatting, Ruby supports a reference by name.
4078 * %<name>s style uses format style, but %{name} style doesn't.
4080 * Examples:
4081 * sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 })
4082 * #=> 1 : 2.000000
4083 * sprintf("%{foo}f", { :foo => 1 })
4084 * # => "1f"
4087 static VALUE
4088 f_sprintf(int c, const VALUE *v, VALUE _)
4090 return rb_f_sprintf(c, v);
4094 * Document-class: Class
4096 * Classes in Ruby are first-class objects---each is an instance of
4097 * class Class.
4099 * Typically, you create a new class by using:
4101 * class Name
4102 * # some code describing the class behavior
4103 * end
4105 * When a new class is created, an object of type Class is initialized and
4106 * assigned to a global constant (Name in this case).
4108 * When <code>Name.new</code> is called to create a new object, the
4109 * #new method in Class is run by default.
4110 * This can be demonstrated by overriding #new in Class:
4112 * class Class
4113 * alias old_new new
4114 * def new(*args)
4115 * print "Creating a new ", self.name, "\n"
4116 * old_new(*args)
4117 * end
4118 * end
4120 * class Name
4121 * end
4123 * n = Name.new
4125 * <em>produces:</em>
4127 * Creating a new Name
4129 * Classes, modules, and objects are interrelated. In the diagram
4130 * that follows, the vertical arrows represent inheritance, and the
4131 * parentheses metaclasses. All metaclasses are instances
4132 * of the class `Class'.
4133 * +---------+ +-...
4134 * | | |
4135 * BasicObject-----|-->(BasicObject)-------|-...
4136 * ^ | ^ |
4137 * | | | |
4138 * Object---------|----->(Object)---------|-...
4139 * ^ | ^ |
4140 * | | | |
4141 * +-------+ | +--------+ |
4142 * | | | | | |
4143 * | Module-|---------|--->(Module)-|-...
4144 * | ^ | | ^ |
4145 * | | | | | |
4146 * | Class-|---------|---->(Class)-|-...
4147 * | ^ | | ^ |
4148 * | +---+ | +----+
4149 * | |
4150 * obj--->OtherClass---------->(OtherClass)-----------...
4155 /* Document-class: BasicObject
4157 * BasicObject is the parent class of all classes in Ruby. It's an explicit
4158 * blank class.
4160 * BasicObject can be used for creating object hierarchies independent of
4161 * Ruby's object hierarchy, proxy objects like the Delegator class, or other
4162 * uses where namespace pollution from Ruby's methods and classes must be
4163 * avoided.
4165 * To avoid polluting BasicObject for other users an appropriately named
4166 * subclass of BasicObject should be created instead of directly modifying
4167 * BasicObject:
4169 * class MyObjectSystem < BasicObject
4170 * end
4172 * BasicObject does not include Kernel (for methods like +puts+) and
4173 * BasicObject is outside of the namespace of the standard library so common
4174 * classes will not be found without using a full class path.
4176 * A variety of strategies can be used to provide useful portions of the
4177 * standard library to subclasses of BasicObject. A subclass could
4178 * <code>include Kernel</code> to obtain +puts+, +exit+, etc. A custom
4179 * Kernel-like module could be created and included or delegation can be used
4180 * via #method_missing:
4182 * class MyObjectSystem < BasicObject
4183 * DELEGATE = [:puts, :p]
4185 * def method_missing(name, *args, &block)
4186 * return super unless DELEGATE.include? name
4187 * ::Kernel.send(name, *args, &block)
4188 * end
4190 * def respond_to_missing?(name, include_private = false)
4191 * DELEGATE.include?(name) or super
4192 * end
4193 * end
4195 * Access to classes and modules from the Ruby standard library can be
4196 * obtained in a BasicObject subclass by referencing the desired constant
4197 * from the root like <code>::File</code> or <code>::Enumerator</code>.
4198 * Like #method_missing, #const_missing can be used to delegate constant
4199 * lookup to +Object+:
4201 * class MyObjectSystem < BasicObject
4202 * def self.const_missing(name)
4203 * ::Object.const_get(name)
4204 * end
4205 * end
4207 * === What's Here
4209 * These are the methods defined for \BasicObject:
4211 * - ::new:: Returns a new \BasicObject instance.
4212 * - {!}[#method-i-21]:: Returns the boolean negation of +self+: +true+ or +false+.
4213 * - {!=}[#method-i-21-3D]:: Returns whether +self+ and the given object
4214 * are _not_ equal.
4215 * - {==}[#method-i-3D-3D]:: Returns whether +self+ and the given object
4216 * are equivalent.
4217 * - {__id__}[#method-i-__id__]:: Returns the integer object identifier for +self+.
4218 * - {__send__}[#method-i-__send__]:: Calls the method identified by the given symbol.
4219 * - #equal?:: Returns whether +self+ and the given object are the same object.
4220 * - #instance_eval:: Evaluates the given string or block in the context of +self+.
4221 * - #instance_exec:: Executes the given block in the context of +self+,
4222 * passing the given arguments.
4223 * - #method_missing:: Method called when an undefined method is called on +self+.
4224 * - #singleton_method_added:: Method called when a singleton method
4225 * is added to +self+.
4226 * - #singleton_method_removed:: Method called when a singleton method
4227 * is added removed from +self+.
4228 * - #singleton_method_undefined:: Method called when a singleton method
4229 * is undefined in +self+.
4233 /* Document-class: Object
4235 * Object is the default root of all Ruby objects. Object inherits from
4236 * BasicObject which allows creating alternate object hierarchies. Methods
4237 * on Object are available to all classes unless explicitly overridden.
4239 * Object mixes in the Kernel module, making the built-in kernel functions
4240 * globally accessible. Although the instance methods of Object are defined
4241 * by the Kernel module, we have chosen to document them here for clarity.
4243 * When referencing constants in classes inheriting from Object you do not
4244 * need to use the full namespace. For example, referencing +File+ inside
4245 * +YourClass+ will find the top-level File class.
4247 * In the descriptions of Object's methods, the parameter <i>symbol</i> refers
4248 * to a symbol, which is either a quoted string or a Symbol (such as
4249 * <code>:name</code>).
4251 * == What's Here
4253 * First, what's elsewhere. \Class \Object:
4255 * - Inherits from {class BasicObject}[BasicObject.html#class-BasicObject-label-What-27s+Here].
4256 * - Includes {module Kernel}[Kernel.html#module-Kernel-label-What-27s+Here].
4258 * Here, class \Object provides methods for:
4260 * - {Querying}[#class-Object-label-Querying]
4261 * - {Instance Variables}[#class-Object-label-Instance+Variables]
4262 * - {Other}[#class-Object-label-Other]
4264 * === Querying
4266 * - {!~}[#method-i-21~]:: Returns +true+ if +self+ does not match the given object,
4267 * otherwise +false+.
4268 * - {<=>}[#method-i-3C-3D-3E]:: Returns 0 if +self+ and the given object +object+
4269 * are the same object, or if
4270 * <tt>self == object</tt>; otherwise returns +nil+.
4271 * - #===:: Implements case equality, effectively the same as calling #==.
4272 * - #eql?:: Implements hash equality, effectively the same as calling #==.
4273 * - #kind_of? (aliased as #is_a?):: Returns whether given argument is an ancestor
4274 * of the singleton class of +self+.
4275 * - #instance_of?:: Returns whether +self+ is an instance of the given class.
4276 * - #instance_variable_defined?:: Returns whether the given instance variable
4277 * is defined in +self+.
4278 * - #method:: Returns the Method object for the given method in +self+.
4279 * - #methods:: Returns an array of symbol names of public and protected methods
4280 * in +self+.
4281 * - #nil?:: Returns +false+. (Only +nil+ responds +true+ to method <tt>nil?</tt>.)
4282 * - #object_id:: Returns an integer corresponding to +self+ that is unique
4283 * for the current process
4284 * - #private_methods:: Returns an array of the symbol names
4285 * of the private methods in +self+.
4286 * - #protected_methods:: Returns an array of the symbol names
4287 * of the protected methods in +self+.
4288 * - #public_method:: Returns the Method object for the given public method in +self+.
4289 * - #public_methods:: Returns an array of the symbol names
4290 * of the public methods in +self+.
4291 * - #respond_to?:: Returns whether +self+ responds to the given method.
4292 * - #singleton_class:: Returns the singleton class of +self+.
4293 * - #singleton_method:: Returns the Method object for the given singleton method
4294 * in +self+.
4295 * - #singleton_methods:: Returns an array of the symbol names
4296 * of the singleton methods in +self+.
4298 * - #define_singleton_method:: Defines a singleton method in +self+
4299 * for the given symbol method-name and block or proc.
4300 * - #extend:: Includes the given modules in the singleton class of +self+.
4301 * - #public_send:: Calls the given public method in +self+ with the given argument.
4302 * - #send:: Calls the given method in +self+ with the given argument.
4304 * === Instance Variables
4306 * - #instance_variable_get:: Returns the value of the given instance variable
4307 * in +self+, or +nil+ if the instance variable is not set.
4308 * - #instance_variable_set:: Sets the value of the given instance variable in +self+
4309 * to the given object.
4310 * - #instance_variables:: Returns an array of the symbol names
4311 * of the instance variables in +self+.
4312 * - #remove_instance_variable:: Removes the named instance variable from +self+.
4314 * === Other
4316 * - #clone:: Returns a shallow copy of +self+, including singleton class
4317 * and frozen state.
4318 * - #define_singleton_method:: Defines a singleton method in +self+
4319 * for the given symbol method-name and block or proc.
4320 * - #display:: Prints +self+ to the given \IO stream or <tt>$stdout</tt>.
4321 * - #dup:: Returns a shallow unfrozen copy of +self+.
4322 * - #enum_for (aliased as #to_enum):: Returns an Enumerator for +self+
4323 * using the using the given method,
4324 * arguments, and block.
4325 * - #extend:: Includes the given modules in the singleton class of +self+.
4326 * - #freeze:: Prevents further modifications to +self+.
4327 * - #hash:: Returns the integer hash value for +self+.
4328 * - #inspect:: Returns a human-readable string representation of +self+.
4329 * - #itself:: Returns +self+.
4330 * - #public_send:: Calls the given public method in +self+ with the given argument.
4331 * - #send:: Calls the given method in +self+ with the given argument.
4332 * - #to_s:: Returns a string representation of +self+.
4338 * \private
4339 * Initializes the world of objects and classes.
4341 * At first, the function bootstraps the class hierarchy.
4342 * It initializes the most fundamental classes and their metaclasses.
4343 * - \c BasicObject
4344 * - \c Object
4345 * - \c Module
4346 * - \c Class
4347 * After the bootstrap step, the class hierarchy becomes as the following
4348 * diagram.
4350 * \image html boottime-classes.png
4352 * Then, the function defines classes, modules and methods as usual.
4353 * \ingroup class
4357 void
4358 InitVM_Object(void)
4360 Init_class_hierarchy();
4362 #if 0
4363 // teach RDoc about these classes
4364 rb_cBasicObject = rb_define_class("BasicObject", Qnil);
4365 rb_cObject = rb_define_class("Object", rb_cBasicObject);
4366 rb_cModule = rb_define_class("Module", rb_cObject);
4367 rb_cClass = rb_define_class("Class", rb_cModule);
4368 rb_cRefinement = rb_define_class("Refinement", rb_cModule);
4369 #endif
4371 rb_define_private_method(rb_cBasicObject, "initialize", rb_obj_initialize, 0);
4372 rb_define_alloc_func(rb_cBasicObject, rb_class_allocate_instance);
4373 rb_define_method(rb_cBasicObject, "==", rb_obj_equal, 1);
4374 rb_define_method(rb_cBasicObject, "equal?", rb_obj_equal, 1);
4375 rb_define_method(rb_cBasicObject, "!", rb_obj_not, 0);
4376 rb_define_method(rb_cBasicObject, "!=", rb_obj_not_equal, 1);
4378 rb_define_private_method(rb_cBasicObject, "singleton_method_added", rb_obj_singleton_method_added, 1);
4379 rb_define_private_method(rb_cBasicObject, "singleton_method_removed", rb_obj_singleton_method_removed, 1);
4380 rb_define_private_method(rb_cBasicObject, "singleton_method_undefined", rb_obj_singleton_method_undefined, 1);
4382 /* Document-module: Kernel
4384 * The Kernel module is included by class Object, so its methods are
4385 * available in every Ruby object.
4387 * The Kernel instance methods are documented in class Object while the
4388 * module methods are documented here. These methods are called without a
4389 * receiver and thus can be called in functional form:
4391 * sprintf "%.1f", 1.234 #=> "1.2"
4393 * == What's Here
4395 * \Module \Kernel provides methods that are useful for:
4397 * - {Converting}[#module-Kernel-label-Converting]
4398 * - {Querying}[#module-Kernel-label-Querying]
4399 * - {Exiting}[#module-Kernel-label-Exiting]
4400 * - {Exceptions}[#module-Kernel-label-Exceptions]
4401 * - {IO}[#module-Kernel-label-IO]
4402 * - {Procs}[#module-Kernel-label-Procs]
4403 * - {Tracing}[#module-Kernel-label-Tracing]
4404 * - {Subprocesses}[#module-Kernel-label-Subprocesses]
4405 * - {Loading}[#module-Kernel-label-Loading]
4406 * - {Yielding}[#module-Kernel-label-Yielding]
4407 * - {Random Values}[#module-Kernel-label-Random+Values]
4408 * - {Other}[#module-Kernel-label-Other]
4410 * === Converting
4412 * - {#Array}[#method-i-Array]:: Returns an Array based on the given argument.
4413 * - {#Complex}[#method-i-Complex]:: Returns a Complex based on the given arguments.
4414 * - {#Float}[#method-i-Float]:: Returns a Float based on the given arguments.
4415 * - {#Hash}[#method-i-Hash]:: Returns a Hash based on the given argument.
4416 * - {#Integer}[#method-i-Integer]:: Returns an Integer based on the given arguments.
4417 * - {#Rational}[#method-i-Rational]:: Returns a Rational
4418 * based on the given arguments.
4419 * - {#String}[#method-i-String]:: Returns a String based on the given argument.
4421 * === Querying
4423 * - {#__callee__}[#method-i-__callee__]:: Returns the called name
4424 * of the current method as a symbol.
4425 * - {#__dir__}[#method-i-__dir__]:: Returns the path to the directory
4426 * from which the current method is called.
4427 * - {#__method__}[#method-i-__method__]:: Returns the name
4428 * of the current method as a symbol.
4429 * - #autoload?:: Returns the file to be loaded when the given module is referenced.
4430 * - #binding:: Returns a Binding for the context at the point of call.
4431 * - #block_given?:: Returns +true+ if a block was passed to the calling method.
4432 * - #caller:: Returns the current execution stack as an array of strings.
4433 * - #caller_locations:: Returns the current execution stack as an array
4434 * of Thread::Backtrace::Location objects.
4435 * - #class:: Returns the class of +self+.
4436 * - #frozen?:: Returns whether +self+ is frozen.
4437 * - #global_variables:: Returns an array of global variables as symbols.
4438 * - #local_variables:: Returns an array of local variables as symbols.
4439 * - #test:: Performs specified tests on the given single file or pair of files.
4441 * === Exiting
4443 * - #abort:: Exits the current process after printing the given arguments.
4444 * - #at_exit:: Executes the given block when the process exits.
4445 * - #exit:: Exits the current process after calling any registered
4446 * +at_exit+ handlers.
4447 * - #exit!:: Exits the current process without calling any registered
4448 * +at_exit+ handlers.
4450 * === Exceptions
4452 * - #catch:: Executes the given block, possibly catching a thrown object.
4453 * - #raise (aliased as #fail):: Raises an exception based on the given arguments.
4454 * - #throw:: Returns from the active catch block waiting for the given tag.
4457 * === \IO
4459 * - #gets:: Returns and assigns to <tt>$_</tt> the next line from the current input.
4460 * - #open:: Creates an IO object connected to the given stream, file, or subprocess.
4461 * - #p:: Prints the given objects' inspect output to the standard output.
4462 * - #pp:: Prints the given objects in pretty form.
4463 * - #print:: Prints the given objects to standard output without a newline.
4464 * - #printf:: Prints the string resulting from applying the given format string
4465 * to any additional arguments.
4466 * - #putc:: Equivalent to <tt.$stdout.putc(object)</tt> for the given object.
4467 * - #puts:: Equivalent to <tt>$stdout.puts(*objects)</tt> for the given objects.
4468 * - #readline:: Similar to #gets, but raises an exception at the end of file.
4469 * - #readlines:: Returns an array of the remaining lines from the current input.
4470 * - #select:: Same as IO.select.
4472 * === Procs
4474 * - #lambda:: Returns a lambda proc for the given block.
4475 * - #proc:: Returns a new Proc; equivalent to Proc.new.
4477 * === Tracing
4479 * - #set_trace_func:: Sets the given proc as the handler for tracing,
4480 * or disables tracing if given +nil+.
4481 * - #trace_var:: Starts tracing assignments to the given global variable.
4482 * - #untrace_var:: Disables tracing of assignments to the given global variable.
4484 * === Subprocesses
4486 * - #`cmd`:: Returns the standard output of running +cmd+ in a subshell.
4487 * - #exec:: Replaces current process with a new process.
4488 * - #fork:: Forks the current process into two processes.
4489 * - #spawn:: Executes the given command and returns its pid without waiting
4490 * for completion.
4491 * - #system:: Executes the given command in a subshell.
4493 * === Loading
4495 * - #autoload:: Registers the given file to be loaded when the given constant
4496 * is first referenced.
4497 * - #load:: Loads the given Ruby file.
4498 * - #require:: Loads the given Ruby file unless it has already been loaded.
4499 * - #require_relative:: Loads the Ruby file path relative to the calling file,
4500 * unless it has already been loaded.
4502 * === Yielding
4504 * - #tap:: Yields +self+ to the given block; returns +self+.
4505 * - #then (aliased as #yield_self):: Yields +self+ to the block
4506 * and returns the result of the block.
4508 * === \Random Values
4510 * - #rand:: Returns a pseudo-random floating point number
4511 * strictly between 0.0 and 1.0.
4512 * - #srand:: Seeds the pseudo-random number generator with the given number.
4514 * === Other
4516 * - #eval:: Evaluates the given string as Ruby code.
4517 * - #loop:: Repeatedly executes the given block.
4518 * - #sleep:: Suspends the current thread for the given number of seconds.
4519 * - #sprintf (aliased as #format):: Returns the string resulting from applying
4520 * the given format string
4521 * to any additional arguments.
4522 * - #syscall:: Runs an operating system call.
4523 * - #trap:: Specifies the handling of system signals.
4524 * - #warn:: Issue a warning based on the given messages and options.
4527 rb_mKernel = rb_define_module("Kernel");
4528 rb_include_module(rb_cObject, rb_mKernel);
4529 rb_define_private_method(rb_cClass, "inherited", rb_obj_class_inherited, 1);
4530 rb_define_private_method(rb_cModule, "included", rb_obj_mod_included, 1);
4531 rb_define_private_method(rb_cModule, "extended", rb_obj_mod_extended, 1);
4532 rb_define_private_method(rb_cModule, "prepended", rb_obj_mod_prepended, 1);
4533 rb_define_private_method(rb_cModule, "method_added", rb_obj_mod_method_added, 1);
4534 rb_define_private_method(rb_cModule, "method_removed", rb_obj_mod_method_removed, 1);
4535 rb_define_private_method(rb_cModule, "method_undefined", rb_obj_mod_method_undefined, 1);
4537 rb_define_method(rb_mKernel, "nil?", rb_false, 0);
4538 rb_define_method(rb_mKernel, "===", case_equal, 1);
4539 rb_define_method(rb_mKernel, "=~", rb_obj_match, 1);
4540 rb_define_method(rb_mKernel, "!~", rb_obj_not_match, 1);
4541 rb_define_method(rb_mKernel, "eql?", rb_obj_equal, 1);
4542 rb_define_method(rb_mKernel, "hash", rb_obj_hash, 0); /* in hash.c */
4543 rb_define_method(rb_mKernel, "<=>", rb_obj_cmp, 1);
4545 rb_define_method(rb_mKernel, "singleton_class", rb_obj_singleton_class, 0);
4546 rb_define_method(rb_mKernel, "dup", rb_obj_dup, 0);
4547 rb_define_method(rb_mKernel, "itself", rb_obj_itself, 0);
4548 rb_define_method(rb_mKernel, "initialize_copy", rb_obj_init_copy, 1);
4549 rb_define_method(rb_mKernel, "initialize_dup", rb_obj_init_dup_clone, 1);
4550 rb_define_method(rb_mKernel, "initialize_clone", rb_obj_init_clone, -1);
4552 rb_define_method(rb_mKernel, "taint", rb_obj_taint, 0);
4553 rb_define_method(rb_mKernel, "tainted?", rb_obj_tainted, 0);
4554 rb_define_method(rb_mKernel, "untaint", rb_obj_untaint, 0);
4555 rb_define_method(rb_mKernel, "untrust", rb_obj_untrust, 0);
4556 rb_define_method(rb_mKernel, "untrusted?", rb_obj_untrusted, 0);
4557 rb_define_method(rb_mKernel, "trust", rb_obj_trust, 0);
4558 rb_define_method(rb_mKernel, "freeze", rb_obj_freeze, 0);
4560 rb_define_method(rb_mKernel, "to_s", rb_any_to_s, 0);
4561 rb_define_method(rb_mKernel, "inspect", rb_obj_inspect, 0);
4562 rb_define_method(rb_mKernel, "methods", rb_obj_methods, -1); /* in class.c */
4563 rb_define_method(rb_mKernel, "singleton_methods", rb_obj_singleton_methods, -1); /* in class.c */
4564 rb_define_method(rb_mKernel, "protected_methods", rb_obj_protected_methods, -1); /* in class.c */
4565 rb_define_method(rb_mKernel, "private_methods", rb_obj_private_methods, -1); /* in class.c */
4566 rb_define_method(rb_mKernel, "public_methods", rb_obj_public_methods, -1); /* in class.c */
4567 rb_define_method(rb_mKernel, "instance_variables", rb_obj_instance_variables, 0); /* in variable.c */
4568 rb_define_method(rb_mKernel, "instance_variable_get", rb_obj_ivar_get, 1);
4569 rb_define_method(rb_mKernel, "instance_variable_set", rb_obj_ivar_set, 2);
4570 rb_define_method(rb_mKernel, "instance_variable_defined?", rb_obj_ivar_defined, 1);
4571 rb_define_method(rb_mKernel, "remove_instance_variable",
4572 rb_obj_remove_instance_variable, 1); /* in variable.c */
4574 rb_define_method(rb_mKernel, "instance_of?", rb_obj_is_instance_of, 1);
4575 rb_define_method(rb_mKernel, "kind_of?", rb_obj_is_kind_of, 1);
4576 rb_define_method(rb_mKernel, "is_a?", rb_obj_is_kind_of, 1);
4578 rb_define_global_function("sprintf", f_sprintf, -1);
4579 rb_define_global_function("format", f_sprintf, -1);
4581 rb_define_global_function("Integer", rb_f_integer, -1);
4583 rb_define_global_function("String", rb_f_string, 1);
4584 rb_define_global_function("Array", rb_f_array, 1);
4585 rb_define_global_function("Hash", rb_f_hash, 1);
4587 rb_cNilClass = rb_define_class("NilClass", rb_cObject);
4588 rb_cNilClass_to_s = rb_fstring_enc_lit("", rb_usascii_encoding());
4589 rb_gc_register_mark_object(rb_cNilClass_to_s);
4590 rb_define_method(rb_cNilClass, "to_s", rb_nil_to_s, 0);
4591 rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0);
4592 rb_define_method(rb_cNilClass, "to_h", nil_to_h, 0);
4593 rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0);
4594 rb_define_method(rb_cNilClass, "=~", nil_match, 1);
4595 rb_define_method(rb_cNilClass, "&", false_and, 1);
4596 rb_define_method(rb_cNilClass, "|", false_or, 1);
4597 rb_define_method(rb_cNilClass, "^", false_xor, 1);
4598 rb_define_method(rb_cNilClass, "===", case_equal, 1);
4600 rb_define_method(rb_cNilClass, "nil?", rb_true, 0);
4601 rb_undef_alloc_func(rb_cNilClass);
4602 rb_undef_method(CLASS_OF(rb_cNilClass), "new");
4604 rb_define_method(rb_cModule, "freeze", rb_mod_freeze, 0);
4605 rb_define_method(rb_cModule, "===", rb_mod_eqq, 1);
4606 rb_define_method(rb_cModule, "==", rb_obj_equal, 1);
4607 rb_define_method(rb_cModule, "<=>", rb_mod_cmp, 1);
4608 rb_define_method(rb_cModule, "<", rb_mod_lt, 1);
4609 rb_define_method(rb_cModule, "<=", rb_class_inherited_p, 1);
4610 rb_define_method(rb_cModule, ">", rb_mod_gt, 1);
4611 rb_define_method(rb_cModule, ">=", rb_mod_ge, 1);
4612 rb_define_method(rb_cModule, "initialize_copy", rb_mod_init_copy, 1); /* in class.c */
4613 rb_define_method(rb_cModule, "to_s", rb_mod_to_s, 0);
4614 rb_define_alias(rb_cModule, "inspect", "to_s");
4615 rb_define_method(rb_cModule, "included_modules", rb_mod_included_modules, 0); /* in class.c */
4616 rb_define_method(rb_cModule, "include?", rb_mod_include_p, 1); /* in class.c */
4617 rb_define_method(rb_cModule, "name", rb_mod_name, 0); /* in variable.c */
4618 rb_define_method(rb_cModule, "ancestors", rb_mod_ancestors, 0); /* in class.c */
4620 rb_define_method(rb_cModule, "attr", rb_mod_attr, -1);
4621 rb_define_method(rb_cModule, "attr_reader", rb_mod_attr_reader, -1);
4622 rb_define_method(rb_cModule, "attr_writer", rb_mod_attr_writer, -1);
4623 rb_define_method(rb_cModule, "attr_accessor", rb_mod_attr_accessor, -1);
4625 rb_define_alloc_func(rb_cModule, rb_module_s_alloc);
4626 rb_undef_method(rb_singleton_class(rb_cModule), "allocate");
4627 rb_define_method(rb_cModule, "initialize", rb_mod_initialize, 0);
4628 rb_define_method(rb_cModule, "initialize_clone", rb_mod_initialize_clone, -1);
4629 rb_define_method(rb_cModule, "instance_methods", rb_class_instance_methods, -1); /* in class.c */
4630 rb_define_method(rb_cModule, "public_instance_methods",
4631 rb_class_public_instance_methods, -1); /* in class.c */
4632 rb_define_method(rb_cModule, "protected_instance_methods",
4633 rb_class_protected_instance_methods, -1); /* in class.c */
4634 rb_define_method(rb_cModule, "private_instance_methods",
4635 rb_class_private_instance_methods, -1); /* in class.c */
4637 rb_define_method(rb_cModule, "constants", rb_mod_constants, -1); /* in variable.c */
4638 rb_define_method(rb_cModule, "const_get", rb_mod_const_get, -1);
4639 rb_define_method(rb_cModule, "const_set", rb_mod_const_set, 2);
4640 rb_define_method(rb_cModule, "const_defined?", rb_mod_const_defined, -1);
4641 rb_define_method(rb_cModule, "const_source_location", rb_mod_const_source_location, -1);
4642 rb_define_private_method(rb_cModule, "remove_const",
4643 rb_mod_remove_const, 1); /* in variable.c */
4644 rb_define_method(rb_cModule, "const_missing",
4645 rb_mod_const_missing, 1); /* in variable.c */
4646 rb_define_method(rb_cModule, "class_variables",
4647 rb_mod_class_variables, -1); /* in variable.c */
4648 rb_define_method(rb_cModule, "remove_class_variable",
4649 rb_mod_remove_cvar, 1); /* in variable.c */
4650 rb_define_method(rb_cModule, "class_variable_get", rb_mod_cvar_get, 1);
4651 rb_define_method(rb_cModule, "class_variable_set", rb_mod_cvar_set, 2);
4652 rb_define_method(rb_cModule, "class_variable_defined?", rb_mod_cvar_defined, 1);
4653 rb_define_method(rb_cModule, "public_constant", rb_mod_public_constant, -1); /* in variable.c */
4654 rb_define_method(rb_cModule, "private_constant", rb_mod_private_constant, -1); /* in variable.c */
4655 rb_define_method(rb_cModule, "deprecate_constant", rb_mod_deprecate_constant, -1); /* in variable.c */
4656 rb_define_method(rb_cModule, "singleton_class?", rb_mod_singleton_p, 0);
4658 rb_define_method(rb_singleton_class(rb_cClass), "allocate", rb_class_alloc_m, 0);
4659 rb_define_method(rb_cClass, "allocate", rb_class_alloc_m, 0);
4660 rb_define_method(rb_cClass, "new", rb_class_new_instance_pass_kw, -1);
4661 rb_define_method(rb_cClass, "initialize", rb_class_initialize, -1);
4662 rb_define_method(rb_cClass, "superclass", rb_class_superclass, 0);
4663 rb_define_method(rb_cClass, "subclasses", rb_class_subclasses, 0); /* in class.c */
4664 rb_define_alloc_func(rb_cClass, rb_class_s_alloc);
4665 rb_undef_method(rb_cClass, "extend_object");
4666 rb_undef_method(rb_cClass, "append_features");
4667 rb_undef_method(rb_cClass, "prepend_features");
4669 rb_cTrueClass = rb_define_class("TrueClass", rb_cObject);
4670 rb_cTrueClass_to_s = rb_fstring_enc_lit("true", rb_usascii_encoding());
4671 rb_gc_register_mark_object(rb_cTrueClass_to_s);
4672 rb_define_method(rb_cTrueClass, "to_s", rb_true_to_s, 0);
4673 rb_define_alias(rb_cTrueClass, "inspect", "to_s");
4674 rb_define_method(rb_cTrueClass, "&", true_and, 1);
4675 rb_define_method(rb_cTrueClass, "|", true_or, 1);
4676 rb_define_method(rb_cTrueClass, "^", true_xor, 1);
4677 rb_define_method(rb_cTrueClass, "===", case_equal, 1);
4678 rb_undef_alloc_func(rb_cTrueClass);
4679 rb_undef_method(CLASS_OF(rb_cTrueClass), "new");
4681 rb_cFalseClass = rb_define_class("FalseClass", rb_cObject);
4682 rb_cFalseClass_to_s = rb_fstring_enc_lit("false", rb_usascii_encoding());
4683 rb_gc_register_mark_object(rb_cFalseClass_to_s);
4684 rb_define_method(rb_cFalseClass, "to_s", rb_false_to_s, 0);
4685 rb_define_alias(rb_cFalseClass, "inspect", "to_s");
4686 rb_define_method(rb_cFalseClass, "&", false_and, 1);
4687 rb_define_method(rb_cFalseClass, "|", false_or, 1);
4688 rb_define_method(rb_cFalseClass, "^", false_xor, 1);
4689 rb_define_method(rb_cFalseClass, "===", case_equal, 1);
4690 rb_undef_alloc_func(rb_cFalseClass);
4691 rb_undef_method(CLASS_OF(rb_cFalseClass), "new");
4694 #include "kernel.rbinc"
4695 #include "nilclass.rbinc"
4697 void
4698 Init_Object(void)
4700 id_dig = rb_intern_const("dig");
4701 InitVM(Object);
4705 * \}