The Ruby Cross Reference

Implementation: mri jruby rubinius
Version: 1.8.7-p374 1.9.1-p431 1.9.2-p381 1.9.3-p547 2.0.0-p481 2.1.0-p0 2.1.1 2.1.2 HEAD
001 /**********************************************************************
002 
003   object.c -
004 
005   $Author$
006   created at: Thu Jul 15 12:01:24 JST 1993
007 
008   Copyright (C) 1993-2007 Yukihiro Matsumoto
009   Copyright (C) 2000  Network Applied Communication Laboratory, Inc.
010   Copyright (C) 2000  Information-technology Promotion Agency, Japan
011 
012 **********************************************************************/
013 
014 #include "ruby/ruby.h"
015 #include "ruby/st.h"
016 #include "ruby/util.h"
017 #include "ruby/encoding.h"
018 #include <stdio.h>
019 #include <errno.h>
020 #include <ctype.h>
021 #include <math.h>
022 #include <float.h>
023 #include "constant.h"
024 #include "internal.h"
025 #include "id.h"
026 #include "probes.h"
027 
028 VALUE rb_cBasicObject;
029 VALUE rb_mKernel;
030 VALUE rb_cObject;
031 VALUE rb_cModule;
032 VALUE rb_cClass;
033 VALUE rb_cData;
034 
035 VALUE rb_cNilClass;
036 VALUE rb_cTrueClass;
037 VALUE rb_cFalseClass;
038 
039 #define id_eq               idEq
040 #define id_eql              idEqlP
041 #define id_match            idEqTilde
042 #define id_inspect          idInspect
043 #define id_init_copy        idInitialize_copy
044 #define id_init_clone       idInitialize_clone
045 #define id_init_dup         idInitialize_dup
046 #define id_const_missing    idConst_missing
047 
048 #define CLASS_OR_MODULE_P(obj) \
049     (!SPECIAL_CONST_P(obj) && \
050      (BUILTIN_TYPE(obj) == T_CLASS || BUILTIN_TYPE(obj) == T_MODULE))
051 
052 VALUE
053 rb_obj_hide(VALUE obj)
054 {
055     if (!SPECIAL_CONST_P(obj)) {
056         RBASIC_CLEAR_CLASS(obj);
057     }
058     return obj;
059 }
060 
061 VALUE
062 rb_obj_reveal(VALUE obj, VALUE klass)
063 {
064     if (!SPECIAL_CONST_P(obj)) {
065         RBASIC_SET_CLASS(obj, klass);
066     }
067     return obj;
068 }
069 
070 VALUE
071 rb_obj_setup(VALUE obj, VALUE klass, VALUE type)
072 {
073     RBASIC(obj)->flags = type;
074     RBASIC_SET_CLASS(obj, klass);
075     if (rb_safe_level() >= 3) FL_SET((obj), FL_TAINT);
076     return obj;
077 }
078 
079 /*
080  *  call-seq:
081  *     obj === other   -> true or false
082  *
083  *  Case Equality -- For class Object, effectively the same as calling
084  *  <code>#==</code>, but typically overridden by descendants to provide
085  *  meaningful semantics in +case+ statements.
086  */
087 
088 VALUE
089 rb_equal(VALUE obj1, VALUE obj2)
090 {
091     VALUE result;
092 
093     if (obj1 == obj2) return Qtrue;
094     result = rb_funcall(obj1, id_eq, 1, obj2);
095     if (RTEST(result)) return Qtrue;
096     return Qfalse;
097 }
098 
099 int
100 rb_eql(VALUE obj1, VALUE obj2)
101 {
102     return RTEST(rb_funcall(obj1, id_eql, 1, obj2));
103 }
104 
105 /*
106  *  call-seq:
107  *     obj == other        -> true or false
108  *     obj.equal?(other)   -> true or false
109  *     obj.eql?(other)     -> true or false
110  *
111  *  Equality --- At the <code>Object</code> level, <code>==</code> returns
112  *  <code>true</code> only if +obj+ and +other+ are the same object.
113  *  Typically, this method is overridden in descendant classes to provide
114  *  class-specific meaning.
115  *
116  *  Unlike <code>==</code>, the <code>equal?</code> method should never be
117  *  overridden by subclasses as it is used to determine object identity
118  *  (that is, <code>a.equal?(b)</code> if and only if <code>a</code> is the
119  *  same object as <code>b</code>):
120  *
121  *    obj = "a"
122  *    other = obj.dup
123  *
124  *    obj == other      #=> true
125  *    obj.equal? other  #=> false
126  *    obj.equal? obj    #=> true
127  *
128  *  The <code>eql?</code> method returns <code>true</code> if +obj+ and
129  *  +other+ refer to the same hash key.  This is used by Hash to test members
130  *  for equality.  For objects of class <code>Object</code>, <code>eql?</code>
131  *  is synonymous with <code>==</code>.  Subclasses normally continue this
132  *  tradition by aliasing <code>eql?</code> to their overridden <code>==</code>
133  *  method, but there are exceptions.  <code>Numeric</code> types, for
134  *  example, perform type conversion across <code>==</code>, but not across
135  *  <code>eql?</code>, so:
136  *
137  *     1 == 1.0     #=> true
138  *     1.eql? 1.0   #=> false
139  */
140 
141 VALUE
142 rb_obj_equal(VALUE obj1, VALUE obj2)
143 {
144     if (obj1 == obj2) return Qtrue;
145     return Qfalse;
146 }
147 
148 /*
149  * Generates a Fixnum hash value for this object.  This function must have the
150  * property that <code>a.eql?(b)</code> implies <code>a.hash == b.hash</code>.
151  *
152  * The hash value is used along with #eql? by the Hash class to determine if
153  * two objects reference the same hash key.  Any hash value that exceeds the
154  * capacity of a Fixnum will be truncated before being used.
155  *
156  * The hash value for an object may not be identical across invocations or
157  * implementations of ruby.  If you need a stable identifier across ruby
158  * invocations and implementations you will need to generate one with a custom
159  * method.
160  */
161 VALUE
162 rb_obj_hash(VALUE obj)
163 {
164     VALUE oid = rb_obj_id(obj);
165 #if SIZEOF_LONG == SIZEOF_VOIDP
166     st_index_t index = NUM2LONG(oid);
167 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
168     st_index_t index = NUM2LL(oid);
169 #else
170 # error not supported
171 #endif
172     st_index_t h = rb_hash_end(rb_hash_start(index));
173     return LONG2FIX(h);
174 }
175 
176 /*
177  *  call-seq:
178  *     !obj    -> true or false
179  *
180  *  Boolean negate.
181  */
182 
183 VALUE
184 rb_obj_not(VALUE obj)
185 {
186     return RTEST(obj) ? Qfalse : Qtrue;
187 }
188 
189 /*
190  *  call-seq:
191  *     obj != other        -> true or false
192  *
193  *  Returns true if two objects are not-equal, otherwise false.
194  */
195 
196 VALUE
197 rb_obj_not_equal(VALUE obj1, VALUE obj2)
198 {
199     VALUE result = rb_funcall(obj1, id_eq, 1, obj2);
200     return RTEST(result) ? Qfalse : Qtrue;
201 }
202 
203 VALUE
204 rb_class_real(VALUE cl)
205 {
206     if (cl == 0)
207         return 0;
208     while ((RBASIC(cl)->flags & FL_SINGLETON) || BUILTIN_TYPE(cl) == T_ICLASS) {
209         cl = RCLASS_SUPER(cl);
210     }
211     return cl;
212 }
213 
214 /*
215  *  call-seq:
216  *     obj.class    -> class
217  *
218  *  Returns the class of <i>obj</i>. This method must always be
219  *  called with an explicit receiver, as <code>class</code> is also a
220  *  reserved word in Ruby.
221  *
222  *     1.class      #=> Fixnum
223  *     self.class   #=> Object
224  */
225 
226 VALUE
227 rb_obj_class(VALUE obj)
228 {
229     return rb_class_real(CLASS_OF(obj));
230 }
231 
232 /*
233  *  call-seq:
234  *     obj.singleton_class    -> class
235  *
236  *  Returns the singleton class of <i>obj</i>.  This method creates
237  *  a new singleton class if <i>obj</i> does not have it.
238  *
239  *  If <i>obj</i> is <code>nil</code>, <code>true</code>, or
240  *  <code>false</code>, it returns NilClass, TrueClass, or FalseClass,
241  *  respectively.
242  *  If <i>obj</i> is a Fixnum or a Symbol, it raises a TypeError.
243  *
244  *     Object.new.singleton_class  #=> #<Class:#<Object:0xb7ce1e24>>
245  *     String.singleton_class      #=> #<Class:String>
246  *     nil.singleton_class         #=> NilClass
247  */
248 
249 static VALUE
250 rb_obj_singleton_class(VALUE obj)
251 {
252     return rb_singleton_class(obj);
253 }
254 
255 static void
256 init_copy(VALUE dest, VALUE obj)
257 {
258     if (OBJ_FROZEN(dest)) {
259         rb_raise(rb_eTypeError, "[bug] frozen object (%s) allocated", rb_obj_classname(dest));
260     }
261     RBASIC(dest)->flags &= ~(T_MASK|FL_EXIVAR);
262     RBASIC(dest)->flags |= RBASIC(obj)->flags & (T_MASK|FL_EXIVAR|FL_TAINT);
263     rb_copy_generic_ivar(dest, obj);
264     rb_gc_copy_finalizer(dest, obj);
265     switch (TYPE(obj)) {
266       case T_OBJECT:
267         if (!(RBASIC(dest)->flags & ROBJECT_EMBED) && ROBJECT_IVPTR(dest)) {
268             xfree(ROBJECT_IVPTR(dest));
269             ROBJECT(dest)->as.heap.ivptr = 0;
270             ROBJECT(dest)->as.heap.numiv = 0;
271             ROBJECT(dest)->as.heap.iv_index_tbl = 0;
272         }
273         if (RBASIC(obj)->flags & ROBJECT_EMBED) {
274             MEMCPY(ROBJECT(dest)->as.ary, ROBJECT(obj)->as.ary, VALUE, ROBJECT_EMBED_LEN_MAX);
275             RBASIC(dest)->flags |= ROBJECT_EMBED;
276         }
277         else {
278             long len = ROBJECT(obj)->as.heap.numiv;
279             VALUE *ptr = ALLOC_N(VALUE, len);
280             MEMCPY(ptr, ROBJECT(obj)->as.heap.ivptr, VALUE, len);
281             ROBJECT(dest)->as.heap.ivptr = ptr;
282             ROBJECT(dest)->as.heap.numiv = len;
283             ROBJECT(dest)->as.heap.iv_index_tbl = ROBJECT(obj)->as.heap.iv_index_tbl;
284             RBASIC(dest)->flags &= ~ROBJECT_EMBED;
285         }
286         break;
287       case T_CLASS:
288       case T_MODULE:
289         if (RCLASS_IV_TBL(dest)) {
290             st_free_table(RCLASS_IV_TBL(dest));
291             RCLASS_IV_TBL(dest) = 0;
292         }
293         if (RCLASS_CONST_TBL(dest)) {
294             rb_free_const_table(RCLASS_CONST_TBL(dest));
295             RCLASS_CONST_TBL(dest) = 0;
296         }
297         if (RCLASS_IV_TBL(obj)) {
298             RCLASS_IV_TBL(dest) = rb_st_copy(dest, RCLASS_IV_TBL(obj));
299         }
300         break;
301     }
302 }
303 
304 /*
305  *  call-seq:
306  *     obj.clone -> an_object
307  *
308  *  Produces a shallow copy of <i>obj</i>---the instance variables of
309  *  <i>obj</i> are copied, but not the objects they reference. Copies
310  *  the frozen and tainted state of <i>obj</i>. See also the discussion
311  *  under <code>Object#dup</code>.
312  *
313  *     class Klass
314  *        attr_accessor :str
315  *     end
316  *     s1 = Klass.new      #=> #<Klass:0x401b3a38>
317  *     s1.str = "Hello"    #=> "Hello"
318  *     s2 = s1.clone       #=> #<Klass:0x401b3998 @str="Hello">
319  *     s2.str[1,4] = "i"   #=> "i"
320  *     s1.inspect          #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
321  *     s2.inspect          #=> "#<Klass:0x401b3998 @str=\"Hi\">"
322  *
323  *  This method may have class-specific behavior.  If so, that
324  *  behavior will be documented under the #+initialize_copy+ method of
325  *  the class.
326  */
327 
328 VALUE
329 rb_obj_clone(VALUE obj)
330 {
331     VALUE clone;
332     VALUE singleton;
333 
334     if (rb_special_const_p(obj)) {
335         rb_raise(rb_eTypeError, "can't clone %s", rb_obj_classname(obj));
336     }
337     clone = rb_obj_alloc(rb_obj_class(obj));
338     RBASIC(clone)->flags &= FL_TAINT;
339     RBASIC(clone)->flags |= RBASIC(obj)->flags & ~(FL_OLDGEN|FL_FREEZE|FL_FINALIZE);
340 
341     singleton = rb_singleton_class_clone_and_attach(obj, clone);
342     RBASIC_SET_CLASS(clone, singleton);
343     if (FL_TEST(singleton, FL_SINGLETON)) {
344         rb_singleton_class_attached(singleton, clone);
345     }
346 
347     init_copy(clone, obj);
348     rb_funcall(clone, id_init_clone, 1, obj);
349     RBASIC(clone)->flags |= RBASIC(obj)->flags & FL_FREEZE;
350 
351     return clone;
352 }
353 
354 /*
355  *  call-seq:
356  *     obj.dup -> an_object
357  *
358  *  Produces a shallow copy of <i>obj</i>---the instance variables of
359  *  <i>obj</i> are copied, but not the objects they reference.
360  *  <code>dup</code> copies the tainted state of <i>obj</i>. See also
361  *  the discussion under <code>Object#clone</code>. In general,
362  *  <code>clone</code> and <code>dup</code> may have different semantics
363  *  in descendant classes. While <code>clone</code> is used to duplicate
364  *  an object, including its internal state, <code>dup</code> typically
365  *  uses the class of the descendant object to create the new instance.
366  *
367  *  This method may have class-specific behavior.  If so, that
368  *  behavior will be documented under the #+initialize_copy+ method of
369  *  the class.
370  */
371 
372 VALUE
373 rb_obj_dup(VALUE obj)
374 {
375     VALUE dup;
376 
377     if (rb_special_const_p(obj)) {
378         rb_raise(rb_eTypeError, "can't dup %s", rb_obj_classname(obj));
379     }
380     dup = rb_obj_alloc(rb_obj_class(obj));
381     init_copy(dup, obj);
382     rb_funcall(dup, id_init_dup, 1, obj);
383 
384     return dup;
385 }
386 
387 /* :nodoc: */
388 VALUE
389 rb_obj_init_copy(VALUE obj, VALUE orig)
390 {
391     if (obj == orig) return obj;
392     rb_check_frozen(obj);
393     rb_check_trusted(obj);
394     if (TYPE(obj) != TYPE(orig) || rb_obj_class(obj) != rb_obj_class(orig)) {
395         rb_raise(rb_eTypeError, "initialize_copy should take same class object");
396     }
397     return obj;
398 }
399 
400 /* :nodoc: */
401 VALUE
402 rb_obj_init_dup_clone(VALUE obj, VALUE orig)
403 {
404     rb_funcall(obj, id_init_copy, 1, orig);
405     return obj;
406 }
407 
408 /*
409  *  call-seq:
410  *     obj.to_s    -> string
411  *
412  *  Returns a string representing <i>obj</i>. The default
413  *  <code>to_s</code> prints the object's class and an encoding of the
414  *  object id. As a special case, the top-level object that is the
415  *  initial execution context of Ruby programs returns ``main.''
416  */
417 
418 VALUE
419 rb_any_to_s(VALUE obj)
420 {
421     VALUE str;
422     VALUE cname = rb_class_name(CLASS_OF(obj));
423 
424     str = rb_sprintf("#<%"PRIsVALUE":%p>", cname, (void*)obj);
425     OBJ_INFECT(str, obj);
426 
427     return str;
428 }
429 
430 /*
431  * If the default external encoding is ASCII compatible, the encoding of
432  * inspected result must be compatible with it.
433  * If the default external encoding is ASCII incompatible,
434  * the result must be ASCII only.
435  */
436 VALUE
437 rb_inspect(VALUE obj)
438 {
439     VALUE str = rb_obj_as_string(rb_funcall(obj, id_inspect, 0, 0));
440     rb_encoding *ext = rb_default_external_encoding();
441     if (!rb_enc_asciicompat(ext)) {
442         if (!rb_enc_str_asciionly_p(str))
443             rb_raise(rb_eEncCompatError, "inspected result must be ASCII only if default external encoding is ASCII incompatible");
444         return str;
445     }
446     if (rb_enc_get(str) != ext && !rb_enc_str_asciionly_p(str))
447         rb_raise(rb_eEncCompatError, "inspected result must be ASCII only or use the default external encoding");
448     return str;
449 }
450 
451 static int
452 inspect_i(st_data_t k, st_data_t v, st_data_t a)
453 {
454     ID id = (ID)k;
455     VALUE value = (VALUE)v;
456     VALUE str = (VALUE)a;
457     VALUE str2;
458     const char *ivname;
459 
460     /* need not to show internal data */
461     if (CLASS_OF(value) == 0) return ST_CONTINUE;
462     if (!rb_is_instance_id(id)) return ST_CONTINUE;
463     if (RSTRING_PTR(str)[0] == '-') { /* first element */
464         RSTRING_PTR(str)[0] = '#';
465         rb_str_cat2(str, " ");
466     }
467     else {
468         rb_str_cat2(str, ", ");
469     }
470     ivname = rb_id2name(id);
471     rb_str_cat2(str, ivname);
472     rb_str_cat2(str, "=");
473     str2 = rb_inspect(value);
474     rb_str_append(str, str2);
475     OBJ_INFECT(str, str2);
476 
477     return ST_CONTINUE;
478 }
479 
480 static VALUE
481 inspect_obj(VALUE obj, VALUE str, int recur)
482 {
483     if (recur) {
484         rb_str_cat2(str, " ...");
485     }
486     else {
487         rb_ivar_foreach(obj, inspect_i, str);
488     }
489     rb_str_cat2(str, ">");
490     RSTRING_PTR(str)[0] = '#';
491     OBJ_INFECT(str, obj);
492 
493     return str;
494 }
495 
496 /*
497  *  call-seq:
498  *     obj.inspect   -> string
499  *
500  * Returns a string containing a human-readable representation of <i>obj</i>.
501  * By default, show the class name and the list of the instance variables and
502  * their values (by calling #inspect on each of them).
503  * User defined classes should override this method to make better
504  * representation of <i>obj</i>.  When overriding this method, it should
505  * return a string whose encoding is compatible with the default external
506  * encoding.
507  *
508  *     [ 1, 2, 3..4, 'five' ].inspect   #=> "[1, 2, 3..4, \"five\"]"
509  *     Time.new.inspect                 #=> "2008-03-08 19:43:39 +0900"
510  *
511  *     class Foo
512  *     end
513  *     Foo.new.inspect                  #=> "#<Foo:0x0300c868>"
514  *
515  *     class Bar
516  *       def initialize
517  *         @bar = 1
518  *       end
519  *     end
520  *     Bar.new.inspect                  #=> "#<Bar:0x0300c868 @bar=1>"
521  *
522  *     class Baz
523  *       def to_s
524  *         "baz"
525  *       end
526  *     end
527  *     Baz.new.inspect                  #=> "#<Baz:0x0300c868>"
528  */
529 
530 static VALUE
531 rb_obj_inspect(VALUE obj)
532 {
533     if (rb_ivar_count(obj) > 0) {
534         VALUE str;
535         VALUE c = rb_class_name(CLASS_OF(obj));
536 
537         str = rb_sprintf("-<%"PRIsVALUE":%p", c, (void*)obj);
538         return rb_exec_recursive(inspect_obj, obj, str);
539     }
540     else {
541         return rb_any_to_s(obj);
542     }
543 }
544 
545 static VALUE
546 class_or_module_required(VALUE c)
547 {
548     if (SPECIAL_CONST_P(c)) goto not_class;
549     switch (BUILTIN_TYPE(c)) {
550       case T_MODULE:
551       case T_CLASS:
552       case T_ICLASS:
553         break;
554 
555       default:
556       not_class:
557         rb_raise(rb_eTypeError, "class or module required");
558     }
559     return c;
560 }
561 
562 /*
563  *  call-seq:
564  *     obj.instance_of?(class)    -> true or false
565  *
566  *  Returns <code>true</code> if <i>obj</i> is an instance of the given
567  *  class. See also <code>Object#kind_of?</code>.
568  *
569  *     class A;     end
570  *     class B < A; end
571  *     class C < B; end
572  *
573  *     b = B.new
574  *     b.instance_of? A   #=> false
575  *     b.instance_of? B   #=> true
576  *     b.instance_of? C   #=> false
577  */
578 
579 VALUE
580 rb_obj_is_instance_of(VALUE obj, VALUE c)
581 {
582     c = class_or_module_required(c);
583     if (rb_obj_class(obj) == c) return Qtrue;
584     return Qfalse;
585 }
586 
587 
588 /*
589  *  call-seq:
590  *     obj.is_a?(class)       -> true or false
591  *     obj.kind_of?(class)    -> true or false
592  *
593  *  Returns <code>true</code> if <i>class</i> is the class of
594  *  <i>obj</i>, or if <i>class</i> is one of the superclasses of
595  *  <i>obj</i> or modules included in <i>obj</i>.
596  *
597  *     module M;    end
598  *     class A
599  *       include M
600  *     end
601  *     class B < A; end
602  *     class C < B; end
603  *
604  *     b = B.new
605  *     b.is_a? A          #=> true
606  *     b.is_a? B          #=> true
607  *     b.is_a? C          #=> false
608  *     b.is_a? M          #=> true
609  *
610  *     b.kind_of? A       #=> true
611  *     b.kind_of? B       #=> true
612  *     b.kind_of? C       #=> false
613  *     b.kind_of? M       #=> true
614  */
615 
616 VALUE
617 rb_obj_is_kind_of(VALUE obj, VALUE c)
618 {
619     VALUE cl = CLASS_OF(obj);
620 
621     c = class_or_module_required(c);
622     c = RCLASS_ORIGIN(c);
623     while (cl) {
624         if (cl == c || RCLASS_M_TBL(cl) == RCLASS_M_TBL(c))
625             return Qtrue;
626         cl = RCLASS_SUPER(cl);
627     }
628     return Qfalse;
629 }
630 
631 
632 /*
633  *  call-seq:
634  *     obj.tap{|x|...}    -> obj
635  *
636  *  Yields <code>x</code> to the block, and then returns <code>x</code>.
637  *  The primary purpose of this method is to "tap into" a method chain,
638  *  in order to perform operations on intermediate results within the chain.
639  *
640  *      (1..10)                .tap {|x| puts "original: #{x.inspect}"}
641  *        .to_a                .tap {|x| puts "array: #{x.inspect}"}
642  *        .select {|x| x%2==0} .tap {|x| puts "evens: #{x.inspect}"}
643  *        .map { |x| x*x }     .tap {|x| puts "squares: #{x.inspect}"}
644  *
645  */
646 
647 VALUE
648 rb_obj_tap(VALUE obj)
649 {
650     rb_yield(obj);
651     return obj;
652 }
653 
654 
655 /*
656  * Document-method: inherited
657  *
658  * call-seq:
659  *    inherited(subclass)
660  *
661  * Callback invoked whenever a subclass of the current class is created.
662  *
663  * Example:
664  *
665  *    class Foo
666  *      def self.inherited(subclass)
667  *        puts "New subclass: #{subclass}"
668  *      end
669  *    end
670  *
671  *    class Bar < Foo
672  *    end
673  *
674  *    class Baz < Bar
675  *    end
676  *
677  * produces:
678  *
679  *    New subclass: Bar
680  *    New subclass: Baz
681  */
682 
683 /* Document-method: method_added
684  *
685  * call-seq:
686  *   method_added(method_name)
687  *
688  * Invoked as a callback whenever an instance method is added to the
689  * receiver.
690  *
691  *   module Chatty
692  *     def self.method_added(method_name)
693  *       puts "Adding #{method_name.inspect}"
694  *     end
695  *     def self.some_class_method() end
696  *     def some_instance_method() end
697  *   end
698  *
699  * produces:
700  *
701  *   Adding :some_instance_method
702  *
703  */
704 
705 /* Document-method: method_removed
706  *
707  * call-seq:
708  *   method_removed(method_name)
709  *
710  * Invoked as a callback whenever an instance method is removed from the
711  * receiver.
712  *
713  *   module Chatty
714  *     def self.method_removed(method_name)
715  *       puts "Removing #{method_name.inspect}"
716  *     end
717  *     def self.some_class_method() end
718  *     def some_instance_method() end
719  *     class << self
720  *       remove_method :some_class_method
721  *     end
722  *     remove_method :some_instance_method
723  *   end
724  *
725  * produces:
726  *
727  *   Removing :some_instance_method
728  *
729  */
730 
731 /*
732  * Document-method: singleton_method_added
733  *
734  *  call-seq:
735  *     singleton_method_added(symbol)
736  *
737  *  Invoked as a callback whenever a singleton method is added to the
738  *  receiver.
739  *
740  *     module Chatty
741  *       def Chatty.singleton_method_added(id)
742  *         puts "Adding #{id.id2name}"
743  *       end
744  *       def self.one()     end
745  *       def two()          end
746  *       def Chatty.three() end
747  *     end
748  *
749  *  <em>produces:</em>
750  *
751  *     Adding singleton_method_added
752  *     Adding one
753  *     Adding three
754  *
755  */
756 
757 /*
758  * Document-method: singleton_method_removed
759  *
760  *  call-seq:
761  *     singleton_method_removed(symbol)
762  *
763  *  Invoked as a callback whenever a singleton method is removed from
764  *  the receiver.
765  *
766  *     module Chatty
767  *       def Chatty.singleton_method_removed(id)
768  *         puts "Removing #{id.id2name}"
769  *       end
770  *       def self.one()     end
771  *       def two()          end
772  *       def Chatty.three() end
773  *       class << self
774  *         remove_method :three
775  *         remove_method :one
776  *       end
777  *     end
778  *
779  *  <em>produces:</em>
780  *
781  *     Removing three
782  *     Removing one
783  */
784 
785 /*
786  * Document-method: singleton_method_undefined
787  *
788  *  call-seq:
789  *     singleton_method_undefined(symbol)
790  *
791  *  Invoked as a callback whenever a singleton method is undefined in
792  *  the receiver.
793  *
794  *     module Chatty
795  *       def Chatty.singleton_method_undefined(id)
796  *         puts "Undefining #{id.id2name}"
797  *       end
798  *       def Chatty.one()   end
799  *       class << self
800  *          undef_method(:one)
801  *       end
802  *     end
803  *
804  *  <em>produces:</em>
805  *
806  *     Undefining one
807  */
808 
809 /*
810  * Document-method: extended
811  *
812  * call-seq:
813  *    extended(othermod)
814  *
815  * The equivalent of <tt>included</tt>, but for extended modules.
816  *
817  *        module A
818  *          def self.extended(mod)
819  *            puts "#{self} extended in #{mod}"
820  *          end
821  *        end
822  *        module Enumerable
823  *          extend A
824  *        end
825  *         # => prints "A extended in Enumerable"
826  */
827 
828 /*
829  * Document-method: included
830  *
831  * call-seq:
832  *    included(othermod)
833  *
834  * Callback invoked whenever the receiver is included in another
835  * module or class. This should be used in preference to
836  * <tt>Module.append_features</tt> if your code wants to perform some
837  * action when a module is included in another.
838  *
839  *        module A
840  *          def A.included(mod)
841  *            puts "#{self} included in #{mod}"
842  *          end
843  *        end
844  *        module Enumerable
845  *          include A
846  *        end
847  *         # => prints "A included in Enumerable"
848  */
849 
850 /*
851  * Document-method: prepended
852  *
853  * call-seq:
854  *    prepended(othermod)
855  *
856  * The equivalent of <tt>included</tt>, but for prepended modules.
857  *
858  *        module A
859  *          def self.prepended(mod)
860  *            puts "#{self} prepended to #{mod}"
861  *          end
862  *        end
863  *        module Enumerable
864  *          prepend A
865  *        end
866  *         # => prints "A prepended to Enumerable"
867  */
868 
869 /*
870  * Document-method: initialize
871  *
872  * call-seq:
873  *    BasicObject.new
874  *
875  * Returns a new BasicObject.
876  */
877 
878 /*
879  * Not documented
880  */
881 
882 static VALUE
883 rb_obj_dummy(void)
884 {
885     return Qnil;
886 }
887 
888 /*
889  *  call-seq:
890  *     obj.tainted?    -> true or false
891  *
892  *  Returns true if the object is tainted.
893  *
894  *  See #taint for more information.
895  */
896 
897 VALUE
898 rb_obj_tainted(VALUE obj)
899 {
900     if (OBJ_TAINTED(obj))
901         return Qtrue;
902     return Qfalse;
903 }
904 
905 /*
906  *  call-seq:
907  *     obj.taint -> obj
908  *
909  *  Mark the object as tainted.
910  *
911  *  Objects that are marked as tainted will be restricted from various built-in
912  *  methods. This is to prevent insecure data, such as command-line arguments
913  *  or strings read from Kernel#gets, from inadvertently compromising the users
914  *  system.
915  *
916  *  To check whether an object is tainted, use #tainted?
917  *
918  *  You should only untaint a tainted object if your code has inspected it and
919  *  determined that it is safe. To do so use #untaint
920  *
921  *  In $SAFE level 3 and 4, all objects are tainted and untrusted, any use of
922  *  trust or taint methods will raise a SecurityError exception.
923  */
924 
925 VALUE
926 rb_obj_taint(VALUE obj)
927 {
928     if (!OBJ_TAINTED(obj)) {
929         rb_check_frozen(obj);
930         OBJ_TAINT(obj);
931     }
932     return obj;
933 }
934 
935 
936 /*
937  *  call-seq:
938  *     obj.untaint    -> obj
939  *
940  *  Removes the tainted mark from the object.
941  *
942  *  See #taint for more information.
943  */
944 
945 VALUE
946 rb_obj_untaint(VALUE obj)
947 {
948     rb_secure(3);
949     if (OBJ_TAINTED(obj)) {
950         rb_check_frozen(obj);
951         FL_UNSET(obj, FL_TAINT);
952     }
953     return obj;
954 }
955 
956 /*
957  *  call-seq:
958  *     obj.untrusted?    -> true or false
959  *
960  *  Deprecated method that is equivalent to #tainted?.
961  */
962 
963 VALUE
964 rb_obj_untrusted(VALUE obj)
965 {
966     rb_warning("untrusted? is deprecated and its behavior is same as tainted?");
967     return rb_obj_tainted(obj);
968 }
969 
970 /*
971  *  call-seq:
972  *     obj.untrust -> obj
973  *
974  *  Deprecated method that is equivalent to #taint.
975  */
976 
977 VALUE
978 rb_obj_untrust(VALUE obj)
979 {
980     rb_warning("untrust is deprecated and its behavior is same as taint");
981     return rb_obj_taint(obj);
982 }
983 
984 
985 /*
986  *  call-seq:
987  *     obj.trust    -> obj
988  *
989  *  Deprecated method that is equivalent to #untaint.
990  */
991 
992 VALUE
993 rb_obj_trust(VALUE obj)
994 {
995     rb_warning("trust is deprecated and its behavior is same as untaint");
996     return rb_obj_untaint(obj);
997 }
998 
999 void
1000 rb_obj_infect(VALUE obj1, VALUE obj2)
1001 {
1002     OBJ_INFECT(obj1, obj2);
1003 }
1004 
1005 static st_table *immediate_frozen_tbl = 0;
1006 
1007 /*
1008  *  call-seq:
1009  *     obj.freeze    -> obj
1010  *
1011  *  Prevents further modifications to <i>obj</i>. A
1012  *  <code>RuntimeError</code> will be raised if modification is attempted.
1013  *  There is no way to unfreeze a frozen object. See also
1014  *  <code>Object#frozen?</code>.
1015  *
1016  *  This method returns self.
1017  *
1018  *     a = [ "a", "b", "c" ]
1019  *     a.freeze
1020  *     a << "z"
1021  *
1022  *  <em>produces:</em>
1023  *
1024  *     prog.rb:3:in `<<': can't modify frozen array (RuntimeError)
1025  *      from prog.rb:3
1026  */
1027 
1028 VALUE
1029 rb_obj_freeze(VALUE obj)
1030 {
1031     if (!OBJ_FROZEN(obj)) {
1032         OBJ_FREEZE(obj);
1033         if (SPECIAL_CONST_P(obj)) {
1034             if (!immediate_frozen_tbl) {
1035                 immediate_frozen_tbl = st_init_numtable();
1036             }
1037             st_insert(immediate_frozen_tbl, obj, (st_data_t)Qtrue);
1038         }
1039     }
1040     return obj;
1041 }
1042 
1043 /*
1044  *  call-seq:
1045  *     obj.frozen?    -> true or false
1046  *
1047  *  Returns the freeze status of <i>obj</i>.
1048  *
1049  *     a = [ "a", "b", "c" ]
1050  *     a.freeze    #=> ["a", "b", "c"]
1051  *     a.frozen?   #=> true
1052  */
1053 
1054 VALUE
1055 rb_obj_frozen_p(VALUE obj)
1056 {
1057     if (OBJ_FROZEN(obj)) return Qtrue;
1058     if (SPECIAL_CONST_P(obj)) {
1059         if (!immediate_frozen_tbl) return Qfalse;
1060         if (st_lookup(immediate_frozen_tbl, obj, 0)) return Qtrue;
1061     }
1062     return Qfalse;
1063 }
1064 
1065 
1066 /*
1067  * Document-class: NilClass
1068  *
1069  *  The class of the singleton object <code>nil</code>.
1070  */
1071 
1072 /*
1073  *  call-seq:
1074  *     nil.to_i -> 0
1075  *
1076  *  Always returns zero.
1077  *
1078  *     nil.to_i   #=> 0
1079  */
1080 
1081 
1082 static VALUE
1083 nil_to_i(VALUE obj)
1084 {
1085     return INT2FIX(0);
1086 }
1087 
1088 /*
1089  *  call-seq:
1090  *     nil.to_f    -> 0.0
1091  *
1092  *  Always returns zero.
1093  *
1094  *     nil.to_f   #=> 0.0
1095  */
1096 
1097 static VALUE
1098 nil_to_f(VALUE obj)
1099 {
1100     return DBL2NUM(0.0);
1101 }
1102 
1103 /*
1104  *  call-seq:
1105  *     nil.to_s    -> ""
1106  *
1107  *  Always returns the empty string.
1108  */
1109 
1110 static VALUE
1111 nil_to_s(VALUE obj)
1112 {
1113     return rb_usascii_str_new(0, 0);
1114 }
1115 
1116 /*
1117  * Document-method: to_a
1118  *
1119  *  call-seq:
1120  *     nil.to_a    -> []
1121  *
1122  *  Always returns an empty array.
1123  *
1124  *     nil.to_a   #=> []
1125  */
1126 
1127 static VALUE
1128 nil_to_a(VALUE obj)
1129 {
1130     return rb_ary_new2(0);
1131 }
1132 
1133 /*
1134  * Document-method: to_h
1135  *
1136  *  call-seq:
1137  *     nil.to_h    -> {}
1138  *
1139  *  Always returns an empty hash.
1140  *
1141  *     nil.to_h   #=> {}
1142  */
1143 
1144 static VALUE
1145 nil_to_h(VALUE obj)
1146 {
1147     return rb_hash_new();
1148 }
1149 
1150 /*
1151  *  call-seq:
1152  *    nil.inspect  -> "nil"
1153  *
1154  *  Always returns the string "nil".
1155  */
1156 
1157 static VALUE
1158 nil_inspect(VALUE obj)
1159 {
1160     return rb_usascii_str_new2("nil");
1161 }
1162 
1163 /***********************************************************************
1164  *  Document-class: TrueClass
1165  *
1166  *  The global value <code>true</code> is the only instance of class
1167  *  <code>TrueClass</code> and represents a logically true value in
1168  *  boolean expressions. The class provides operators allowing
1169  *  <code>true</code> to be used in logical expressions.
1170  */
1171 
1172 
1173 /*
1174  * call-seq:
1175  *   true.to_s   ->  "true"
1176  *
1177  * The string representation of <code>true</code> is "true".
1178  */
1179 
1180 static VALUE
1181 true_to_s(VALUE obj)
1182 {
1183     return rb_usascii_str_new2("true");
1184 }
1185 
1186 
1187 /*
1188  *  call-seq:
1189  *     true & obj    -> true or false
1190  *
1191  *  And---Returns <code>false</code> if <i>obj</i> is
1192  *  <code>nil</code> or <code>false</code>, <code>true</code> otherwise.
1193  */
1194 
1195 static VALUE
1196 true_and(VALUE obj, VALUE obj2)
1197 {
1198     return RTEST(obj2)?Qtrue:Qfalse;
1199 }
1200 
1201 /*
1202  *  call-seq:
1203  *     true | obj   -> true
1204  *
1205  *  Or---Returns <code>true</code>. As <i>anObject</i> is an argument to
1206  *  a method call, it is always evaluated; there is no short-circuit
1207  *  evaluation in this case.
1208  *
1209  *     true |  puts("or")
1210  *     true || puts("logical or")
1211  *
1212  *  <em>produces:</em>
1213  *
1214  *     or
1215  */
1216 
1217 static VALUE
1218 true_or(VALUE obj, VALUE obj2)
1219 {
1220     return Qtrue;
1221 }
1222 
1223 
1224 /*
1225  *  call-seq:
1226  *     true ^ obj   -> !obj
1227  *
1228  *  Exclusive Or---Returns <code>true</code> if <i>obj</i> is
1229  *  <code>nil</code> or <code>false</code>, <code>false</code>
1230  *  otherwise.
1231  */
1232 
1233 static VALUE
1234 true_xor(VALUE obj, VALUE obj2)
1235 {
1236     return RTEST(obj2)?Qfalse:Qtrue;
1237 }
1238 
1239 
1240 /*
1241  *  Document-class: FalseClass
1242  *
1243  *  The global value <code>false</code> is the only instance of class
1244  *  <code>FalseClass</code> and represents a logically false value in
1245  *  boolean expressions. The class provides operators allowing
1246  *  <code>false</code> to participate correctly in logical expressions.
1247  *
1248  */
1249 
1250 /*
1251  * call-seq:
1252  *   false.to_s   ->  "false"
1253  *
1254  * 'nuf said...
1255  */
1256 
1257 static VALUE
1258 false_to_s(VALUE obj)
1259 {
1260     return rb_usascii_str_new2("false");
1261 }
1262 
1263 /*
1264  *  call-seq:
1265  *     false & obj   -> false
1266  *     nil & obj     -> false
1267  *
1268  *  And---Returns <code>false</code>. <i>obj</i> is always
1269  *  evaluated as it is the argument to a method call---there is no
1270  *  short-circuit evaluation in this case.
1271  */
1272 
1273 static VALUE
1274 false_and(VALUE obj, VALUE obj2)
1275 {
1276     return Qfalse;
1277 }
1278 
1279 
1280 /*
1281  *  call-seq:
1282  *     false | obj   ->   true or false
1283  *     nil   | obj   ->   true or false
1284  *
1285  *  Or---Returns <code>false</code> if <i>obj</i> is
1286  *  <code>nil</code> or <code>false</code>; <code>true</code> otherwise.
1287  */
1288 
1289 static VALUE
1290 false_or(VALUE obj, VALUE obj2)
1291 {
1292     return RTEST(obj2)?Qtrue:Qfalse;
1293 }
1294 
1295 
1296 
1297 /*
1298  *  call-seq:
1299  *     false ^ obj    -> true or false
1300  *     nil   ^ obj    -> true or false
1301  *
1302  *  Exclusive Or---If <i>obj</i> is <code>nil</code> or
1303  *  <code>false</code>, returns <code>false</code>; otherwise, returns
1304  *  <code>true</code>.
1305  *
1306  */
1307 
1308 static VALUE
1309 false_xor(VALUE obj, VALUE obj2)
1310 {
1311     return RTEST(obj2)?Qtrue:Qfalse;
1312 }
1313 
1314 /*
1315  * call-seq:
1316  *   nil.nil?               -> true
1317  *
1318  * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1319  */
1320 
1321 static VALUE
1322 rb_true(VALUE obj)
1323 {
1324     return Qtrue;
1325 }
1326 
1327 /*
1328  * call-seq:
1329  *   nil.nil?               -> true
1330  *   <anything_else>.nil?   -> false
1331  *
1332  * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1333  */
1334 
1335 
1336 static VALUE
1337 rb_false(VALUE obj)
1338 {
1339     return Qfalse;
1340 }
1341 
1342 
1343 /*
1344  *  call-seq:
1345  *     obj =~ other  -> nil
1346  *
1347  *  Pattern Match---Overridden by descendants (notably
1348  *  <code>Regexp</code> and <code>String</code>) to provide meaningful
1349  *  pattern-match semantics.
1350  */
1351 
1352 static VALUE
1353 rb_obj_match(VALUE obj1, VALUE obj2)
1354 {
1355     return Qnil;
1356 }
1357 
1358 /*
1359  *  call-seq:
1360  *     obj !~ other  -> true or false
1361  *
1362  *  Returns true if two objects do not match (using the <i>=~</i>
1363  *  method), otherwise false.
1364  */
1365 
1366 static VALUE
1367 rb_obj_not_match(VALUE obj1, VALUE obj2)
1368 {
1369     VALUE result = rb_funcall(obj1, id_match, 1, obj2);
1370     return RTEST(result) ? Qfalse : Qtrue;
1371 }
1372 
1373 
1374 /*
1375  *  call-seq:
1376  *     obj <=> other -> 0 or nil
1377  *
1378  *  Returns 0 if +obj+ and +other+ are the same object
1379  *  or <code>obj == other</code>, otherwise nil.
1380  *
1381  *  The <=> is used by various methods to compare objects, for example
1382  *  Enumerable#sort, Enumerable#max etc.
1383  *
1384  *  Your implementation of <=> should return one of the following values: -1, 0,
1385  *  1 or nil. -1 means self is smaller than other. 0 means self is equal to other.
1386  *  1 means self is bigger than other. Nil means the two values could not be
1387  *  compared.
1388  *
1389  *  When you define <=>, you can include Comparable to gain the methods <=, <,
1390  *  ==, >=, > and between?.
1391  */
1392 static VALUE
1393 rb_obj_cmp(VALUE obj1, VALUE obj2)
1394 {
1395     if (obj1 == obj2 || rb_equal(obj1, obj2))
1396         return INT2FIX(0);
1397     return Qnil;
1398 }
1399 
1400 /***********************************************************************
1401  *
1402  * Document-class: Module
1403  *
1404  *  A <code>Module</code> is a collection of methods and constants. The
1405  *  methods in a module may be instance methods or module methods.
1406  *  Instance methods appear as methods in a class when the module is
1407  *  included, module methods do not. Conversely, module methods may be
1408  *  called without creating an encapsulating object, while instance
1409  *  methods may not. (See <code>Module#module_function</code>)
1410  *
1411  *  In the descriptions that follow, the parameter <i>sym</i> refers
1412  *  to a symbol, which is either a quoted string or a
1413  *  <code>Symbol</code> (such as <code>:name</code>).
1414  *
1415  *     module Mod
1416  *       include Math
1417  *       CONST = 1
1418  *       def meth
1419  *         #  ...
1420  *       end
1421  *     end
1422  *     Mod.class              #=> Module
1423  *     Mod.constants          #=> [:CONST, :PI, :E]
1424  *     Mod.instance_methods   #=> [:meth]
1425  *
1426  */
1427 
1428 /*
1429  * call-seq:
1430  *   mod.to_s   -> string
1431  *
1432  * Return a string representing this module or class. For basic
1433  * classes and modules, this is the name. For singletons, we
1434  * show information on the thing we're attached to as well.
1435  */
1436 
1437 static VALUE
1438 rb_mod_to_s(VALUE klass)
1439 {
1440     ID id_defined_at;
1441     VALUE refined_class, defined_at;
1442 
1443     if (FL_TEST(klass, FL_SINGLETON)) {
1444         VALUE s = rb_usascii_str_new2("#<Class:");
1445         VALUE v = rb_ivar_get(klass, id__attached__);
1446 
1447         if (CLASS_OR_MODULE_P(v)) {
1448             rb_str_append(s, rb_inspect(v));
1449         }
1450         else {
1451             rb_str_append(s, rb_any_to_s(v));
1452         }
1453         rb_str_cat2(s, ">");
1454 
1455         return s;
1456     }
1457     refined_class = rb_refinement_module_get_refined_class(klass);
1458     if (!NIL_P(refined_class)) {
1459         VALUE s = rb_usascii_str_new2("#<refinement:");
1460 
1461         rb_str_concat(s, rb_inspect(refined_class));
1462         rb_str_cat2(s, "@");
1463         CONST_ID(id_defined_at, "__defined_at__");
1464         defined_at = rb_attr_get(klass, id_defined_at);
1465         rb_str_concat(s, rb_inspect(defined_at));
1466         rb_str_cat2(s, ">");
1467         return s;
1468     }
1469     return rb_str_dup(rb_class_name(klass));
1470 }
1471 
1472 /*
1473  *  call-seq:
1474  *     mod.freeze       -> mod
1475  *
1476  *  Prevents further modifications to <i>mod</i>.
1477  *
1478  *  This method returns self.
1479  */
1480 
1481 static VALUE
1482 rb_mod_freeze(VALUE mod)
1483 {
1484     rb_class_name(mod);
1485     return rb_obj_freeze(mod);
1486 }
1487 
1488 /*
1489  *  call-seq:
1490  *     mod === obj    -> true or false
1491  *
1492  *  Case Equality---Returns <code>true</code> if <i>anObject</i> is an
1493  *  instance of <i>mod</i> or one of <i>mod</i>'s descendants. Of
1494  *  limited use for modules, but can be used in <code>case</code>
1495  *  statements to classify objects by class.
1496  */
1497 
1498 static VALUE
1499 rb_mod_eqq(VALUE mod, VALUE arg)
1500 {
1501     return rb_obj_is_kind_of(arg, mod);
1502 }
1503 
1504 /*
1505  * call-seq:
1506  *   mod <= other   ->  true, false, or nil
1507  *
1508  * Returns true if <i>mod</i> is a subclass of <i>other</i> or
1509  * is the same as <i>other</i>. Returns
1510  * <code>nil</code> if there's no relationship between the two.
1511  * (Think of the relationship in terms of the class definition:
1512  * "class A<B" implies "A<B").
1513  *
1514  */
1515 
1516 VALUE
1517 rb_class_inherited_p(VALUE mod, VALUE arg)
1518 {
1519     VALUE start = mod;
1520 
1521     if (mod == arg) return Qtrue;
1522     if (!CLASS_OR_MODULE_P(arg)) {
1523         rb_raise(rb_eTypeError, "compared with non class/module");
1524     }
1525     arg = RCLASS_ORIGIN(arg);
1526     while (mod) {
1527         if (RCLASS_M_TBL(mod) == RCLASS_M_TBL(arg))
1528             return Qtrue;
1529         mod = RCLASS_SUPER(mod);
1530     }
1531     /* not mod < arg; check if mod > arg */
1532     while (arg) {
1533         if (RCLASS_M_TBL(arg) == RCLASS_M_TBL(start))
1534             return Qfalse;
1535         arg = RCLASS_SUPER(arg);
1536     }
1537     return Qnil;
1538 }
1539 
1540 /*
1541  * call-seq:
1542  *   mod < other   ->  true, false, or nil
1543  *
1544  * Returns true if <i>mod</i> is a subclass of <i>other</i>. Returns
1545  * <code>nil</code> if there's no relationship between the two.
1546  * (Think of the relationship in terms of the class definition:
1547  * "class A<B" implies "A<B").
1548  *
1549  */
1550 
1551 static VALUE
1552 rb_mod_lt(VALUE mod, VALUE arg)
1553 {
1554     if (mod == arg) return Qfalse;
1555     return rb_class_inherited_p(mod, arg);
1556 }
1557 
1558 
1559 /*
1560  * call-seq:
1561  *   mod >= other   ->  true, false, or nil
1562  *
1563  * Returns true if <i>mod</i> is an ancestor of <i>other</i>, or the
1564  * two modules are the same. Returns
1565  * <code>nil</code> if there's no relationship between the two.
1566  * (Think of the relationship in terms of the class definition:
1567  * "class A<B" implies "B>A").
1568  *
1569  */
1570 
1571 static VALUE
1572 rb_mod_ge(VALUE mod, VALUE arg)
1573 {
1574     if (!CLASS_OR_MODULE_P(arg)) {
1575         rb_raise(rb_eTypeError, "compared with non class/module");
1576     }
1577 
1578     return rb_class_inherited_p(arg, mod);
1579 }
1580 
1581 /*
1582  * call-seq:
1583  *   mod > other   ->  true, false, or nil
1584  *
1585  * Returns true if <i>mod</i> is an ancestor of <i>other</i>. Returns
1586  * <code>nil</code> if there's no relationship between the two.
1587  * (Think of the relationship in terms of the class definition:
1588  * "class A<B" implies "B>A").
1589  *
1590  */
1591 
1592 static VALUE
1593 rb_mod_gt(VALUE mod, VALUE arg)
1594 {
1595     if (mod == arg) return Qfalse;
1596     return rb_mod_ge(mod, arg);
1597 }
1598 
1599 /*
1600  *  call-seq:
1601  *     module <=> other_module   -> -1, 0, +1, or nil
1602  *
1603  *  Comparison---Returns -1, 0, +1 or nil depending on whether +module+
1604  *  includes +other_module+, they are the same, or if +module+ is included by
1605  *  +other_module+. This is the basis for the tests in Comparable.
1606  *
1607  *  Returns +nil+ if +module+ has no relationship with +other_module+, if
1608  *  +other_module+ is not a module, or if the two values are incomparable.
1609  */
1610 
1611 static VALUE
1612 rb_mod_cmp(VALUE mod, VALUE arg)
1613 {
1614     VALUE cmp;
1615 
1616     if (mod == arg) return INT2FIX(0);
1617     if (!CLASS_OR_MODULE_P(arg)) {
1618         return Qnil;
1619     }
1620 
1621     cmp = rb_class_inherited_p(mod, arg);
1622     if (NIL_P(cmp)) return Qnil;
1623     if (cmp) {
1624         return INT2FIX(-1);
1625     }
1626     return INT2FIX(1);
1627 }
1628 
1629 static VALUE
1630 rb_module_s_alloc(VALUE klass)
1631 {
1632     VALUE mod = rb_module_new();
1633 
1634     RBASIC_SET_CLASS(mod, klass);
1635     return mod;
1636 }
1637 
1638 static VALUE
1639 rb_class_s_alloc(VALUE klass)
1640 {
1641     return rb_class_boot(0);
1642 }
1643 
1644 /*
1645  *  call-seq:
1646  *    Module.new                  -> mod
1647  *    Module.new {|mod| block }   -> mod
1648  *
1649  *  Creates a new anonymous module. If a block is given, it is passed
1650  *  the module object, and the block is evaluated in the context of this
1651  *  module using <code>module_eval</code>.
1652  *
1653  *     fred = Module.new do
1654  *       def meth1
1655  *         "hello"
1656  *       end
1657  *       def meth2
1658  *         "bye"
1659  *       end
1660  *     end
1661  *     a = "my string"
1662  *     a.extend(fred)   #=> "my string"
1663  *     a.meth1          #=> "hello"
1664  *     a.meth2          #=> "bye"
1665  *
1666  *  Assign the module to a constant (name starting uppercase) if you
1667  *  want to treat it like a regular module.
1668  */
1669 
1670 static VALUE
1671 rb_mod_initialize(VALUE module)
1672 {
1673     if (rb_block_given_p()) {
1674         rb_mod_module_exec(1, &module, module);
1675     }
1676     return Qnil;
1677 }
1678 
1679 /*
1680  *  call-seq:
1681  *     Class.new(super_class=Object)               -> a_class
1682  *     Class.new(super_class=Object) { |mod| ... } -> a_class
1683  *
1684  *  Creates a new anonymous (unnamed) class with the given superclass
1685  *  (or <code>Object</code> if no parameter is given). You can give a
1686  *  class a name by assigning the class object to a constant.
1687  *
1688  *  If a block is given, it is passed the class object, and the block
1689  *  is evaluated in the context of this class using
1690  *  <code>class_eval</code>.
1691  *
1692  *     fred = Class.new do
1693  *       def meth1
1694  *         "hello"
1695  *       end
1696  *       def meth2
1697  *         "bye"
1698  *       end
1699  *     end
1700  *
1701  *     a = fred.new     #=> #<#<Class:0x100381890>:0x100376b98>
1702  *     a.meth1          #=> "hello"
1703  *     a.meth2          #=> "bye"
1704  *
1705  *  Assign the class to a constant (name starting uppercase) if you
1706  *  want to treat it like a regular class.
1707  */
1708 
1709 static VALUE
1710 rb_class_initialize(int argc, VALUE *argv, VALUE klass)
1711 {
1712     VALUE super;
1713 
1714     if (RCLASS_SUPER(klass) != 0 || klass == rb_cBasicObject) {
1715         rb_raise(rb_eTypeError, "already initialized class");
1716     }
1717     if (argc == 0) {
1718         super = rb_cObject;
1719     }
1720     else {
1721         rb_scan_args(argc, argv, "01", &super);
1722         rb_check_inheritable(super);
1723         if (super != rb_cBasicObject && !RCLASS_SUPER(super)) {
1724             rb_raise(rb_eTypeError, "can't inherit uninitialized class");
1725         }
1726     }
1727     RCLASS_SET_SUPER(klass, super);
1728     rb_make_metaclass(klass, RBASIC(super)->klass);
1729     rb_class_inherited(super, klass);
1730     rb_mod_initialize(klass);
1731 
1732     return klass;
1733 }
1734 
1735 /*
1736  *  call-seq:
1737  *     class.allocate()   ->   obj
1738  *
1739  *  Allocates space for a new object of <i>class</i>'s class and does not
1740  *  call initialize on the new instance. The returned object must be an
1741  *  instance of <i>class</i>.
1742  *
1743  *      klass = Class.new do
1744  *        def initialize(*args)
1745  *          @initialized = true
1746  *        end
1747  *
1748  *        def initialized?
1749  *          @initialized || false
1750  *        end
1751  *      end
1752  *
1753  *      klass.allocate.initialized? #=> false
1754  *
1755  */
1756 
1757 VALUE
1758 rb_obj_alloc(VALUE klass)
1759 {
1760     VALUE obj;
1761     rb_alloc_func_t allocator;
1762 
1763     if (RCLASS_SUPER(klass) == 0 && klass != rb_cBasicObject) {
1764         rb_raise(rb_eTypeError, "can't instantiate uninitialized class");
1765     }
1766     if (FL_TEST(klass, FL_SINGLETON)) {
1767         rb_raise(rb_eTypeError, "can't create instance of singleton class");
1768     }
1769     allocator = rb_get_alloc_func(klass);
1770     if (!allocator) {
1771         rb_raise(rb_eTypeError, "allocator undefined for %"PRIsVALUE,
1772                  klass);
1773     }
1774 
1775 #if !defined(DTRACE_PROBES_DISABLED) || !DTRACE_PROBES_DISABLED
1776     if (RUBY_DTRACE_OBJECT_CREATE_ENABLED()) {
1777         const char * file = rb_sourcefile();
1778         RUBY_DTRACE_OBJECT_CREATE(rb_class2name(klass),
1779                                   file ? file : "",
1780                                   rb_sourceline());
1781     }
1782 #endif
1783 
1784     obj = (*allocator)(klass);
1785 
1786     if (rb_obj_class(obj) != rb_class_real(klass)) {
1787         rb_raise(rb_eTypeError, "wrong instance allocation");
1788     }
1789     return obj;
1790 }
1791 
1792 static VALUE
1793 rb_class_allocate_instance(VALUE klass)
1794 {
1795     NEWOBJ_OF(obj, struct RObject, klass, T_OBJECT | (RGENGC_WB_PROTECTED_OBJECT ? FL_WB_PROTECTED : 0));
1796     return (VALUE)obj;
1797 }
1798 
1799 /*
1800  *  call-seq:
1801  *     class.new(args, ...)    ->  obj
1802  *
1803  *  Calls <code>allocate</code> to create a new object of
1804  *  <i>class</i>'s class, then invokes that object's
1805  *  <code>initialize</code> method, passing it <i>args</i>.
1806  *  This is the method that ends up getting called whenever
1807  *  an object is constructed using .new.
1808  *
1809  */
1810 
1811 VALUE
1812 rb_class_new_instance(int argc, VALUE *argv, VALUE klass)
1813 {
1814     VALUE obj;
1815 
1816     obj = rb_obj_alloc(klass);
1817     rb_obj_call_init(obj, argc, argv);
1818 
1819     return obj;
1820 }
1821 
1822 /*
1823  *  call-seq:
1824  *     class.superclass -> a_super_class or nil
1825  *
1826  *  Returns the superclass of <i>class</i>, or <code>nil</code>.
1827  *
1828  *     File.superclass          #=> IO
1829  *     IO.superclass            #=> Object
1830  *     Object.superclass        #=> BasicObject
1831  *     class Foo; end
1832  *     class Bar < Foo; end
1833  *     Bar.superclass           #=> Foo
1834  *
1835  *  returns nil when the given class hasn't a parent class:
1836  *
1837  *     BasicObject.superclass   #=> nil
1838  *
1839  */
1840 
1841 VALUE
1842 rb_class_superclass(VALUE klass)
1843 {
1844     VALUE super = RCLASS_SUPER(klass);
1845 
1846     if (!super) {
1847         if (klass == rb_cBasicObject) return Qnil;
1848         rb_raise(rb_eTypeError, "uninitialized class");
1849     }
1850     while (RB_TYPE_P(super, T_ICLASS)) {
1851         super = RCLASS_SUPER(super);
1852     }
1853     if (!super) {
1854         return Qnil;
1855     }
1856     return super;
1857 }
1858 
1859 VALUE
1860 rb_class_get_superclass(VALUE klass)
1861 {
1862     return RCLASS_EXT(klass)->super;
1863 }
1864 
1865 #define id_for_setter(name, type, message) \
1866     check_setter_id(name, rb_is_##type##_id, rb_is_##type##_name, message)
1867 static ID
1868 check_setter_id(VALUE name, int (*valid_id_p)(ID), int (*valid_name_p)(VALUE),
1869                 const char *message)
1870 {
1871     ID id;
1872     if (SYMBOL_P(name)) {
1873         id = SYM2ID(name);
1874         if (!valid_id_p(id)) {
1875             rb_name_error(id, message, QUOTE_ID(id));
1876         }
1877     }
1878     else {
1879         VALUE str = rb_check_string_type(name);
1880         if (NIL_P(str)) {
1881             rb_raise(rb_eTypeError, "%+"PRIsVALUE" is not a symbol or string",
1882                      str);
1883         }
1884         if (!valid_name_p(str)) {
1885             rb_name_error_str(str, message, QUOTE(str));
1886         }
1887         id = rb_to_id(str);
1888     }
1889     return id;
1890 }
1891 
1892 /*
1893  *  call-seq:
1894  *     attr_reader(symbol, ...)  -> nil
1895  *     attr(symbol, ...)         -> nil
1896  *     attr_reader(string, ...)  -> nil
1897  *     attr(string, ...)         -> nil
1898  *
1899  *  Creates instance variables and corresponding methods that return the
1900  *  value of each instance variable. Equivalent to calling
1901  *  ``<code>attr</code><i>:name</i>'' on each name in turn.
1902  *  String arguments are converted to symbols.
1903  */
1904 
1905 static VALUE
1906 rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass)
1907 {
1908     int i;
1909 
1910     for (i=0; i<argc; i++) {
1911         rb_attr(klass, rb_to_id(argv[i]), TRUE, FALSE, TRUE);
1912     }
1913     return Qnil;
1914 }
1915 
1916 VALUE
1917 rb_mod_attr(int argc, VALUE *argv, VALUE klass)
1918 {
1919     if (argc == 2 && (argv[1] == Qtrue || argv[1] == Qfalse)) {
1920         rb_warning("optional boolean argument is obsoleted");
1921         rb_attr(klass, rb_to_id(argv[0]), 1, RTEST(argv[1]), TRUE);
1922         return Qnil;
1923     }
1924     return rb_mod_attr_reader(argc, argv, klass);
1925 }
1926 
1927 /*
1928  *  call-seq:
1929  *      attr_writer(symbol, ...)    -> nil
1930  *      attr_writer(string, ...)    -> nil
1931  *
1932  *  Creates an accessor method to allow assignment to the attribute
1933  *  <i>symbol</i><code>.id2name</code>.
1934  *  String arguments are converted to symbols.
1935  */
1936 
1937 static VALUE
1938 rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass)
1939 {
1940     int i;
1941 
1942     for (i=0; i<argc; i++) {
1943         rb_attr(klass, rb_to_id(argv[i]), FALSE, TRUE, TRUE);
1944     }
1945     return Qnil;
1946 }
1947 
1948 /*
1949  *  call-seq:
1950  *     attr_accessor(symbol, ...)    -> nil
1951  *     attr_accessor(string, ...)    -> nil
1952  *
1953  *  Defines a named attribute for this module, where the name is
1954  *  <i>symbol.</i><code>id2name</code>, creating an instance variable
1955  *  (<code>@name</code>) and a corresponding access method to read it.
1956  *  Also creates a method called <code>name=</code> to set the attribute.
1957  *  String arguments are converted to symbols.
1958  *
1959  *     module Mod
1960  *       attr_accessor(:one, :two)
1961  *     end
1962  *     Mod.instance_methods.sort   #=> [:one, :one=, :two, :two=]
1963  */
1964 
1965 static VALUE
1966 rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass)
1967 {
1968     int i;
1969 
1970     for (i=0; i<argc; i++) {
1971         rb_attr(klass, rb_to_id(argv[i]), TRUE, TRUE, TRUE);
1972     }
1973     return Qnil;
1974 }
1975 
1976 /*
1977  *  call-seq:
1978  *     mod.const_get(sym, inherit=true)    -> obj
1979  *     mod.const_get(str, inherit=true)    -> obj
1980  *
1981  *  Checks for a constant with the given name in <i>mod</i>
1982  *  If +inherit+ is set, the lookup will also search
1983  *  the ancestors (and +Object+ if <i>mod</i> is a +Module+.)
1984  *
1985  *  The value of the constant is returned if a definition is found,
1986  *  otherwise a +NameError+ is raised.
1987  *
1988  *     Math.const_get(:PI)   #=> 3.14159265358979
1989  *
1990  *  This method will recursively look up constant names if a namespaced
1991  *  class name is provided.  For example:
1992  *
1993  *     module Foo; class Bar; end end
1994  *     Object.const_get 'Foo::Bar'
1995  *
1996  *  The +inherit+ flag is respected on each lookup.  For example:
1997  *
1998  *     module Foo
1999  *       class Bar
2000  *         VAL = 10
2001  *       end
2002  *
2003  *       class Baz < Bar; end
2004  *     end
2005  *
2006  *     Object.const_get 'Foo::Baz::VAL'         # => 10
2007  *     Object.const_get 'Foo::Baz::VAL', false  # => NameError
2008  */
2009 
2010 static VALUE
2011 rb_mod_const_get(int argc, VALUE *argv, VALUE mod)
2012 {
2013     VALUE name, recur;
2014     rb_encoding *enc;
2015     const char *pbeg, *p, *path, *pend;
2016     ID id;
2017     int nestable = 1;
2018 
2019     if (argc == 1) {
2020         name = argv[0];
2021         recur = Qtrue;
2022     }
2023     else {
2024         rb_scan_args(argc, argv, "11", &name, &recur);
2025     }
2026 
2027     if (SYMBOL_P(name)) {
2028         name = rb_sym_to_s(name);
2029         nestable = 0;
2030     }
2031 
2032     name = rb_check_string_type(name);
2033     Check_Type(name, T_STRING);
2034 
2035     enc = rb_enc_get(name);
2036     path = RSTRING_PTR(name);
2037 
2038     if (!rb_enc_asciicompat(enc)) {
2039         rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2040     }
2041 
2042     pbeg = p = path;
2043     pend = path + RSTRING_LEN(name);
2044 
2045     if (p >= pend || !*p) {
2046       wrong_name:
2047         rb_raise(rb_eNameError, "wrong constant name %"PRIsVALUE,
2048                  QUOTE(name));
2049     }
2050 
2051     if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2052         if (!nestable) goto wrong_name;
2053         mod = rb_cObject;
2054         p += 2;
2055         pbeg = p;
2056     }
2057 
2058     while (p < pend) {
2059         VALUE part;
2060         long len, beglen;
2061 
2062         while (p < pend && *p != ':') p++;
2063 
2064         if (pbeg == p) goto wrong_name;
2065 
2066         id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2067         beglen = pbeg-path;
2068 
2069         if (p < pend && p[0] == ':') {
2070             if (!nestable) goto wrong_name;
2071             if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2072             p += 2;
2073             pbeg = p;
2074         }
2075 
2076         if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2077             rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2078                      QUOTE(name));
2079         }
2080 
2081         if (!id) {
2082             if (!ISUPPER(*pbeg) || !rb_enc_symname2_p(pbeg, len, enc)) {
2083                 part = rb_str_subseq(name, beglen, len);
2084                 rb_name_error_str(part, "wrong constant name %"PRIsVALUE,
2085                                   QUOTE(part));
2086             }
2087             else if (!rb_method_basic_definition_p(CLASS_OF(mod), id_const_missing)) {
2088                 id = rb_intern3(pbeg, len, enc);
2089             }
2090             else {
2091                 part = rb_str_subseq(name, beglen, len);
2092                 rb_name_error_str(part, "uninitialized constant %"PRIsVALUE"%"PRIsVALUE,
2093                                   rb_str_subseq(name, 0, beglen),
2094                                   QUOTE(part));
2095             }
2096         }
2097         if (!rb_is_const_id(id)) {
2098             rb_name_error(id, "wrong constant name %"PRIsVALUE,
2099                           QUOTE_ID(id));
2100         }
2101         mod = RTEST(recur) ? rb_const_get(mod, id) : rb_const_get_at(mod, id);
2102     }
2103 
2104     return mod;
2105 }
2106 
2107 /*
2108  *  call-seq:
2109  *     mod.const_set(sym, obj)    -> obj
2110  *
2111  *  Sets the named constant to the given object, returning that object.
2112  *  Creates a new constant if no constant with the given name previously
2113  *  existed.
2114  *
2115  *     Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0)   #=> 3.14285714285714
2116  *     Math::HIGH_SCHOOL_PI - Math::PI              #=> 0.00126448926734968
2117  */
2118 
2119 static VALUE
2120 rb_mod_const_set(VALUE mod, VALUE name, VALUE value)
2121 {
2122     ID id = id_for_setter(name, const, "wrong constant name %"PRIsVALUE);
2123     rb_const_set(mod, id, value);
2124     return value;
2125 }
2126 
2127 /*
2128  *  call-seq:
2129  *     mod.const_defined?(sym, inherit=true)   -> true or false
2130  *
2131  *  Checks for a constant with the given name in <i>mod</i>
2132  *  If +inherit+ is set, the lookup will also search
2133  *  the ancestors (and +Object+ if <i>mod</i> is a +Module+.)
2134  *
2135  *  Returns whether or not a definition is found:
2136  *
2137  *     Math.const_defined? "PI"   #=> true
2138  *     IO.const_defined? :SYNC   #=> true
2139  *     IO.const_defined? :SYNC, false   #=> false
2140  */
2141 
2142 static VALUE
2143 rb_mod_const_defined(int argc, VALUE *argv, VALUE mod)
2144 {
2145     VALUE name, recur;
2146     ID id;
2147 
2148     if (argc == 1) {
2149         name = argv[0];
2150         recur = Qtrue;
2151     }
2152     else {
2153         rb_scan_args(argc, argv, "11", &name, &recur);
2154     }
2155     if (!(id = rb_check_id(&name))) {
2156         if (rb_is_const_name(name)) {
2157             return Qfalse;
2158         }
2159         else {
2160             rb_name_error_str(name, "wrong constant name %"PRIsVALUE,
2161                               QUOTE(name));
2162         }
2163     }
2164     if (!rb_is_const_id(id)) {
2165         rb_name_error(id, "wrong constant name %"PRIsVALUE,
2166                       QUOTE_ID(id));
2167     }
2168     return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id);
2169 }
2170 
2171 /*
2172  *  call-seq:
2173  *     obj.instance_variable_get(symbol)    -> obj
2174  *     obj.instance_variable_get(string)    -> obj
2175  *
2176  *  Returns the value of the given instance variable, or nil if the
2177  *  instance variable is not set. The <code>@</code> part of the
2178  *  variable name should be included for regular instance
2179  *  variables. Throws a <code>NameError</code> exception if the
2180  *  supplied symbol is not valid as an instance variable name.
2181  *  String arguments are converted to symbols.
2182  *
2183  *     class Fred
2184  *       def initialize(p1, p2)
2185  *         @a, @b = p1, p2
2186  *       end
2187  *     end
2188  *     fred = Fred.new('cat', 99)
2189  *     fred.instance_variable_get(:@a)    #=> "cat"
2190  *     fred.instance_variable_get("@b")   #=> 99
2191  */
2192 
2193 static VALUE
2194 rb_obj_ivar_get(VALUE obj, VALUE iv)
2195 {
2196     ID id = rb_check_id(&iv);
2197 
2198     if (!id) {
2199         if (rb_is_instance_name(iv)) {
2200             return Qnil;
2201         }
2202         else {
2203             rb_name_error_str(iv, "`%"PRIsVALUE"' is not allowed as an instance variable name",
2204                               QUOTE(iv));
2205         }
2206     }
2207     if (!rb_is_instance_id(id)) {
2208         rb_name_error(id, "`%"PRIsVALUE"' is not allowed as an instance variable name",
2209                       QUOTE_ID(id));
2210     }
2211     return rb_ivar_get(obj, id);
2212 }
2213 
2214 /*
2215  *  call-seq:
2216  *     obj.instance_variable_set(symbol, obj)    -> obj
2217  *     obj.instance_variable_set(string, obj)    -> obj
2218  *
2219  *  Sets the instance variable names by <i>symbol</i> to
2220  *  <i>object</i>, thereby frustrating the efforts of the class's
2221  *  author to attempt to provide proper encapsulation. The variable
2222  *  did not have to exist prior to this call.
2223  *  If the instance variable name is passed as a string, that string
2224  *  is converted to a symbol.
2225  *
2226  *     class Fred
2227  *       def initialize(p1, p2)
2228  *         @a, @b = p1, p2
2229  *       end
2230  *     end
2231  *     fred = Fred.new('cat', 99)
2232  *     fred.instance_variable_set(:@a, 'dog')   #=> "dog"
2233  *     fred.instance_variable_set(:@c, 'cat')   #=> "cat"
2234  *     fred.inspect                             #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
2235  */
2236 
2237 static VALUE
2238 rb_obj_ivar_set(VALUE obj, VALUE iv, VALUE val)
2239 {
2240     ID id = id_for_setter(iv, instance, "`%"PRIsVALUE"' is not allowed as an instance variable name");
2241     return rb_ivar_set(obj, id, val);
2242 }
2243 
2244 /*
2245  *  call-seq:
2246  *     obj.instance_variable_defined?(symbol)    -> true or false
2247  *     obj.instance_variable_defined?(string)    -> true or false
2248  *
2249  *  Returns <code>true</code> if the given instance variable is
2250  *  defined in <i>obj</i>.
2251  *  String arguments are converted to symbols.
2252  *
2253  *     class Fred
2254  *       def initialize(p1, p2)
2255  *         @a, @b = p1, p2
2256  *       end
2257  *     end
2258  *     fred = Fred.new('cat', 99)
2259  *     fred.instance_variable_defined?(:@a)    #=> true
2260  *     fred.instance_variable_defined?("@b")   #=> true
2261  *     fred.instance_variable_defined?("@c")   #=> false
2262  */
2263 
2264 static VALUE
2265 rb_obj_ivar_defined(VALUE obj, VALUE iv)
2266 {
2267     ID id = rb_check_id(&iv);
2268 
2269     if (!id) {
2270         if (rb_is_instance_name(iv)) {
2271             return Qfalse;
2272         }
2273         else {
2274             rb_name_error_str(iv, "`%"PRIsVALUE"' is not allowed as an instance variable name",
2275                               QUOTE(iv));
2276         }
2277     }
2278     if (!rb_is_instance_id(id)) {
2279         rb_name_error(id, "`%"PRIsVALUE"' is not allowed as an instance variable name",
2280                       QUOTE_ID(id));
2281     }
2282     return rb_ivar_defined(obj, id);
2283 }
2284 
2285 /*
2286  *  call-seq:
2287  *     mod.class_variable_get(symbol)    -> obj
2288  *     mod.class_variable_get(string)    -> obj
2289  *
2290  *  Returns the value of the given class variable (or throws a
2291  *  <code>NameError</code> exception). The <code>@@</code> part of the
2292  *  variable name should be included for regular class variables
2293  *  String arguments are converted to symbols.
2294  *
2295  *     class Fred
2296  *       @@foo = 99
2297  *     end
2298  *     Fred.class_variable_get(:@@foo)     #=> 99
2299  */
2300 
2301 static VALUE
2302 rb_mod_cvar_get(VALUE obj, VALUE iv)
2303 {
2304     ID id = rb_check_id(&iv);
2305 
2306     if (!id) {
2307         if (rb_is_class_name(iv)) {
2308             rb_name_error_str(iv, "uninitialized class variable %"PRIsVALUE" in %"PRIsVALUE"",
2309                               iv, rb_class_name(obj));
2310         }
2311         else {
2312             rb_name_error_str(iv, "`%"PRIsVALUE"' is not allowed as a class variable name",
2313                               QUOTE(iv));
2314         }
2315     }
2316     if (!rb_is_class_id(id)) {
2317         rb_name_error(id, "`%"PRIsVALUE"' is not allowed as a class variable name",
2318                       QUOTE_ID(id));
2319     }
2320     return rb_cvar_get(obj, id);
2321 }
2322 
2323 /*
2324  *  call-seq:
2325  *     obj.class_variable_set(symbol, obj)    -> obj
2326  *     obj.class_variable_set(string, obj)    -> obj
2327  *
2328  *  Sets the class variable names by <i>symbol</i> to
2329  *  <i>object</i>.
2330  *  If the class variable name is passed as a string, that string
2331  *  is converted to a symbol.
2332  *
2333  *     class Fred
2334  *       @@foo = 99
2335  *       def foo
2336  *         @@foo
2337  *       end
2338  *     end
2339  *     Fred.class_variable_set(:@@foo, 101)     #=> 101
2340  *     Fred.new.foo                             #=> 101
2341  */
2342 
2343 static VALUE
2344 rb_mod_cvar_set(VALUE obj, VALUE iv, VALUE val)
2345 {
2346     ID id = id_for_setter(iv, class, "`%"PRIsVALUE"' is not allowed as a class variable name");
2347     rb_cvar_set(obj, id, val);
2348     return val;
2349 }
2350 
2351 /*
2352  *  call-seq:
2353  *     obj.class_variable_defined?(symbol)    -> true or false
2354  *     obj.class_variable_defined?(string)    -> true or false
2355  *
2356  *  Returns <code>true</code> if the given class variable is defined
2357  *  in <i>obj</i>.
2358  *  String arguments are converted to symbols.
2359  *
2360  *     class Fred
2361  *       @@foo = 99
2362  *     end
2363  *     Fred.class_variable_defined?(:@@foo)    #=> true
2364  *     Fred.class_variable_defined?(:@@bar)    #=> false
2365  */
2366 
2367 static VALUE
2368 rb_mod_cvar_defined(VALUE obj, VALUE iv)
2369 {
2370     ID id = rb_check_id(&iv);
2371 
2372     if (!id) {
2373         if (rb_is_class_name(iv)) {
2374             return Qfalse;
2375         }
2376         else {
2377             rb_name_error_str(iv, "`%"PRIsVALUE"' is not allowed as a class variable name",
2378                               QUOTE(iv));
2379         }
2380     }
2381     if (!rb_is_class_id(id)) {
2382         rb_name_error(id, "`%"PRIsVALUE"' is not allowed as a class variable name",
2383                       QUOTE_ID(id));
2384     }
2385     return rb_cvar_defined(obj, id);
2386 }
2387 
2388 static struct conv_method_tbl {
2389     const char *method;
2390     ID id;
2391 } conv_method_names[] = {
2392     {"to_int", 0},
2393     {"to_ary", 0},
2394     {"to_str", 0},
2395     {"to_sym", 0},
2396     {"to_hash", 0},
2397     {"to_proc", 0},
2398     {"to_io", 0},
2399     {"to_a", 0},
2400     {"to_s", 0},
2401     {NULL, 0}
2402 };
2403 #define IMPLICIT_CONVERSIONS 7
2404 
2405 static VALUE
2406 convert_type(VALUE val, const char *tname, const char *method, int raise)
2407 {
2408     ID m = 0;
2409     int i;
2410     VALUE r;
2411 
2412     for (i=0; conv_method_names[i].method; i++) {
2413         if (conv_method_names[i].method[0] == method[0] &&
2414             strcmp(conv_method_names[i].method, method) == 0) {
2415             m = conv_method_names[i].id;
2416             break;
2417         }
2418     }
2419     if (!m) m = rb_intern(method);
2420     r = rb_check_funcall(val, m, 0, 0);
2421     if (r == Qundef) {
2422         if (raise) {
2423             rb_raise(rb_eTypeError, i < IMPLICIT_CONVERSIONS
2424                 ? "no implicit conversion of %s into %s"
2425                 : "can't convert %s into %s",
2426                      NIL_P(val) ? "nil" :
2427                      val == Qtrue ? "true" :
2428                      val == Qfalse ? "false" :
2429                      rb_obj_classname(val),
2430                      tname);
2431         }
2432         return Qnil;
2433     }
2434     return r;
2435 }
2436 
2437 VALUE
2438 rb_convert_type(VALUE val, int type, const char *tname, const char *method)
2439 {
2440     VALUE v;
2441 
2442     if (TYPE(val) == type) return val;
2443     v = convert_type(val, tname, method, TRUE);
2444     if (TYPE(v) != type) {
2445         const char *cname = rb_obj_classname(val);
2446         rb_raise(rb_eTypeError, "can't convert %s to %s (%s#%s gives %s)",
2447                  cname, tname, cname, method, rb_obj_classname(v));
2448     }
2449     return v;
2450 }
2451 
2452 VALUE
2453 rb_check_convert_type(VALUE val, int type, const char *tname, const char *method)
2454 {
2455     VALUE v;
2456 
2457     /* always convert T_DATA */
2458     if (TYPE(val) == type && type != T_DATA) return val;
2459     v = convert_type(val, tname, method, FALSE);
2460     if (NIL_P(v)) return Qnil;
2461     if (TYPE(v) != type) {
2462         const char *cname = rb_obj_classname(val);
2463         rb_raise(rb_eTypeError, "can't convert %s to %s (%s#%s gives %s)",
2464                  cname, tname, cname, method, rb_obj_classname(v));
2465     }
2466     return v;
2467 }
2468 
2469 
2470 static VALUE
2471 rb_to_integer(VALUE val, const char *method)
2472 {
2473     VALUE v;
2474 
2475     if (FIXNUM_P(val)) return val;
2476     if (RB_TYPE_P(val, T_BIGNUM)) return val;
2477     v = convert_type(val, "Integer", method, TRUE);
2478     if (!rb_obj_is_kind_of(v, rb_cInteger)) {
2479         const char *cname = rb_obj_classname(val);
2480         rb_raise(rb_eTypeError, "can't convert %s to Integer (%s#%s gives %s)",
2481                  cname, cname, method, rb_obj_classname(v));
2482     }
2483     return v;
2484 }
2485 
2486 VALUE
2487 rb_check_to_integer(VALUE val, const char *method)
2488 {
2489     VALUE v;
2490 
2491     if (FIXNUM_P(val)) return val;
2492     if (RB_TYPE_P(val, T_BIGNUM)) return val;
2493     v = convert_type(val, "Integer", method, FALSE);
2494     if (!rb_obj_is_kind_of(v, rb_cInteger)) {
2495         return Qnil;
2496     }
2497     return v;
2498 }
2499 
2500 VALUE
2501 rb_to_int(VALUE val)
2502 {
2503     return rb_to_integer(val, "to_int");
2504 }
2505 
2506 VALUE
2507 rb_check_to_int(VALUE val)
2508 {
2509     return rb_check_to_integer(val, "to_int");
2510 }
2511 
2512 static VALUE
2513 rb_convert_to_integer(VALUE val, int base)
2514 {
2515     VALUE tmp;
2516 
2517     switch (TYPE(val)) {
2518       case T_FLOAT:
2519         if (base != 0) goto arg_error;
2520         if (RFLOAT_VALUE(val) <= (double)FIXNUM_MAX
2521             && RFLOAT_VALUE(val) >= (double)FIXNUM_MIN) {
2522             break;
2523         }
2524         return rb_dbl2big(RFLOAT_VALUE(val));
2525 
2526       case T_FIXNUM:
2527       case T_BIGNUM:
2528         if (base != 0) goto arg_error;
2529         return val;
2530 
2531       case T_STRING:
2532       string_conv:
2533         return rb_str_to_inum(val, base, TRUE);
2534 
2535       case T_NIL:
2536         if (base != 0) goto arg_error;
2537         rb_raise(rb_eTypeError, "can't convert nil into Integer");
2538         break;
2539 
2540       default:
2541         break;
2542     }
2543     if (base != 0) {
2544         tmp = rb_check_string_type(val);
2545         if (!NIL_P(tmp)) goto string_conv;
2546       arg_error:
2547         rb_raise(rb_eArgError, "base specified for non string value");
2548     }
2549     tmp = convert_type(val, "Integer", "to_int", FALSE);
2550     if (NIL_P(tmp)) {
2551         return rb_to_integer(val, "to_i");
2552     }
2553     return tmp;
2554 
2555 }
2556 
2557 VALUE
2558 rb_Integer(VALUE val)
2559 {
2560     return rb_convert_to_integer(val, 0);
2561 }
2562 
2563 /*
2564  *  call-seq:
2565  *     Integer(arg,base=0)    -> integer
2566  *
2567  *  Converts <i>arg</i> to a <code>Fixnum</code> or <code>Bignum</code>.
2568  *  Numeric types are converted directly (with floating point numbers
2569  *  being truncated).    <i>base</i> (0, or between 2 and 36) is a base for
2570  *  integer string representation.  If <i>arg</i> is a <code>String</code>,
2571  *  when <i>base</i> is omitted or equals to zero, radix indicators
2572  *  (<code>0</code>, <code>0b</code>, and <code>0x</code>) are honored.
2573  *  In any case, strings should be strictly conformed to numeric
2574  *  representation. This behavior is different from that of
2575  *  <code>String#to_i</code>.  Non string values will be converted using
2576  *  <code>to_int</code>, and <code>to_i</code>.
2577  *
2578  *     Integer(123.999)    #=> 123
2579  *     Integer("0x1a")     #=> 26
2580  *     Integer(Time.new)   #=> 1204973019
2581  *     Integer("0930", 10) #=> 930
2582  *     Integer("111", 2)   #=> 7
2583  */
2584 
2585 static VALUE
2586 rb_f_integer(int argc, VALUE *argv, VALUE obj)
2587 {
2588     VALUE arg = Qnil;
2589     int base = 0;
2590 
2591     switch (argc) {
2592       case 2:
2593         base = NUM2INT(argv[1]);
2594       case 1:
2595         arg = argv[0];
2596         break;
2597       default:
2598         /* should cause ArgumentError */
2599         rb_scan_args(argc, argv, "11", NULL, NULL);
2600     }
2601     return rb_convert_to_integer(arg, base);
2602 }
2603 
2604 double
2605 rb_cstr_to_dbl(const char *p, int badcheck)
2606 {
2607     const char *q;
2608     char *end;
2609     double d;
2610     const char *ellipsis = "";
2611     int w;
2612     enum {max_width = 20};
2613 #define OutOfRange() ((end - p > max_width) ? \
2614                       (w = max_width, ellipsis = "...") : \
2615                       (w = (int)(end - p), ellipsis = ""))
2616 
2617     if (!p) return 0.0;
2618     q = p;
2619     while (ISSPACE(*p)) p++;
2620 
2621     if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
2622         return 0.0;
2623     }
2624 
2625     d = strtod(p, &end);
2626     if (errno == ERANGE) {
2627         OutOfRange();
2628         rb_warning("Float %.*s%s out of range", w, p, ellipsis);
2629         errno = 0;
2630     }
2631     if (p == end) {
2632         if (badcheck) {
2633           bad:
2634             rb_invalid_str(q, "Float()");
2635         }
2636         return d;
2637     }
2638     if (*end) {
2639         char buf[DBL_DIG * 4 + 10];
2640         char *n = buf;
2641         char *e = buf + sizeof(buf) - 1;
2642         char prev = 0;
2643 
2644         while (p < end && n < e) prev = *n++ = *p++;
2645         while (*p) {
2646             if (*p == '_') {
2647                 /* remove underscores between digits */
2648                 if (badcheck) {
2649                     if (n == buf || !ISDIGIT(prev)) goto bad;
2650                     ++p;
2651                     if (!ISDIGIT(*p)) goto bad;
2652                 }
2653                 else {
2654                     while (*++p == '_');
2655                     continue;
2656                 }
2657             }
2658             prev = *p++;
2659             if (n < e) *n++ = prev;
2660         }
2661         *n = '\0';
2662         p = buf;
2663 
2664         if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
2665             return 0.0;
2666         }
2667 
2668         d = strtod(p, &end);
2669         if (errno == ERANGE) {
2670             OutOfRange();
2671             rb_warning("Float %.*s%s out of range", w, p, ellipsis);
2672             errno = 0;
2673         }
2674         if (badcheck) {
2675             if (!end || p == end) goto bad;
2676             while (*end && ISSPACE(*end)) end++;
2677             if (*end) goto bad;
2678         }
2679     }
2680     if (errno == ERANGE) {
2681         errno = 0;
2682         OutOfRange();
2683         rb_raise(rb_eArgError, "Float %.*s%s out of range", w, q, ellipsis);
2684     }
2685     return d;
2686 }
2687 
2688 double
2689 rb_str_to_dbl(VALUE str, int badcheck)
2690 {
2691     char *s;
2692     long len;
2693     double ret;
2694     VALUE v = 0;
2695 
2696     StringValue(str);
2697     s = RSTRING_PTR(str);
2698     len = RSTRING_LEN(str);
2699     if (s) {
2700         if (badcheck && memchr(s, '\0', len)) {
2701             rb_raise(rb_eArgError, "string for Float contains null byte");
2702         }
2703         if (s[len]) {           /* no sentinel somehow */
2704             char *p =  ALLOCV(v, len);
2705             MEMCPY(p, s, char, len);
2706             p[len] = '\0';
2707             s = p;
2708         }
2709     }
2710     ret = rb_cstr_to_dbl(s, badcheck);
2711     if (v)
2712         ALLOCV_END(v);
2713     return ret;
2714 }
2715 
2716 VALUE
2717 rb_Float(VALUE val)
2718 {
2719     switch (TYPE(val)) {
2720       case T_FIXNUM:
2721         return DBL2NUM((double)FIX2LONG(val));
2722 
2723       case T_FLOAT:
2724         return val;
2725 
2726       case T_BIGNUM:
2727         return DBL2NUM(rb_big2dbl(val));
2728 
2729       case T_STRING:
2730         return DBL2NUM(rb_str_to_dbl(val, TRUE));
2731 
2732       case T_NIL:
2733         rb_raise(rb_eTypeError, "can't convert nil into Float");
2734         break;
2735 
2736       default:
2737         return rb_convert_type(val, T_FLOAT, "Float", "to_f");
2738     }
2739 
2740     UNREACHABLE;
2741 }
2742 
2743 /*
2744  *  call-seq:
2745  *     Float(arg)    -> float
2746  *
2747  *  Returns <i>arg</i> converted to a float. Numeric types are converted
2748  *  directly, the rest are converted using <i>arg</i>.to_f. As of Ruby
2749  *  1.8, converting <code>nil</code> generates a <code>TypeError</code>.
2750  *
2751  *     Float(1)           #=> 1.0
2752  *     Float("123.456")   #=> 123.456
2753  */
2754 
2755 static VALUE
2756 rb_f_float(VALUE obj, VALUE arg)
2757 {
2758     return rb_Float(arg);
2759 }
2760 
2761 VALUE
2762 rb_to_float(VALUE val)
2763 {
2764     if (RB_TYPE_P(val, T_FLOAT)) return val;
2765     if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
2766         rb_raise(rb_eTypeError, "can't convert %s into Float",
2767                  NIL_P(val) ? "nil" :
2768                  val == Qtrue ? "true" :
2769                  val == Qfalse ? "false" :
2770                  rb_obj_classname(val));
2771     }
2772     return rb_convert_type(val, T_FLOAT, "Float", "to_f");
2773 }
2774 
2775 VALUE
2776 rb_check_to_float(VALUE val)
2777 {
2778     if (RB_TYPE_P(val, T_FLOAT)) return val;
2779     if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
2780         return Qnil;
2781     }
2782     return rb_check_convert_type(val, T_FLOAT, "Float", "to_f");
2783 }
2784 
2785 double
2786 rb_num2dbl(VALUE val)
2787 {
2788     switch (TYPE(val)) {
2789       case T_FLOAT:
2790         return RFLOAT_VALUE(val);
2791 
2792       case T_STRING:
2793         rb_raise(rb_eTypeError, "no implicit conversion to float from string");
2794         break;
2795 
2796       case T_NIL:
2797         rb_raise(rb_eTypeError, "no implicit conversion to float from nil");
2798         break;
2799 
2800       default:
2801         break;
2802     }
2803 
2804     return RFLOAT_VALUE(rb_Float(val));
2805 }
2806 
2807 VALUE
2808 rb_String(VALUE val)
2809 {
2810     VALUE tmp = rb_check_string_type(val);
2811     if (NIL_P(tmp))
2812         tmp = rb_convert_type(val, T_STRING, "String", "to_s");
2813     return tmp;
2814 }
2815 
2816 
2817 /*
2818  *  call-seq:
2819  *     String(arg)   -> string
2820  *
2821  *  Converts <i>arg</i> to a <code>String</code> by calling its
2822  *  <code>to_s</code> method.
2823  *
2824  *     String(self)        #=> "main"
2825  *     String(self.class)  #=> "Object"
2826  *     String(123456)      #=> "123456"
2827  */
2828 
2829 static VALUE
2830 rb_f_string(VALUE obj, VALUE arg)
2831 {
2832     return rb_String(arg);
2833 }
2834 
2835 VALUE
2836 rb_Array(VALUE val)
2837 {
2838     VALUE tmp = rb_check_array_type(val);
2839 
2840     if (NIL_P(tmp)) {
2841         tmp = rb_check_convert_type(val, T_ARRAY, "Array", "to_a");
2842         if (NIL_P(tmp)) {
2843             return rb_ary_new3(1, val);
2844         }
2845     }
2846     return tmp;
2847 }
2848 
2849 /*
2850  *  call-seq:
2851  *     Array(arg)    -> array
2852  *
2853  *  Returns +arg+ as an Array.
2854  *
2855  *  First tries to call Array#to_ary on +arg+, then Array#to_a.
2856  *
2857  *     Array(1..5)   #=> [1, 2, 3, 4, 5]
2858  */
2859 
2860 static VALUE
2861 rb_f_array(VALUE obj, VALUE arg)
2862 {
2863     return rb_Array(arg);
2864 }
2865 
2866 VALUE
2867 rb_Hash(VALUE val)
2868 {
2869     VALUE tmp;
2870 
2871     if (NIL_P(val)) return rb_hash_new();
2872     tmp = rb_check_hash_type(val);
2873     if (NIL_P(tmp)) {
2874         if (RB_TYPE_P(val, T_ARRAY) && RARRAY_LEN(val) == 0)
2875             return rb_hash_new();
2876         rb_raise(rb_eTypeError, "can't convert %s into Hash", rb_obj_classname(val));
2877     }
2878     return tmp;
2879 }
2880 
2881 /*
2882  *  call-seq:
2883  *     Hash(arg)    -> hash
2884  *
2885  *  Converts <i>arg</i> to a <code>Hash</code> by calling
2886  *  <i>arg</i><code>.to_hash</code>. Returns an empty <code>Hash</code> when
2887  *  <i>arg</i> is <tt>nil</tt> or <tt>[]</tt>.
2888  *
2889  *     Hash([])          #=> {}
2890  *     Hash(nil)         #=> {}
2891  *     Hash(key: :value) #=> {:key => :value}
2892  *     Hash([1, 2, 3])   #=> TypeError
2893  */
2894 
2895 static VALUE
2896 rb_f_hash(VALUE obj, VALUE arg)
2897 {
2898     return rb_Hash(arg);
2899 }
2900 
2901 /*
2902  *  Document-class: Class
2903  *
2904  *  Classes in Ruby are first-class objects---each is an instance of
2905  *  class <code>Class</code>.
2906  *
2907  *  Typically, you create a new class by using:
2908  *
2909  *    class Name
2910  *     # some class describing the class behavior
2911  *    end
2912  *
2913  *  When a new class is created, an object of type Class is initialized and
2914  *  assigned to a global constant (<code>Name</code> in this case).
2915  *
2916  *  When <code>Name.new</code> is called to create a new object, the
2917  *  <code>new</code> method in <code>Class</code> is run by default.
2918  *  This can be demonstrated by overriding <code>new</code> in
2919  *  <code>Class</code>:
2920  *
2921  *     class Class
2922  *        alias oldNew  new
2923  *        def new(*args)
2924  *          print "Creating a new ", self.name, "\n"
2925  *          oldNew(*args)
2926  *        end
2927  *      end
2928  *
2929  *
2930  *      class Name
2931  *      end
2932  *
2933  *
2934  *      n = Name.new
2935  *
2936  *  <em>produces:</em>
2937  *
2938  *     Creating a new Name
2939  *
2940  *  Classes, modules, and objects are interrelated. In the diagram
2941  *  that follows, the vertical arrows represent inheritance, and the
2942  *  parentheses meta-classes. All metaclasses are instances
2943  *  of the class `Class'.
2944  *                             +---------+             +-...
2945  *                             |         |             |
2946  *             BasicObject-----|-->(BasicObject)-------|-...
2947  *                 ^           |         ^             |
2948  *                 |           |         |             |
2949  *              Object---------|----->(Object)---------|-...
2950  *                 ^           |         ^             |
2951  *                 |           |         |             |
2952  *                 +-------+   |         +--------+    |
2953  *                 |       |   |         |        |    |
2954  *                 |    Module-|---------|--->(Module)-|-...
2955  *                 |       ^   |         |        ^    |
2956  *                 |       |   |         |        |    |
2957  *                 |     Class-|---------|---->(Class)-|-...
2958  *                 |       ^   |         |        ^    |
2959  *                 |       +---+         |        +----+
2960  *                 |                     |
2961  *    obj--->OtherClass---------->(OtherClass)-----------...
2962  *
2963  */
2964 
2965 
2966 /*!
2967  * Initializes the world of objects and classes.
2968  *
2969  * At first, the function bootstraps the class hierarchy.
2970  * It initializes the most fundamental classes and their metaclasses.
2971  * - \c BasicObject
2972  * - \c Object
2973  * - \c Module
2974  * - \c Class
2975  * After the bootstrap step, the class hierarchy becomes as the following
2976  * diagram.
2977  *
2978  * \image html boottime-classes.png
2979  *
2980  * Then, the function defines classes, modules and methods as usual.
2981  * \ingroup class
2982  */
2983 
2984 /*  Document-class: BasicObject
2985  *
2986  *  BasicObject is the parent class of all classes in Ruby.  It's an explicit
2987  *  blank class.
2988  *
2989  *  BasicObject can be used for creating object hierarchies independent of
2990  *  Ruby's object hierarchy, proxy objects like the Delegator class, or other
2991  *  uses where namespace pollution from Ruby's methods and classes must be
2992  *  avoided.
2993  *
2994  *  To avoid polluting BasicObject for other users an appropriately named
2995  *  subclass of BasicObject should be created instead of directly modifying
2996  *  BasicObject:
2997  *
2998  *    class MyObjectSystem < BasicObject
2999  *    end
3000  *
3001  *  BasicObject does not include Kernel (for methods like +puts+) and
3002  *  BasicObject is outside of the namespace of the standard library so common
3003  *  classes will not be found without a using a full class path.
3004  *
3005  *  A variety of strategies can be used to provide useful portions of the
3006  *  standard library to subclasses of BasicObject.  A subclass could
3007  *  <code>include Kernel</code> to obtain +puts+, +exit+, etc.  A custom
3008  *  Kernel-like module could be created and included or delegation can be used
3009  *  via #method_missing:
3010  *
3011  *    class MyObjectSystem < BasicObject
3012  *      DELEGATE = [:puts, :p]
3013  *
3014  *      def method_missing(name, *args, &block)
3015  *        super unless DELEGATE.include? name
3016  *        ::Kernel.send(name, *args, &block)
3017  *      end
3018  *
3019  *      def respond_to_missing?(name, include_private = false)
3020  *        DELEGATE.include?(name) or super
3021  *      end
3022  *    end
3023  *
3024  *  Access to classes and modules from the Ruby standard library can be
3025  *  obtained in a BasicObject subclass by referencing the desired constant
3026  *  from the root like <code>::File</code> or <code>::Enumerator</code>.
3027  *  Like #method_missing, #const_missing can be used to delegate constant
3028  *  lookup to +Object+:
3029  *
3030  *    class MyObjectSystem < BasicObject
3031  *      def self.const_missing(name)
3032  *        ::Object.const_get(name)
3033  *      end
3034  *    end
3035  */
3036 
3037 /*  Document-class: Object
3038  *
3039  *  Object is the default root of all Ruby objects.  Object inherits from
3040  *  BasicObject which allows creating alternate object hierarchies.  Methods
3041  *  on object are available to all classes unless explicitly overridden.
3042  *
3043  *  Object mixes in the Kernel module, making the built-in kernel functions
3044  *  globally accessible.  Although the instance methods of Object are defined
3045  *  by the Kernel module, we have chosen to document them here for clarity.
3046  *
3047  *  When referencing constants in classes inheriting from Object you do not
3048  *  need to use the full namespace.  For example, referencing +File+ inside
3049  *  +YourClass+ will find the top-level File class.
3050  *
3051  *  In the descriptions of Object's methods, the parameter <i>symbol</i> refers
3052  *  to a symbol, which is either a quoted string or a Symbol (such as
3053  *  <code>:name</code>).
3054  */
3055 
3056 void
3057 Init_Object(void)
3058 {
3059     int i;
3060 
3061     Init_class_hierarchy();
3062 
3063 #if 0
3064     // teach RDoc about these classes
3065     rb_cBasicObject = rb_define_class("BasicObject", Qnil);
3066     rb_cObject = rb_define_class("Object", rb_cBasicObject);
3067     rb_cModule = rb_define_class("Module", rb_cObject);
3068     rb_cClass =  rb_define_class("Class",  rb_cModule);
3069 #endif
3070 
3071 #undef rb_intern
3072 #define rb_intern(str) rb_intern_const(str)
3073 
3074     rb_define_private_method(rb_cBasicObject, "initialize", rb_obj_dummy, 0);
3075     rb_define_alloc_func(rb_cBasicObject, rb_class_allocate_instance);
3076     rb_define_method(rb_cBasicObject, "==", rb_obj_equal, 1);
3077     rb_define_method(rb_cBasicObject, "equal?", rb_obj_equal, 1);
3078     rb_define_method(rb_cBasicObject, "!", rb_obj_not, 0);
3079     rb_define_method(rb_cBasicObject, "!=", rb_obj_not_equal, 1);
3080 
3081     rb_define_private_method(rb_cBasicObject, "singleton_method_added", rb_obj_dummy, 1);
3082     rb_define_private_method(rb_cBasicObject, "singleton_method_removed", rb_obj_dummy, 1);
3083     rb_define_private_method(rb_cBasicObject, "singleton_method_undefined", rb_obj_dummy, 1);
3084 
3085     /* Document-module: Kernel
3086      *
3087      * The Kernel module is included by class Object, so its methods are
3088      * available in every Ruby object.
3089      *
3090      * The Kernel instance methods are documented in class Object while the
3091      * module methods are documented here.  These methods are called without a
3092      * receiver and thus can be called in functional form:
3093      *
3094      *   sprintf "%.1f", 1.234 #=> "1.2"
3095      *
3096      */
3097     rb_mKernel = rb_define_module("Kernel");
3098     rb_include_module(rb_cObject, rb_mKernel);
3099     rb_define_private_method(rb_cClass, "inherited", rb_obj_dummy, 1);
3100     rb_define_private_method(rb_cModule, "included", rb_obj_dummy, 1);
3101     rb_define_private_method(rb_cModule, "extended", rb_obj_dummy, 1);
3102     rb_define_private_method(rb_cModule, "prepended", rb_obj_dummy, 1);
3103     rb_define_private_method(rb_cModule, "method_added", rb_obj_dummy, 1);
3104     rb_define_private_method(rb_cModule, "method_removed", rb_obj_dummy, 1);
3105     rb_define_private_method(rb_cModule, "method_undefined", rb_obj_dummy, 1);
3106 
3107     rb_define_method(rb_mKernel, "nil?", rb_false, 0);
3108     rb_define_method(rb_mKernel, "===", rb_equal, 1);
3109     rb_define_method(rb_mKernel, "=~", rb_obj_match, 1);
3110     rb_define_method(rb_mKernel, "!~", rb_obj_not_match, 1);
3111     rb_define_method(rb_mKernel, "eql?", rb_obj_equal, 1);
3112     rb_define_method(rb_mKernel, "hash", rb_obj_hash, 0);
3113     rb_define_method(rb_mKernel, "<=>", rb_obj_cmp, 1);
3114 
3115     rb_define_method(rb_mKernel, "class", rb_obj_class, 0);
3116     rb_define_method(rb_mKernel, "singleton_class", rb_obj_singleton_class, 0);
3117     rb_define_method(rb_mKernel, "clone", rb_obj_clone, 0);
3118     rb_define_method(rb_mKernel, "dup", rb_obj_dup, 0);
3119     rb_define_method(rb_mKernel, "initialize_copy", rb_obj_init_copy, 1);
3120     rb_define_method(rb_mKernel, "initialize_dup", rb_obj_init_dup_clone, 1);
3121     rb_define_method(rb_mKernel, "initialize_clone", rb_obj_init_dup_clone, 1);
3122 
3123     rb_define_method(rb_mKernel, "taint", rb_obj_taint, 0);
3124     rb_define_method(rb_mKernel, "tainted?", rb_obj_tainted, 0);
3125     rb_define_method(rb_mKernel, "untaint", rb_obj_untaint, 0);
3126     rb_define_method(rb_mKernel, "untrust", rb_obj_untrust, 0);
3127     rb_define_method(rb_mKernel, "untrusted?", rb_obj_untrusted, 0);
3128     rb_define_method(rb_mKernel, "trust", rb_obj_trust, 0);
3129     rb_define_method(rb_mKernel, "freeze", rb_obj_freeze, 0);
3130     rb_define_method(rb_mKernel, "frozen?", rb_obj_frozen_p, 0);
3131 
3132     rb_define_method(rb_mKernel, "to_s", rb_any_to_s, 0);
3133     rb_define_method(rb_mKernel, "inspect", rb_obj_inspect, 0);
3134     rb_define_method(rb_mKernel, "methods", rb_obj_methods, -1); /* in class.c */
3135     rb_define_method(rb_mKernel, "singleton_methods", rb_obj_singleton_methods, -1); /* in class.c */
3136     rb_define_method(rb_mKernel, "protected_methods", rb_obj_protected_methods, -1); /* in class.c */
3137     rb_define_method(rb_mKernel, "private_methods", rb_obj_private_methods, -1); /* in class.c */
3138     rb_define_method(rb_mKernel, "public_methods", rb_obj_public_methods, -1); /* in class.c */
3139     rb_define_method(rb_mKernel, "instance_variables", rb_obj_instance_variables, 0); /* in variable.c */
3140     rb_define_method(rb_mKernel, "instance_variable_get", rb_obj_ivar_get, 1);
3141     rb_define_method(rb_mKernel, "instance_variable_set", rb_obj_ivar_set, 2);
3142     rb_define_method(rb_mKernel, "instance_variable_defined?", rb_obj_ivar_defined, 1);
3143     rb_define_method(rb_mKernel, "remove_instance_variable",
3144                      rb_obj_remove_instance_variable, 1); /* in variable.c */
3145 
3146     rb_define_method(rb_mKernel, "instance_of?", rb_obj_is_instance_of, 1);
3147     rb_define_method(rb_mKernel, "kind_of?", rb_obj_is_kind_of, 1);
3148     rb_define_method(rb_mKernel, "is_a?", rb_obj_is_kind_of, 1);
3149     rb_define_method(rb_mKernel, "tap", rb_obj_tap, 0);
3150 
3151     rb_define_global_function("sprintf", rb_f_sprintf, -1); /* in sprintf.c */
3152     rb_define_global_function("format", rb_f_sprintf, -1);  /* in sprintf.c */
3153 
3154     rb_define_global_function("Integer", rb_f_integer, -1);
3155     rb_define_global_function("Float", rb_f_float, 1);
3156 
3157     rb_define_global_function("String", rb_f_string, 1);
3158     rb_define_global_function("Array", rb_f_array, 1);
3159     rb_define_global_function("Hash", rb_f_hash, 1);
3160 
3161     rb_cNilClass = rb_define_class("NilClass", rb_cObject);
3162     rb_define_method(rb_cNilClass, "to_i", nil_to_i, 0);
3163     rb_define_method(rb_cNilClass, "to_f", nil_to_f, 0);
3164     rb_define_method(rb_cNilClass, "to_s", nil_to_s, 0);
3165     rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0);
3166     rb_define_method(rb_cNilClass, "to_h", nil_to_h, 0);
3167     rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0);
3168     rb_define_method(rb_cNilClass, "&", false_and, 1);
3169     rb_define_method(rb_cNilClass, "|", false_or, 1);
3170     rb_define_method(rb_cNilClass, "^", false_xor, 1);
3171 
3172     rb_define_method(rb_cNilClass, "nil?", rb_true, 0);
3173     rb_undef_alloc_func(rb_cNilClass);
3174     rb_undef_method(CLASS_OF(rb_cNilClass), "new");
3175     /*
3176      * An alias of +nil+
3177      */
3178     rb_define_global_const("NIL", Qnil);
3179 
3180     rb_define_method(rb_cModule, "freeze", rb_mod_freeze, 0);
3181     rb_define_method(rb_cModule, "===", rb_mod_eqq, 1);
3182     rb_define_method(rb_cModule, "==", rb_obj_equal, 1);
3183     rb_define_method(rb_cModule, "<=>",  rb_mod_cmp, 1);
3184     rb_define_method(rb_cModule, "<",  rb_mod_lt, 1);
3185     rb_define_method(rb_cModule, "<=", rb_class_inherited_p, 1);
3186     rb_define_method(rb_cModule, ">",  rb_mod_gt, 1);
3187     rb_define_method(rb_cModule, ">=", rb_mod_ge, 1);
3188     rb_define_method(rb_cModule, "initialize_copy", rb_mod_init_copy, 1); /* in class.c */
3189     rb_define_method(rb_cModule, "to_s", rb_mod_to_s, 0);
3190     rb_define_alias(rb_cModule, "inspect", "to_s");
3191     rb_define_method(rb_cModule, "included_modules", rb_mod_included_modules, 0); /* in class.c */
3192     rb_define_method(rb_cModule, "include?", rb_mod_include_p, 1); /* in class.c */
3193     rb_define_method(rb_cModule, "name", rb_mod_name, 0);  /* in variable.c */
3194     rb_define_method(rb_cModule, "ancestors", rb_mod_ancestors, 0); /* in class.c */
3195 
3196     rb_define_private_method(rb_cModule, "attr", rb_mod_attr, -1);
3197     rb_define_private_method(rb_cModule, "attr_reader", rb_mod_attr_reader, -1);
3198     rb_define_private_method(rb_cModule, "attr_writer", rb_mod_attr_writer, -1);
3199     rb_define_private_method(rb_cModule, "attr_accessor", rb_mod_attr_accessor, -1);
3200 
3201     rb_define_alloc_func(rb_cModule, rb_module_s_alloc);
3202     rb_define_method(rb_cModule, "initialize", rb_mod_initialize, 0);
3203     rb_define_method(rb_cModule, "instance_methods", rb_class_instance_methods, -1); /* in class.c */
3204     rb_define_method(rb_cModule, "public_instance_methods",
3205                      rb_class_public_instance_methods, -1);    /* in class.c */
3206     rb_define_method(rb_cModule, "protected_instance_methods",
3207                      rb_class_protected_instance_methods, -1); /* in class.c */
3208     rb_define_method(rb_cModule, "private_instance_methods",
3209                      rb_class_private_instance_methods, -1);   /* in class.c */
3210 
3211     rb_define_method(rb_cModule, "constants", rb_mod_constants, -1); /* in variable.c */
3212     rb_define_method(rb_cModule, "const_get", rb_mod_const_get, -1);
3213     rb_define_method(rb_cModule, "const_set", rb_mod_const_set, 2);
3214     rb_define_method(rb_cModule, "const_defined?", rb_mod_const_defined, -1);
3215     rb_define_private_method(rb_cModule, "remove_const",
3216                              rb_mod_remove_const, 1); /* in variable.c */
3217     rb_define_method(rb_cModule, "const_missing",
3218                      rb_mod_const_missing, 1); /* in variable.c */
3219     rb_define_method(rb_cModule, "class_variables",
3220                      rb_mod_class_variables, -1); /* in variable.c */
3221     rb_define_method(rb_cModule, "remove_class_variable",
3222                      rb_mod_remove_cvar, 1); /* in variable.c */
3223     rb_define_method(rb_cModule, "class_variable_get", rb_mod_cvar_get, 1);
3224     rb_define_method(rb_cModule, "class_variable_set", rb_mod_cvar_set, 2);
3225     rb_define_method(rb_cModule, "class_variable_defined?", rb_mod_cvar_defined, 1);
3226     rb_define_method(rb_cModule, "public_constant", rb_mod_public_constant, -1); /* in variable.c */
3227     rb_define_method(rb_cModule, "private_constant", rb_mod_private_constant, -1); /* in variable.c */
3228 
3229     rb_define_method(rb_cClass, "allocate", rb_obj_alloc, 0);
3230     rb_define_method(rb_cClass, "new", rb_class_new_instance, -1);
3231     rb_define_method(rb_cClass, "initialize", rb_class_initialize, -1);
3232     rb_define_method(rb_cClass, "superclass", rb_class_superclass, 0);
3233     rb_define_alloc_func(rb_cClass, rb_class_s_alloc);
3234     rb_undef_method(rb_cClass, "extend_object");
3235     rb_undef_method(rb_cClass, "append_features");
3236 
3237     /*
3238      * Document-class: Data
3239      *
3240      * This is a recommended base class for C extensions using Data_Make_Struct
3241      * or Data_Wrap_Struct, see README.EXT for details.
3242      */
3243     rb_cData = rb_define_class("Data", rb_cObject);
3244     rb_undef_alloc_func(rb_cData);
3245 
3246     rb_cTrueClass = rb_define_class("TrueClass", rb_cObject);
3247     rb_define_method(rb_cTrueClass, "to_s", true_to_s, 0);
3248     rb_define_alias(rb_cTrueClass, "inspect", "to_s");
3249     rb_define_method(rb_cTrueClass, "&", true_and, 1);
3250     rb_define_method(rb_cTrueClass, "|", true_or, 1);
3251     rb_define_method(rb_cTrueClass, "^", true_xor, 1);
3252     rb_undef_alloc_func(rb_cTrueClass);
3253     rb_undef_method(CLASS_OF(rb_cTrueClass), "new");
3254     /*
3255      * An alias of +true+
3256      */
3257     rb_define_global_const("TRUE", Qtrue);
3258 
3259     rb_cFalseClass = rb_define_class("FalseClass", rb_cObject);
3260     rb_define_method(rb_cFalseClass, "to_s", false_to_s, 0);
3261     rb_define_alias(rb_cFalseClass, "inspect", "to_s");
3262     rb_define_method(rb_cFalseClass, "&", false_and, 1);
3263     rb_define_method(rb_cFalseClass, "|", false_or, 1);
3264     rb_define_method(rb_cFalseClass, "^", false_xor, 1);
3265     rb_undef_alloc_func(rb_cFalseClass);
3266     rb_undef_method(CLASS_OF(rb_cFalseClass), "new");
3267     /*
3268      * An alias of +false+
3269      */
3270     rb_define_global_const("FALSE", Qfalse);
3271 
3272     for (i=0; conv_method_names[i].method; i++) {
3273         conv_method_names[i].id = rb_intern(conv_method_names[i].method);
3274     }
3275 }