1 /**********************************************************************
2 
3   object.c -
4 
5   $Author: usa $
6   created at: Thu Jul 15 12:01:24 JST 1993
7 
8   Copyright (C) 1993-2007 Yukihiro Matsumoto
9   Copyright (C) 2000  Network Applied Communication Laboratory, Inc.
10   Copyright (C) 2000  Information-technology Promotion Agency, Japan
11 
12 **********************************************************************/
13 
14 #include "ruby/encoding.h"
15 #include "ruby/st.h"
16 #include "ruby/util.h"
17 #include "internal.h"
18 #include <stdio.h>
19 #include <errno.h>
20 #include <ctype.h>
21 #include <math.h>
22 #include <float.h>
23 #include "constant.h"
24 #include "id.h"
25 #include "probes.h"
26 
27 /*!
28  * \defgroup object Core objects and their operations
29  * \{
30  */
31 
32 VALUE rb_cBasicObject; /*!< BasicObject class */
33 VALUE rb_mKernel; /*!< Kernel module */
34 VALUE rb_cObject; /*!< Object class */
35 VALUE rb_cModule; /*!< Module class */
36 VALUE rb_cClass; /*!< Class class */
37 VALUE rb_cData; /*!< Data class */
38 
39 VALUE rb_cNilClass; /*!< NilClass class */
40 VALUE rb_cTrueClass; /*!< TrueClass class */
41 VALUE rb_cFalseClass; /*!< FalseClass class */
42 
43 /*! \cond INTERNAL_MACRO */
44 
45 #define id_eq               idEq
46 #define id_eql              idEqlP
47 #define id_match            idEqTilde
48 #define id_inspect          idInspect
49 #define id_init_copy        idInitialize_copy
50 #define id_init_clone       idInitialize_clone
51 #define id_init_dup         idInitialize_dup
52 #define id_const_missing    idConst_missing
53 #define id_to_f             idTo_f
54 
55 #define CLASS_OR_MODULE_P(obj) \
56     (!SPECIAL_CONST_P(obj) && \
57      (BUILTIN_TYPE(obj) == T_CLASS || BUILTIN_TYPE(obj) == T_MODULE))
58 
59 /*! \endcond */
60 
61 /*!
62  * Make the object invisible from Ruby code.
63  *
64  * It is useful to let Ruby's GC manage your internal data structure --
65  * The object keeps being managed by GC, but \c ObjectSpace.each_object
66  * never yields the object.
67  *
68  * Note that the object also lose a way to call a method on it.
69  *
70  * \param[in] obj a Ruby object
71  * \sa rb_obj_reveal
72  */
73 VALUE
rb_obj_hide(VALUE obj)74 rb_obj_hide(VALUE obj)
75 {
76     if (!SPECIAL_CONST_P(obj)) {
77 	RBASIC_CLEAR_CLASS(obj);
78     }
79     return obj;
80 }
81 
82 /*!
83  * Make a hidden object visible again.
84  *
85  * It is the caller's responsibility to pass the right \a klass
86  * which \a obj originally used to belong to.
87  *
88  * \sa rb_obj_hide
89  */
90 VALUE
rb_obj_reveal(VALUE obj,VALUE klass)91 rb_obj_reveal(VALUE obj, VALUE klass)
92 {
93     if (!SPECIAL_CONST_P(obj)) {
94 	RBASIC_SET_CLASS(obj, klass);
95     }
96     return obj;
97 }
98 
99 /*!
100  * Fills common (\c RBasic) fields in \a obj.
101  *
102  * \note Prefer rb_newobj_of() to this function.
103  * \param[in,out] obj a Ruby object to be set up.
104  * \param[in] klass \c obj will belong to this class.
105  * \param[in] type one of \c ruby_value_type
106  */
107 VALUE
rb_obj_setup(VALUE obj,VALUE klass,VALUE type)108 rb_obj_setup(VALUE obj, VALUE klass, VALUE type)
109 {
110     RBASIC(obj)->flags = type;
111     RBASIC_SET_CLASS(obj, klass);
112     return obj;
113 }
114 
115 /**
116  *  call-seq:
117  *     obj === other   -> true or false
118  *
119  *  Case Equality -- For class Object, effectively the same as calling
120  *  <code>#==</code>, but typically overridden by descendants to provide
121  *  meaningful semantics in +case+ statements.
122  *--
123  * Same as \c Object#===, case equality.
124  *++
125  */
126 
127 VALUE
rb_equal(VALUE obj1,VALUE obj2)128 rb_equal(VALUE obj1, VALUE obj2)
129 {
130     VALUE result;
131 
132     if (obj1 == obj2) return Qtrue;
133     result = rb_equal_opt(obj1, obj2);
134     if (result == Qundef) {
135 	result = rb_funcall(obj1, id_eq, 1, obj2);
136     }
137     if (RTEST(result)) return Qtrue;
138     return Qfalse;
139 }
140 
141 /**
142  * Determines if \a obj1 and \a obj2 are equal in terms of
143  * \c Object#eql?.
144  *
145  * \note It actually calls \c #eql? when necessary.
146  *   So you cannot implement \c #eql? with this function.
147  * \retval non-zero if they are eql?
148  * \retval zero if they are not eql?.
149  */
150 int
rb_eql(VALUE obj1,VALUE obj2)151 rb_eql(VALUE obj1, VALUE obj2)
152 {
153     VALUE result;
154 
155     if (obj1 == obj2) return Qtrue;
156     result = rb_eql_opt(obj1, obj2);
157     if (result == Qundef) {
158 	result = rb_funcall(obj1, id_eql, 1, obj2);
159     }
160     if (RTEST(result)) return Qtrue;
161     return Qfalse;
162 }
163 
164 /**
165  *  call-seq:
166  *     obj == other        -> true or false
167  *     obj.equal?(other)   -> true or false
168  *     obj.eql?(other)     -> true or false
169  *
170  *  Equality --- At the <code>Object</code> level, <code>==</code> returns
171  *  <code>true</code> only if +obj+ and +other+ are the same object.
172  *  Typically, this method is overridden in descendant classes to provide
173  *  class-specific meaning.
174  *
175  *  Unlike <code>==</code>, the <code>equal?</code> method should never be
176  *  overridden by subclasses as it is used to determine object identity
177  *  (that is, <code>a.equal?(b)</code> if and only if <code>a</code> is the
178  *  same object as <code>b</code>):
179  *
180  *    obj = "a"
181  *    other = obj.dup
182  *
183  *    obj == other      #=> true
184  *    obj.equal? other  #=> false
185  *    obj.equal? obj    #=> true
186  *
187  *  The <code>eql?</code> method returns <code>true</code> if +obj+ and
188  *  +other+ refer to the same hash key.  This is used by Hash to test members
189  *  for equality.  For objects of class <code>Object</code>, <code>eql?</code>
190  *  is synonymous with <code>==</code>.  Subclasses normally continue this
191  *  tradition by aliasing <code>eql?</code> to their overridden <code>==</code>
192  *  method, but there are exceptions.  <code>Numeric</code> types, for
193  *  example, perform type conversion across <code>==</code>, but not across
194  *  <code>eql?</code>, so:
195  *
196  *     1 == 1.0     #=> true
197  *     1.eql? 1.0   #=> false
198  *--
199  * \private
200  *++
201  */
202 MJIT_FUNC_EXPORTED VALUE
rb_obj_equal(VALUE obj1,VALUE obj2)203 rb_obj_equal(VALUE obj1, VALUE obj2)
204 {
205     if (obj1 == obj2) return Qtrue;
206     return Qfalse;
207 }
208 
209 VALUE rb_obj_hash(VALUE obj);
210 
211 /**
212  *  call-seq:
213  *     !obj    -> true or false
214  *
215  *  Boolean negate.
216  *--
217  * \private
218  *++
219  */
220 
221 MJIT_FUNC_EXPORTED VALUE
rb_obj_not(VALUE obj)222 rb_obj_not(VALUE obj)
223 {
224     return RTEST(obj) ? Qfalse : Qtrue;
225 }
226 
227 /**
228  *  call-seq:
229  *     obj != other        -> true or false
230  *
231  *  Returns true if two objects are not-equal, otherwise false.
232  *--
233  * \private
234  *++
235  */
236 
237 MJIT_FUNC_EXPORTED VALUE
rb_obj_not_equal(VALUE obj1,VALUE obj2)238 rb_obj_not_equal(VALUE obj1, VALUE obj2)
239 {
240     VALUE result = rb_funcall(obj1, id_eq, 1, obj2);
241     return RTEST(result) ? Qfalse : Qtrue;
242 }
243 
244 /*!
245  * Looks up the nearest ancestor of \a cl, skipping singleton classes or
246  * module inclusions.
247  * It returns the \a cl itself if it is neither a singleton class or a module.
248  *
249  * \param[in] cl a Class object.
250  * \return the ancestor class found, or a falsey value if nothing found.
251  */
252 VALUE
rb_class_real(VALUE cl)253 rb_class_real(VALUE cl)
254 {
255     while (cl &&
256         ((RBASIC(cl)->flags & FL_SINGLETON) || BUILTIN_TYPE(cl) == T_ICLASS)) {
257 	cl = RCLASS_SUPER(cl);
258     }
259     return cl;
260 }
261 
262 /**
263  *  call-seq:
264  *     obj.class    -> class
265  *
266  *  Returns the class of <i>obj</i>. This method must always be
267  *  called with an explicit receiver, as <code>class</code> is also a
268  *  reserved word in Ruby.
269  *
270  *     1.class      #=> Integer
271  *     self.class   #=> Object
272  *--
273  * Equivalent to \c Object\#class in Ruby.
274  *
275  * Returns the class of \c obj, skipping singleton classes or module inclusions.
276  *++
277  */
278 VALUE
rb_obj_class(VALUE obj)279 rb_obj_class(VALUE obj)
280 {
281     return rb_class_real(CLASS_OF(obj));
282 }
283 
284 /*
285  *  call-seq:
286  *     obj.singleton_class    -> class
287  *
288  *  Returns the singleton class of <i>obj</i>.  This method creates
289  *  a new singleton class if <i>obj</i> does not have one.
290  *
291  *  If <i>obj</i> is <code>nil</code>, <code>true</code>, or
292  *  <code>false</code>, it returns NilClass, TrueClass, or FalseClass,
293  *  respectively.
294  *  If <i>obj</i> is an Integer, a Float or a Symbol, it raises a TypeError.
295  *
296  *     Object.new.singleton_class  #=> #<Class:#<Object:0xb7ce1e24>>
297  *     String.singleton_class      #=> #<Class:String>
298  *     nil.singleton_class         #=> NilClass
299  */
300 
301 static VALUE
rb_obj_singleton_class(VALUE obj)302 rb_obj_singleton_class(VALUE obj)
303 {
304     return rb_singleton_class(obj);
305 }
306 
307 /*! \private */
308 MJIT_FUNC_EXPORTED void
rb_obj_copy_ivar(VALUE dest,VALUE obj)309 rb_obj_copy_ivar(VALUE dest, VALUE obj)
310 {
311     if (!(RBASIC(dest)->flags & ROBJECT_EMBED) && ROBJECT_IVPTR(dest)) {
312 	xfree(ROBJECT_IVPTR(dest));
313 	ROBJECT(dest)->as.heap.ivptr = 0;
314 	ROBJECT(dest)->as.heap.numiv = 0;
315 	ROBJECT(dest)->as.heap.iv_index_tbl = 0;
316     }
317     if (RBASIC(obj)->flags & ROBJECT_EMBED) {
318 	MEMCPY(ROBJECT(dest)->as.ary, ROBJECT(obj)->as.ary, VALUE, ROBJECT_EMBED_LEN_MAX);
319 	RBASIC(dest)->flags |= ROBJECT_EMBED;
320     }
321     else {
322 	uint32_t len = ROBJECT(obj)->as.heap.numiv;
323 	VALUE *ptr = 0;
324 	if (len > 0) {
325 	    ptr = ALLOC_N(VALUE, len);
326 	    MEMCPY(ptr, ROBJECT(obj)->as.heap.ivptr, VALUE, len);
327 	}
328 	ROBJECT(dest)->as.heap.ivptr = ptr;
329 	ROBJECT(dest)->as.heap.numiv = len;
330 	ROBJECT(dest)->as.heap.iv_index_tbl = ROBJECT(obj)->as.heap.iv_index_tbl;
331 	RBASIC(dest)->flags &= ~ROBJECT_EMBED;
332     }
333 }
334 
335 static void
init_copy(VALUE dest,VALUE obj)336 init_copy(VALUE dest, VALUE obj)
337 {
338     if (OBJ_FROZEN(dest)) {
339         rb_raise(rb_eTypeError, "[bug] frozen object (%s) allocated", rb_obj_classname(dest));
340     }
341     RBASIC(dest)->flags &= ~(T_MASK|FL_EXIVAR);
342     RBASIC(dest)->flags |= RBASIC(obj)->flags & (T_MASK|FL_EXIVAR|FL_TAINT);
343     rb_copy_wb_protected_attribute(dest, obj);
344     rb_copy_generic_ivar(dest, obj);
345     rb_gc_copy_finalizer(dest, obj);
346     if (RB_TYPE_P(obj, T_OBJECT)) {
347 	rb_obj_copy_ivar(dest, obj);
348     }
349 }
350 
351 static int freeze_opt(int argc, VALUE *argv);
352 static VALUE immutable_obj_clone(VALUE obj, int kwfreeze);
353 static VALUE mutable_obj_clone(VALUE obj, int kwfreeze);
354 PUREFUNC(static inline int special_object_p(VALUE obj)); /*!< \private */
355 static inline int
special_object_p(VALUE obj)356 special_object_p(VALUE obj)
357 {
358     if (SPECIAL_CONST_P(obj)) return TRUE;
359     switch (BUILTIN_TYPE(obj)) {
360       case T_BIGNUM:
361       case T_FLOAT:
362       case T_SYMBOL:
363       case T_RATIONAL:
364       case T_COMPLEX:
365 	/* not a comprehensive list */
366 	return TRUE;
367       default:
368 	return FALSE;
369     }
370 }
371 
372 /*
373  *  call-seq:
374  *     obj.clone(freeze: true) -> an_object
375  *
376  *  Produces a shallow copy of <i>obj</i>---the instance variables of
377  *  <i>obj</i> are copied, but not the objects they reference.
378  *  <code>clone</code> copies the frozen (unless :freeze keyword argument
379  *  is given with a false value) and tainted state of <i>obj</i>.
380  *  See also the discussion under <code>Object#dup</code>.
381  *
382  *     class Klass
383  *        attr_accessor :str
384  *     end
385  *     s1 = Klass.new      #=> #<Klass:0x401b3a38>
386  *     s1.str = "Hello"    #=> "Hello"
387  *     s2 = s1.clone       #=> #<Klass:0x401b3998 @str="Hello">
388  *     s2.str[1,4] = "i"   #=> "i"
389  *     s1.inspect          #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
390  *     s2.inspect          #=> "#<Klass:0x401b3998 @str=\"Hi\">"
391  *
392  *  This method may have class-specific behavior.  If so, that
393  *  behavior will be documented under the #+initialize_copy+ method of
394  *  the class.
395  */
396 
397 static VALUE
rb_obj_clone2(int argc,VALUE * argv,VALUE obj)398 rb_obj_clone2(int argc, VALUE *argv, VALUE obj)
399 {
400     int kwfreeze = freeze_opt(argc, argv);
401     if (!special_object_p(obj))
402 	return mutable_obj_clone(obj, kwfreeze);
403     return immutable_obj_clone(obj, kwfreeze);
404 }
405 
406 /*! \private */
407 VALUE
rb_immutable_obj_clone(int argc,VALUE * argv,VALUE obj)408 rb_immutable_obj_clone(int argc, VALUE *argv, VALUE obj)
409 {
410     int kwfreeze = freeze_opt(argc, argv);
411     return immutable_obj_clone(obj, kwfreeze);
412 }
413 
414 static int
freeze_opt(int argc,VALUE * argv)415 freeze_opt(int argc, VALUE *argv)
416 {
417     static ID keyword_ids[1];
418     VALUE opt;
419     VALUE kwfreeze;
420 
421     if (!keyword_ids[0]) {
422 	CONST_ID(keyword_ids[0], "freeze");
423     }
424     rb_scan_args(argc, argv, "0:", &opt);
425     if (!NIL_P(opt)) {
426 	rb_get_kwargs(opt, keyword_ids, 0, 1, &kwfreeze);
427 	if (kwfreeze == Qfalse) return FALSE;
428 	if (kwfreeze != Qundef && kwfreeze != Qtrue) {
429 	    rb_raise(rb_eArgError, "unexpected value for freeze: %"PRIsVALUE,
430 		     rb_obj_class(kwfreeze));
431 	}
432     }
433     return TRUE;
434 }
435 
436 static VALUE
immutable_obj_clone(VALUE obj,int kwfreeze)437 immutable_obj_clone(VALUE obj, int kwfreeze)
438 {
439     if (!kwfreeze)
440 	rb_raise(rb_eArgError, "can't unfreeze %"PRIsVALUE,
441 		 rb_obj_class(obj));
442     return obj;
443 }
444 
445 static VALUE
mutable_obj_clone(VALUE obj,int kwfreeze)446 mutable_obj_clone(VALUE obj, int kwfreeze)
447 {
448     VALUE clone, singleton;
449 
450     clone = rb_obj_alloc(rb_obj_class(obj));
451 
452     singleton = rb_singleton_class_clone_and_attach(obj, clone);
453     RBASIC_SET_CLASS(clone, singleton);
454     if (FL_TEST(singleton, FL_SINGLETON)) {
455 	rb_singleton_class_attached(singleton, clone);
456     }
457 
458     init_copy(clone, obj);
459     rb_funcall(clone, id_init_clone, 1, obj);
460 
461     if (kwfreeze) {
462 	RBASIC(clone)->flags |= RBASIC(obj)->flags & FL_FREEZE;
463     }
464 
465     return clone;
466 }
467 
468 /**
469  * :nodoc
470  *--
471  * Almost same as \c Object#clone
472  *++
473  */
474 VALUE
rb_obj_clone(VALUE obj)475 rb_obj_clone(VALUE obj)
476 {
477     if (special_object_p(obj)) return obj;
478     return mutable_obj_clone(obj, Qtrue);
479 }
480 
481 /**
482  *  call-seq:
483  *     obj.dup -> an_object
484  *
485  *  Produces a shallow copy of <i>obj</i>---the instance variables of
486  *  <i>obj</i> are copied, but not the objects they reference.
487  *  <code>dup</code> copies the tainted state of <i>obj</i>.
488  *
489  *  This method may have class-specific behavior.  If so, that
490  *  behavior will be documented under the #+initialize_copy+ method of
491  *  the class.
492  *
493  *  === on dup vs clone
494  *
495  *  In general, <code>clone</code> and <code>dup</code> may have different
496  *  semantics in descendant classes. While <code>clone</code> is used to
497  *  duplicate an object, including its internal state, <code>dup</code>
498  *  typically uses the class of the descendant object to create the new
499  *  instance.
500  *
501  *  When using #dup, any modules that the object has been extended with will not
502  *  be copied.
503  *
504  *	class Klass
505  *	  attr_accessor :str
506  *	end
507  *
508  *	module Foo
509  *	  def foo; 'foo'; end
510  *	end
511  *
512  *	s1 = Klass.new #=> #<Klass:0x401b3a38>
513  *	s1.extend(Foo) #=> #<Klass:0x401b3a38>
514  *	s1.foo #=> "foo"
515  *
516  *	s2 = s1.clone #=> #<Klass:0x401b3a38>
517  *	s2.foo #=> "foo"
518  *
519  *	s3 = s1.dup #=> #<Klass:0x401b3a38>
520  *	s3.foo #=> NoMethodError: undefined method `foo' for #<Klass:0x401b3a38>
521  *--
522  * Equivalent to \c Object\#dup in Ruby
523  *++
524  */
525 VALUE
rb_obj_dup(VALUE obj)526 rb_obj_dup(VALUE obj)
527 {
528     VALUE dup;
529 
530     if (special_object_p(obj)) {
531 	return obj;
532     }
533     dup = rb_obj_alloc(rb_obj_class(obj));
534     init_copy(dup, obj);
535     rb_funcall(dup, id_init_dup, 1, obj);
536 
537     return dup;
538 }
539 
540 /*
541  *  call-seq:
542  *     obj.itself    -> obj
543  *
544  *  Returns the receiver.
545  *
546  *     string = "my string"
547  *     string.itself.object_id == string.object_id   #=> true
548  *
549  */
550 
551 static VALUE
rb_obj_itself(VALUE obj)552 rb_obj_itself(VALUE obj)
553 {
554     return obj;
555 }
556 
557 static VALUE
rb_obj_size(VALUE self,VALUE args,VALUE obj)558 rb_obj_size(VALUE self, VALUE args, VALUE obj)
559 {
560     return LONG2FIX(1);
561 }
562 
563 /*
564  *  call-seq:
565  *     obj.then {|x| block }          -> an_object
566  *     obj.yield_self {|x| block }    -> an_object
567  *
568  *  Yields self to the block and returns the result of the block.
569  *
570  *     3.next.then {|x| x**x }.to_s             #=> "256"
571  *     "my string".yield_self {|s| s.upcase }   #=> "MY STRING"
572  *
573  *  Good usage for +yield_self+ is value piping in method chains:
574  *
575  *     require 'open-uri'
576  *     require 'json'
577  *
578  *     construct_url(arguments).
579  *       yield_self {|url| open(url).read }.
580  *       yield_self {|response| JSON.parse(response) }
581  *
582  *  When called without block, the method returns +Enumerator+,
583  *  which can be used, for example, for conditional
584  *  circuit-breaking:
585  *
586  *     # meets condition, no-op
587  *     1.yield_self.detect(&:odd?)            # => 1
588  *     # does not meet condition, drop value
589  *     2.yield_self.detect(&:odd?)            # => nil
590  *
591  */
592 
593 static VALUE
rb_obj_yield_self(VALUE obj)594 rb_obj_yield_self(VALUE obj)
595 {
596     RETURN_SIZED_ENUMERATOR(obj, 0, 0, rb_obj_size);
597     return rb_yield_values2(1, &obj);
598 }
599 
600 /**
601  * :nodoc:
602  *--
603  * Default implementation of \c #initialize_copy
604  * \param[in,out] obj the receiver being initialized
605  * \param[in] orig    the object to be copied from.
606  *++
607  */
608 VALUE
rb_obj_init_copy(VALUE obj,VALUE orig)609 rb_obj_init_copy(VALUE obj, VALUE orig)
610 {
611     if (obj == orig) return obj;
612     rb_check_frozen(obj);
613     rb_check_trusted(obj);
614     if (TYPE(obj) != TYPE(orig) || rb_obj_class(obj) != rb_obj_class(orig)) {
615 	rb_raise(rb_eTypeError, "initialize_copy should take same class object");
616     }
617     return obj;
618 }
619 
620 /*!
621  * :nodoc:
622  *--
623  * Default implementation of \c #initialize_dup and \c #initialize_clone
624  *
625  * \param[in,out] obj the receiver being initialized
626  * \param[in] orig    the object to be dup or cloned from.
627  *++
628  **/
629 VALUE
rb_obj_init_dup_clone(VALUE obj,VALUE orig)630 rb_obj_init_dup_clone(VALUE obj, VALUE orig)
631 {
632     rb_funcall(obj, id_init_copy, 1, orig);
633     return obj;
634 }
635 
636 /**
637  *  call-seq:
638  *     obj.to_s    -> string
639  *
640  *  Returns a string representing <i>obj</i>. The default
641  *  <code>to_s</code> prints the object's class and an encoding of the
642  *  object id. As a special case, the top-level object that is the
643  *  initial execution context of Ruby programs returns ``main''.
644  *
645  *--
646  * Default implementation of \c #to_s.
647  *++
648  */
649 VALUE
rb_any_to_s(VALUE obj)650 rb_any_to_s(VALUE obj)
651 {
652     VALUE str;
653     VALUE cname = rb_class_name(CLASS_OF(obj));
654 
655     str = rb_sprintf("#<%"PRIsVALUE":%p>", cname, (void*)obj);
656     OBJ_INFECT(str, obj);
657 
658     return str;
659 }
660 
661 VALUE rb_str_escape(VALUE str);
662 /*!
663  * Convenient wrapper of \c Object#inspect.
664  * Returns a human-readable string representation of \a obj,
665  * similarly to \c Object#inspect.
666  *
667  * Unlike Ruby-level \c #inspect, it escapes characters to keep the
668  * result compatible to the default internal or external encoding.
669  * If the default internal or external encoding is ASCII compatible,
670  * the encoding of the inspected result must be compatible with it.
671  * If the default internal or external encoding is ASCII incompatible,
672  * the result must be ASCII only.
673  */
674 VALUE
rb_inspect(VALUE obj)675 rb_inspect(VALUE obj)
676 {
677     VALUE str = rb_obj_as_string(rb_funcallv(obj, id_inspect, 0, 0));
678 
679     rb_encoding *enc = rb_default_internal_encoding();
680     if (enc == NULL) enc = rb_default_external_encoding();
681     if (!rb_enc_asciicompat(enc)) {
682 	if (!rb_enc_str_asciionly_p(str))
683 	    return rb_str_escape(str);
684 	return str;
685     }
686     if (rb_enc_get(str) != enc && !rb_enc_str_asciionly_p(str))
687 	return rb_str_escape(str);
688     return str;
689 }
690 
691 static int
inspect_i(st_data_t k,st_data_t v,st_data_t a)692 inspect_i(st_data_t k, st_data_t v, st_data_t a)
693 {
694     ID id = (ID)k;
695     VALUE value = (VALUE)v;
696     VALUE str = (VALUE)a;
697 
698     /* need not to show internal data */
699     if (CLASS_OF(value) == 0) return ST_CONTINUE;
700     if (!rb_is_instance_id(id)) return ST_CONTINUE;
701     if (RSTRING_PTR(str)[0] == '-') { /* first element */
702 	RSTRING_PTR(str)[0] = '#';
703 	rb_str_cat2(str, " ");
704     }
705     else {
706 	rb_str_cat2(str, ", ");
707     }
708     rb_str_catf(str, "%"PRIsVALUE"=%+"PRIsVALUE,
709 		rb_id2str(id), value);
710 
711     return ST_CONTINUE;
712 }
713 
714 static VALUE
inspect_obj(VALUE obj,VALUE str,int recur)715 inspect_obj(VALUE obj, VALUE str, int recur)
716 {
717     if (recur) {
718 	rb_str_cat2(str, " ...");
719     }
720     else {
721 	rb_ivar_foreach(obj, inspect_i, str);
722     }
723     rb_str_cat2(str, ">");
724     RSTRING_PTR(str)[0] = '#';
725     OBJ_INFECT(str, obj);
726 
727     return str;
728 }
729 
730 /*
731  *  call-seq:
732  *     obj.inspect   -> string
733  *
734  * Returns a string containing a human-readable representation of <i>obj</i>.
735  * The default <code>inspect</code> shows the object's class name,
736  * an encoding of the object id, and a list of the instance variables and
737  * their values (by calling #inspect on each of them).
738  * User defined classes should override this method to provide a better
739  * representation of <i>obj</i>.  When overriding this method, it should
740  * return a string whose encoding is compatible with the default external
741  * encoding.
742  *
743  *     [ 1, 2, 3..4, 'five' ].inspect   #=> "[1, 2, 3..4, \"five\"]"
744  *     Time.new.inspect                 #=> "2008-03-08 19:43:39 +0900"
745  *
746  *     class Foo
747  *     end
748  *     Foo.new.inspect                  #=> "#<Foo:0x0300c868>"
749  *
750  *     class Bar
751  *       def initialize
752  *         @bar = 1
753  *       end
754  *     end
755  *     Bar.new.inspect                  #=> "#<Bar:0x0300c868 @bar=1>"
756  */
757 
758 static VALUE
rb_obj_inspect(VALUE obj)759 rb_obj_inspect(VALUE obj)
760 {
761     if (rb_ivar_count(obj) > 0) {
762 	VALUE str;
763 	VALUE c = rb_class_name(CLASS_OF(obj));
764 
765 	str = rb_sprintf("-<%"PRIsVALUE":%p", c, (void*)obj);
766 	return rb_exec_recursive(inspect_obj, obj, str);
767     }
768     else {
769 	return rb_any_to_s(obj);
770     }
771 }
772 
773 static VALUE
class_or_module_required(VALUE c)774 class_or_module_required(VALUE c)
775 {
776     if (SPECIAL_CONST_P(c)) goto not_class;
777     switch (BUILTIN_TYPE(c)) {
778       case T_MODULE:
779       case T_CLASS:
780       case T_ICLASS:
781 	break;
782 
783       default:
784       not_class:
785 	rb_raise(rb_eTypeError, "class or module required");
786     }
787     return c;
788 }
789 
790 static VALUE class_search_ancestor(VALUE cl, VALUE c);
791 
792 /**
793  *  call-seq:
794  *     obj.instance_of?(class)    -> true or false
795  *
796  *  Returns <code>true</code> if <i>obj</i> is an instance of the given
797  *  class. See also <code>Object#kind_of?</code>.
798  *
799  *     class A;     end
800  *     class B < A; end
801  *     class C < B; end
802  *
803  *     b = B.new
804  *     b.instance_of? A   #=> false
805  *     b.instance_of? B   #=> true
806  *     b.instance_of? C   #=> false
807  *--
808  * Determines if \a obj is an instance of \a c.
809  *
810  * Equivalent to \c Object\#is_instance_of in Ruby.
811  * \param[in] obj the object to be determined.
812  * \param[in] c a Class object
813  *++
814  */
815 
816 VALUE
rb_obj_is_instance_of(VALUE obj,VALUE c)817 rb_obj_is_instance_of(VALUE obj, VALUE c)
818 {
819     c = class_or_module_required(c);
820     if (rb_obj_class(obj) == c) return Qtrue;
821     return Qfalse;
822 }
823 
824 
825 /**
826  *  call-seq:
827  *     obj.is_a?(class)       -> true or false
828  *     obj.kind_of?(class)    -> true or false
829  *
830  *  Returns <code>true</code> if <i>class</i> is the class of
831  *  <i>obj</i>, or if <i>class</i> is one of the superclasses of
832  *  <i>obj</i> or modules included in <i>obj</i>.
833  *
834  *     module M;    end
835  *     class A
836  *       include M
837  *     end
838  *     class B < A; end
839  *     class C < B; end
840  *
841  *     b = B.new
842  *     b.is_a? A          #=> true
843  *     b.is_a? B          #=> true
844  *     b.is_a? C          #=> false
845  *     b.is_a? M          #=> true
846  *
847  *     b.kind_of? A       #=> true
848  *     b.kind_of? B       #=> true
849  *     b.kind_of? C       #=> false
850  *     b.kind_of? M       #=> true
851  *--
852  * Determines if \a obj is a kind of \a c.
853  *
854  * Equivalent to \c Object\#kind_of? in Ruby.
855  * \param[in] obj the object to be determined
856  * \param[in] c a Module object.
857  *++
858  */
859 
860 VALUE
rb_obj_is_kind_of(VALUE obj,VALUE c)861 rb_obj_is_kind_of(VALUE obj, VALUE c)
862 {
863     VALUE cl = CLASS_OF(obj);
864 
865     c = class_or_module_required(c);
866     return class_search_ancestor(cl, RCLASS_ORIGIN(c)) ? Qtrue : Qfalse;
867 }
868 
869 static VALUE
class_search_ancestor(VALUE cl,VALUE c)870 class_search_ancestor(VALUE cl, VALUE c)
871 {
872     while (cl) {
873 	if (cl == c || RCLASS_M_TBL(cl) == RCLASS_M_TBL(c))
874 	    return cl;
875 	cl = RCLASS_SUPER(cl);
876     }
877     return 0;
878 }
879 
880 /*! \private */
881 VALUE
rb_class_search_ancestor(VALUE cl,VALUE c)882 rb_class_search_ancestor(VALUE cl, VALUE c)
883 {
884     cl = class_or_module_required(cl);
885     c = class_or_module_required(c);
886     return class_search_ancestor(cl, RCLASS_ORIGIN(c));
887 }
888 
889 /**
890  *  call-seq:
891  *     obj.tap {|x| block }    -> obj
892  *
893  *  Yields self to the block, and then returns self.
894  *  The primary purpose of this method is to "tap into" a method chain,
895  *  in order to perform operations on intermediate results within the chain.
896  *
897  *     (1..10)                  .tap {|x| puts "original: #{x}" }
898  *       .to_a                  .tap {|x| puts "array:    #{x}" }
899  *       .select {|x| x.even? } .tap {|x| puts "evens:    #{x}" }
900  *       .map {|x| x*x }        .tap {|x| puts "squares:  #{x}" }
901  *
902  *--
903  * \private
904  *++
905  */
906 
907 VALUE
rb_obj_tap(VALUE obj)908 rb_obj_tap(VALUE obj)
909 {
910     rb_yield(obj);
911     return obj;
912 }
913 
914 
915 /*
916  * Document-method: inherited
917  *
918  * call-seq:
919  *    inherited(subclass)
920  *
921  * Callback invoked whenever a subclass of the current class is created.
922  *
923  * Example:
924  *
925  *    class Foo
926  *      def self.inherited(subclass)
927  *        puts "New subclass: #{subclass}"
928  *      end
929  *    end
930  *
931  *    class Bar < Foo
932  *    end
933  *
934  *    class Baz < Bar
935  *    end
936  *
937  * <em>produces:</em>
938  *
939  *    New subclass: Bar
940  *    New subclass: Baz
941  */
942 
943 /* Document-method: method_added
944  *
945  * call-seq:
946  *   method_added(method_name)
947  *
948  * Invoked as a callback whenever an instance method is added to the
949  * receiver.
950  *
951  *   module Chatty
952  *     def self.method_added(method_name)
953  *       puts "Adding #{method_name.inspect}"
954  *     end
955  *     def self.some_class_method() end
956  *     def some_instance_method() end
957  *   end
958  *
959  * <em>produces:</em>
960  *
961  *   Adding :some_instance_method
962  *
963  */
964 
965 /* Document-method: method_removed
966  *
967  * call-seq:
968  *   method_removed(method_name)
969  *
970  * Invoked as a callback whenever an instance method is removed from the
971  * receiver.
972  *
973  *   module Chatty
974  *     def self.method_removed(method_name)
975  *       puts "Removing #{method_name.inspect}"
976  *     end
977  *     def self.some_class_method() end
978  *     def some_instance_method() end
979  *     class << self
980  *       remove_method :some_class_method
981  *     end
982  *     remove_method :some_instance_method
983  *   end
984  *
985  * <em>produces:</em>
986  *
987  *   Removing :some_instance_method
988  *
989  */
990 
991 /*
992  * Document-method: singleton_method_added
993  *
994  *  call-seq:
995  *     singleton_method_added(symbol)
996  *
997  *  Invoked as a callback whenever a singleton method is added to the
998  *  receiver.
999  *
1000  *     module Chatty
1001  *       def Chatty.singleton_method_added(id)
1002  *         puts "Adding #{id.id2name}"
1003  *       end
1004  *       def self.one()     end
1005  *       def two()          end
1006  *       def Chatty.three() end
1007  *     end
1008  *
1009  *  <em>produces:</em>
1010  *
1011  *     Adding singleton_method_added
1012  *     Adding one
1013  *     Adding three
1014  *
1015  */
1016 
1017 /*
1018  * Document-method: singleton_method_removed
1019  *
1020  *  call-seq:
1021  *     singleton_method_removed(symbol)
1022  *
1023  *  Invoked as a callback whenever a singleton method is removed from
1024  *  the receiver.
1025  *
1026  *     module Chatty
1027  *       def Chatty.singleton_method_removed(id)
1028  *         puts "Removing #{id.id2name}"
1029  *       end
1030  *       def self.one()     end
1031  *       def two()          end
1032  *       def Chatty.three() end
1033  *       class << self
1034  *         remove_method :three
1035  *         remove_method :one
1036  *       end
1037  *     end
1038  *
1039  *  <em>produces:</em>
1040  *
1041  *     Removing three
1042  *     Removing one
1043  */
1044 
1045 /*
1046  * Document-method: singleton_method_undefined
1047  *
1048  *  call-seq:
1049  *     singleton_method_undefined(symbol)
1050  *
1051  *  Invoked as a callback whenever a singleton method is undefined in
1052  *  the receiver.
1053  *
1054  *     module Chatty
1055  *       def Chatty.singleton_method_undefined(id)
1056  *         puts "Undefining #{id.id2name}"
1057  *       end
1058  *       def Chatty.one()   end
1059  *       class << self
1060  *          undef_method(:one)
1061  *       end
1062  *     end
1063  *
1064  *  <em>produces:</em>
1065  *
1066  *     Undefining one
1067  */
1068 
1069 /*
1070  * Document-method: extended
1071  *
1072  * call-seq:
1073  *    extended(othermod)
1074  *
1075  * The equivalent of <tt>included</tt>, but for extended modules.
1076  *
1077  *        module A
1078  *          def self.extended(mod)
1079  *            puts "#{self} extended in #{mod}"
1080  *          end
1081  *        end
1082  *        module Enumerable
1083  *          extend A
1084  *        end
1085  *         # => prints "A extended in Enumerable"
1086  */
1087 
1088 /*
1089  * Document-method: included
1090  *
1091  * call-seq:
1092  *    included(othermod)
1093  *
1094  * Callback invoked whenever the receiver is included in another
1095  * module or class. This should be used in preference to
1096  * <tt>Module.append_features</tt> if your code wants to perform some
1097  * action when a module is included in another.
1098  *
1099  *        module A
1100  *          def A.included(mod)
1101  *            puts "#{self} included in #{mod}"
1102  *          end
1103  *        end
1104  *        module Enumerable
1105  *          include A
1106  *        end
1107  *         # => prints "A included in Enumerable"
1108  */
1109 
1110 /*
1111  * Document-method: prepended
1112  *
1113  * call-seq:
1114  *    prepended(othermod)
1115  *
1116  * The equivalent of <tt>included</tt>, but for prepended modules.
1117  *
1118  *        module A
1119  *          def self.prepended(mod)
1120  *            puts "#{self} prepended to #{mod}"
1121  *          end
1122  *        end
1123  *        module Enumerable
1124  *          prepend A
1125  *        end
1126  *         # => prints "A prepended to Enumerable"
1127  */
1128 
1129 /*
1130  * Document-method: initialize
1131  *
1132  * call-seq:
1133  *    BasicObject.new
1134  *
1135  * Returns a new BasicObject.
1136  */
1137 
1138 /*
1139  * Not documented
1140  */
1141 
1142 static VALUE
rb_obj_dummy(void)1143 rb_obj_dummy(void)
1144 {
1145     return Qnil;
1146 }
1147 
1148 /**
1149  *  call-seq:
1150  *     obj.tainted?    -> true or false
1151  *
1152  *  Returns true if the object is tainted.
1153  *
1154  *  See #taint for more information.
1155  *--
1156  * Determines if \a obj is tainted. Equivalent to \c Object\#tainted? in Ruby.
1157  * \param[in] obj  the object to be determined
1158  * \retval Qtrue if the object is tainted
1159  * \retval Qfalse if the object is not tainted
1160  * \sa rb_obj_taint
1161  * \sa rb_obj_untaint
1162  *++
1163  */
1164 
1165 VALUE
rb_obj_tainted(VALUE obj)1166 rb_obj_tainted(VALUE obj)
1167 {
1168     if (OBJ_TAINTED(obj))
1169 	return Qtrue;
1170     return Qfalse;
1171 }
1172 
1173 /**
1174  *  call-seq:
1175  *     obj.taint -> obj
1176  *
1177  *  Mark the object as tainted.
1178  *
1179  *  Objects that are marked as tainted will be restricted from various built-in
1180  *  methods. This is to prevent insecure data, such as command-line arguments
1181  *  or strings read from Kernel#gets, from inadvertently compromising the user's
1182  *  system.
1183  *
1184  *  To check whether an object is tainted, use #tainted?.
1185  *
1186  *  You should only untaint a tainted object if your code has inspected it and
1187  *  determined that it is safe. To do so use #untaint.
1188  *--
1189  * Marks the object as tainted. Equivalent to \c Object\#taint in Ruby
1190  * \param[in] obj  the object to be tainted
1191  * \return the object itself
1192  * \sa rb_obj_untaint
1193  * \sa rb_obj_tainted
1194  *++
1195  */
1196 
1197 VALUE
rb_obj_taint(VALUE obj)1198 rb_obj_taint(VALUE obj)
1199 {
1200     if (!OBJ_TAINTED(obj) && OBJ_TAINTABLE(obj)) {
1201 	rb_check_frozen(obj);
1202 	OBJ_TAINT(obj);
1203     }
1204     return obj;
1205 }
1206 
1207 
1208 /**
1209  *  call-seq:
1210  *     obj.untaint    -> obj
1211  *
1212  *  Removes the tainted mark from the object.
1213  *
1214  *  See #taint for more information.
1215  *--
1216  * Removes the tainted mark from the object.
1217  * Equivalent to \c Object\#untaint in Ruby.
1218  *
1219  * \param[in] obj  the object to be tainted
1220  * \return the object itself
1221  * \sa rb_obj_taint
1222  * \sa rb_obj_tainted
1223  *++
1224  */
1225 
1226 VALUE
rb_obj_untaint(VALUE obj)1227 rb_obj_untaint(VALUE obj)
1228 {
1229     if (OBJ_TAINTED(obj)) {
1230 	rb_check_frozen(obj);
1231 	FL_UNSET(obj, FL_TAINT);
1232     }
1233     return obj;
1234 }
1235 
1236 /**
1237  *  call-seq:
1238  *     obj.untrusted?    -> true or false
1239  *
1240  *  Deprecated method that is equivalent to #tainted?.
1241  *--
1242  * \deprecated Use rb_obj_tainted.
1243  *
1244  * Trustiness used to have independent semantics from taintedness.
1245  * But now trustiness of objects is obsolete and this function behaves
1246  * the same as rb_obj_tainted.
1247  *
1248  * \sa rb_obj_tainted
1249  *++
1250  */
1251 
1252 VALUE
rb_obj_untrusted(VALUE obj)1253 rb_obj_untrusted(VALUE obj)
1254 {
1255     rb_warning("untrusted? is deprecated and its behavior is same as tainted?");
1256     return rb_obj_tainted(obj);
1257 }
1258 
1259 /**
1260  *  call-seq:
1261  *     obj.untrust -> obj
1262  *
1263  *  Deprecated method that is equivalent to #taint.
1264  *--
1265  * \deprecated Use rb_obj_taint(obj)
1266  *
1267  * Trustiness used to have independent semantics from taintedness.
1268  * But now trustiness of objects is obsolete and this function behaves
1269  * the same as rb_obj_taint.
1270  *
1271  * \sa rb_obj_taint
1272  *++
1273  */
1274 
1275 VALUE
rb_obj_untrust(VALUE obj)1276 rb_obj_untrust(VALUE obj)
1277 {
1278     rb_warning("untrust is deprecated and its behavior is same as taint");
1279     return rb_obj_taint(obj);
1280 }
1281 
1282 
1283 /**
1284  *  call-seq:
1285  *     obj.trust    -> obj
1286  *
1287  *  Deprecated method that is equivalent to #untaint.
1288  *--
1289  * \deprecated Use rb_obj_untaint(obj)
1290  *
1291  * Trustiness used to have independent semantics from taintedness.
1292  * But now trustiness of objects is obsolete and this function behaves
1293  * the same as rb_obj_untaint.
1294  *
1295  * \sa rb_obj_untaint
1296  *++
1297  */
1298 
1299 VALUE
rb_obj_trust(VALUE obj)1300 rb_obj_trust(VALUE obj)
1301 {
1302     rb_warning("trust is deprecated and its behavior is same as untaint");
1303     return rb_obj_untaint(obj);
1304 }
1305 
1306 /**
1307  * Convenient function to infect \a victim with the taintedness of \a carrier.
1308  *
1309  * It just keeps the taintedness of \a victim if \a carrier is not tainted.
1310  * \param[in,out] victim the object being infected with the taintness of \a carrier
1311  * \param[in] carrier a possibly tainted object
1312  */
1313 
1314 void
rb_obj_infect(VALUE victim,VALUE carrier)1315 rb_obj_infect(VALUE victim, VALUE carrier)
1316 {
1317     OBJ_INFECT(victim, carrier);
1318 }
1319 
1320 /**
1321  *  call-seq:
1322  *     obj.freeze    -> obj
1323  *
1324  *  Prevents further modifications to <i>obj</i>. A
1325  *  <code>RuntimeError</code> will be raised if modification is attempted.
1326  *  There is no way to unfreeze a frozen object. See also
1327  *  <code>Object#frozen?</code>.
1328  *
1329  *  This method returns self.
1330  *
1331  *     a = [ "a", "b", "c" ]
1332  *     a.freeze
1333  *     a << "z"
1334  *
1335  *  <em>produces:</em>
1336  *
1337  *     prog.rb:3:in `<<': can't modify frozen Array (FrozenError)
1338  *     	from prog.rb:3
1339  *
1340  *  Objects of the following classes are always frozen: Integer,
1341  *  Float, Symbol.
1342  *--
1343  * Make the object unmodifiable. Equivalent to \c Object\#freeze in Ruby.
1344  * \param[in,out] obj  the object to be frozen
1345  * \return the frozen object
1346  *++
1347  */
1348 
1349 VALUE
rb_obj_freeze(VALUE obj)1350 rb_obj_freeze(VALUE obj)
1351 {
1352     if (!OBJ_FROZEN(obj)) {
1353 	OBJ_FREEZE(obj);
1354 	if (SPECIAL_CONST_P(obj)) {
1355 	    rb_bug("special consts should be frozen.");
1356 	}
1357     }
1358     return obj;
1359 }
1360 
1361 /**
1362  *  call-seq:
1363  *     obj.frozen?    -> true or false
1364  *
1365  *  Returns the freeze status of <i>obj</i>.
1366  *
1367  *     a = [ "a", "b", "c" ]
1368  *     a.freeze    #=> ["a", "b", "c"]
1369  *     a.frozen?   #=> true
1370  *--
1371  * Determines if the object is frozen. Equivalent to \c Object\#frozen? in Ruby.
1372  * \param[in] obj  the object to be determines
1373  * \retval Qtrue if frozen
1374  * \retval Qfalse if not frozen
1375  *++
1376  */
1377 
1378 VALUE
rb_obj_frozen_p(VALUE obj)1379 rb_obj_frozen_p(VALUE obj)
1380 {
1381     return OBJ_FROZEN(obj) ? Qtrue : Qfalse;
1382 }
1383 
1384 
1385 /*
1386  * Document-class: NilClass
1387  *
1388  *  The class of the singleton object <code>nil</code>.
1389  */
1390 
1391 /*
1392  *  call-seq:
1393  *     nil.to_i -> 0
1394  *
1395  *  Always returns zero.
1396  *
1397  *     nil.to_i   #=> 0
1398  */
1399 
1400 
1401 static VALUE
nil_to_i(VALUE obj)1402 nil_to_i(VALUE obj)
1403 {
1404     return INT2FIX(0);
1405 }
1406 
1407 /*
1408  *  call-seq:
1409  *     nil.to_f    -> 0.0
1410  *
1411  *  Always returns zero.
1412  *
1413  *     nil.to_f   #=> 0.0
1414  */
1415 
1416 static VALUE
nil_to_f(VALUE obj)1417 nil_to_f(VALUE obj)
1418 {
1419     return DBL2NUM(0.0);
1420 }
1421 
1422 /*
1423  *  call-seq:
1424  *     nil.to_s    -> ""
1425  *
1426  *  Always returns the empty string.
1427  */
1428 
1429 static VALUE
nil_to_s(VALUE obj)1430 nil_to_s(VALUE obj)
1431 {
1432     return rb_usascii_str_new(0, 0);
1433 }
1434 
1435 /*
1436  * Document-method: to_a
1437  *
1438  *  call-seq:
1439  *     nil.to_a    -> []
1440  *
1441  *  Always returns an empty array.
1442  *
1443  *     nil.to_a   #=> []
1444  */
1445 
1446 static VALUE
nil_to_a(VALUE obj)1447 nil_to_a(VALUE obj)
1448 {
1449     return rb_ary_new2(0);
1450 }
1451 
1452 /*
1453  * Document-method: to_h
1454  *
1455  *  call-seq:
1456  *     nil.to_h    -> {}
1457  *
1458  *  Always returns an empty hash.
1459  *
1460  *     nil.to_h   #=> {}
1461  */
1462 
1463 static VALUE
nil_to_h(VALUE obj)1464 nil_to_h(VALUE obj)
1465 {
1466     return rb_hash_new();
1467 }
1468 
1469 /*
1470  *  call-seq:
1471  *    nil.inspect  -> "nil"
1472  *
1473  *  Always returns the string "nil".
1474  */
1475 
1476 static VALUE
nil_inspect(VALUE obj)1477 nil_inspect(VALUE obj)
1478 {
1479     return rb_usascii_str_new2("nil");
1480 }
1481 
1482 /*
1483  *  call-seq:
1484  *     nil =~ other  -> nil
1485  *
1486  *  Dummy pattern matching -- always returns nil.
1487  */
1488 
1489 static VALUE
nil_match(VALUE obj1,VALUE obj2)1490 nil_match(VALUE obj1, VALUE obj2)
1491 {
1492     return Qnil;
1493 }
1494 
1495 /***********************************************************************
1496  *  Document-class: TrueClass
1497  *
1498  *  The global value <code>true</code> is the only instance of class
1499  *  <code>TrueClass</code> and represents a logically true value in
1500  *  boolean expressions. The class provides operators allowing
1501  *  <code>true</code> to be used in logical expressions.
1502  */
1503 
1504 
1505 /*
1506  * call-seq:
1507  *   true.to_s   ->  "true"
1508  *
1509  * The string representation of <code>true</code> is "true".
1510  */
1511 
1512 static VALUE
true_to_s(VALUE obj)1513 true_to_s(VALUE obj)
1514 {
1515     return rb_usascii_str_new2("true");
1516 }
1517 
1518 
1519 /*
1520  *  call-seq:
1521  *     true & obj    -> true or false
1522  *
1523  *  And---Returns <code>false</code> if <i>obj</i> is
1524  *  <code>nil</code> or <code>false</code>, <code>true</code> otherwise.
1525  */
1526 
1527 static VALUE
true_and(VALUE obj,VALUE obj2)1528 true_and(VALUE obj, VALUE obj2)
1529 {
1530     return RTEST(obj2)?Qtrue:Qfalse;
1531 }
1532 
1533 /*
1534  *  call-seq:
1535  *     true | obj   -> true
1536  *
1537  *  Or---Returns <code>true</code>. As <i>obj</i> is an argument to
1538  *  a method call, it is always evaluated; there is no short-circuit
1539  *  evaluation in this case.
1540  *
1541  *     true |  puts("or")
1542  *     true || puts("logical or")
1543  *
1544  *  <em>produces:</em>
1545  *
1546  *     or
1547  */
1548 
1549 static VALUE
true_or(VALUE obj,VALUE obj2)1550 true_or(VALUE obj, VALUE obj2)
1551 {
1552     return Qtrue;
1553 }
1554 
1555 
1556 /*
1557  *  call-seq:
1558  *     true ^ obj   -> !obj
1559  *
1560  *  Exclusive Or---Returns <code>true</code> if <i>obj</i> is
1561  *  <code>nil</code> or <code>false</code>, <code>false</code>
1562  *  otherwise.
1563  */
1564 
1565 static VALUE
true_xor(VALUE obj,VALUE obj2)1566 true_xor(VALUE obj, VALUE obj2)
1567 {
1568     return RTEST(obj2)?Qfalse:Qtrue;
1569 }
1570 
1571 
1572 /*
1573  *  Document-class: FalseClass
1574  *
1575  *  The global value <code>false</code> is the only instance of class
1576  *  <code>FalseClass</code> and represents a logically false value in
1577  *  boolean expressions. The class provides operators allowing
1578  *  <code>false</code> to participate correctly in logical expressions.
1579  *
1580  */
1581 
1582 /*
1583  * call-seq:
1584  *   false.to_s   ->  "false"
1585  *
1586  * The string representation of <code>false</code> is "false".
1587  */
1588 
1589 static VALUE
false_to_s(VALUE obj)1590 false_to_s(VALUE obj)
1591 {
1592     return rb_usascii_str_new2("false");
1593 }
1594 
1595 /*
1596  *  call-seq:
1597  *     false & obj   -> false
1598  *     nil & obj     -> false
1599  *
1600  *  And---Returns <code>false</code>. <i>obj</i> is always
1601  *  evaluated as it is the argument to a method call---there is no
1602  *  short-circuit evaluation in this case.
1603  */
1604 
1605 static VALUE
false_and(VALUE obj,VALUE obj2)1606 false_and(VALUE obj, VALUE obj2)
1607 {
1608     return Qfalse;
1609 }
1610 
1611 
1612 /*
1613  *  call-seq:
1614  *     false | obj   ->   true or false
1615  *     nil   | obj   ->   true or false
1616  *
1617  *  Or---Returns <code>false</code> if <i>obj</i> is
1618  *  <code>nil</code> or <code>false</code>; <code>true</code> otherwise.
1619  */
1620 
1621 static VALUE
false_or(VALUE obj,VALUE obj2)1622 false_or(VALUE obj, VALUE obj2)
1623 {
1624     return RTEST(obj2)?Qtrue:Qfalse;
1625 }
1626 
1627 
1628 
1629 /*
1630  *  call-seq:
1631  *     false ^ obj    -> true or false
1632  *     nil   ^ obj    -> true or false
1633  *
1634  *  Exclusive Or---If <i>obj</i> is <code>nil</code> or
1635  *  <code>false</code>, returns <code>false</code>; otherwise, returns
1636  *  <code>true</code>.
1637  *
1638  */
1639 
1640 static VALUE
false_xor(VALUE obj,VALUE obj2)1641 false_xor(VALUE obj, VALUE obj2)
1642 {
1643     return RTEST(obj2)?Qtrue:Qfalse;
1644 }
1645 
1646 /*
1647  * call-seq:
1648  *   nil.nil?               -> true
1649  *
1650  * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1651  */
1652 
1653 static VALUE
rb_true(VALUE obj)1654 rb_true(VALUE obj)
1655 {
1656     return Qtrue;
1657 }
1658 
1659 /*
1660  * call-seq:
1661  *   obj.nil?               -> true or false
1662  *
1663  * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1664  *
1665  *    Object.new.nil?   #=> false
1666  *    nil.nil?          #=> true
1667  */
1668 
1669 
1670 static VALUE
rb_false(VALUE obj)1671 rb_false(VALUE obj)
1672 {
1673     return Qfalse;
1674 }
1675 
1676 
1677 /*
1678  *  call-seq:
1679  *     obj =~ other  -> nil
1680  *
1681  * This method is deprecated.
1682  *
1683  * This is not only unuseful but also troublesome because it
1684  * may hide a type error.
1685  */
1686 
1687 static VALUE
rb_obj_match(VALUE obj1,VALUE obj2)1688 rb_obj_match(VALUE obj1, VALUE obj2)
1689 {
1690     rb_warning("deprecated Object#=~ is called on %"PRIsVALUE
1691                "; it always returns nil", rb_obj_class(obj1));
1692     return Qnil;
1693 }
1694 
1695 /*
1696  *  call-seq:
1697  *     obj !~ other  -> true or false
1698  *
1699  *  Returns true if two objects do not match (using the <i>=~</i>
1700  *  method), otherwise false.
1701  */
1702 
1703 static VALUE
rb_obj_not_match(VALUE obj1,VALUE obj2)1704 rb_obj_not_match(VALUE obj1, VALUE obj2)
1705 {
1706     VALUE result = rb_funcall(obj1, id_match, 1, obj2);
1707     return RTEST(result) ? Qfalse : Qtrue;
1708 }
1709 
1710 
1711 /*
1712  *  call-seq:
1713  *     obj <=> other -> 0 or nil
1714  *
1715  *  Returns 0 if +obj+ and +other+ are the same object
1716  *  or <code>obj == other</code>, otherwise nil.
1717  *
1718  *  The <code><=></code> is used by various methods to compare objects, for example
1719  *  Enumerable#sort, Enumerable#max etc.
1720  *
1721  *  Your implementation of <code><=></code> should return one of the following values: -1, 0,
1722  *  1 or nil. -1 means self is smaller than other. 0 means self is equal to other.
1723  *  1 means self is bigger than other. Nil means the two values could not be
1724  *  compared.
1725  *
1726  *  When you define <code><=></code>, you can include Comparable to gain the methods
1727  *  <code><=</code>, <code><</code>, <code>==</code>, <code>>=</code>, <code>></code> and <code>between?</code>.
1728  */
1729 static VALUE
rb_obj_cmp(VALUE obj1,VALUE obj2)1730 rb_obj_cmp(VALUE obj1, VALUE obj2)
1731 {
1732     if (obj1 == obj2 || rb_equal(obj1, obj2))
1733 	return INT2FIX(0);
1734     return Qnil;
1735 }
1736 
1737 /***********************************************************************
1738  *
1739  * Document-class: Module
1740  *
1741  *  A <code>Module</code> is a collection of methods and constants. The
1742  *  methods in a module may be instance methods or module methods.
1743  *  Instance methods appear as methods in a class when the module is
1744  *  included, module methods do not. Conversely, module methods may be
1745  *  called without creating an encapsulating object, while instance
1746  *  methods may not. (See <code>Module#module_function</code>.)
1747  *
1748  *  In the descriptions that follow, the parameter <i>sym</i> refers
1749  *  to a symbol, which is either a quoted string or a
1750  *  <code>Symbol</code> (such as <code>:name</code>).
1751  *
1752  *     module Mod
1753  *       include Math
1754  *       CONST = 1
1755  *       def meth
1756  *         #  ...
1757  *       end
1758  *     end
1759  *     Mod.class              #=> Module
1760  *     Mod.constants          #=> [:CONST, :PI, :E]
1761  *     Mod.instance_methods   #=> [:meth]
1762  *
1763  */
1764 
1765 /*
1766  * call-seq:
1767  *   mod.to_s   -> string
1768  *
1769  * Returns a string representing this module or class. For basic
1770  * classes and modules, this is the name. For singletons, we
1771  * show information on the thing we're attached to as well.
1772  */
1773 
1774 static VALUE
rb_mod_to_s(VALUE klass)1775 rb_mod_to_s(VALUE klass)
1776 {
1777     ID id_defined_at;
1778     VALUE refined_class, defined_at;
1779 
1780     if (FL_TEST(klass, FL_SINGLETON)) {
1781 	VALUE s = rb_usascii_str_new2("#<Class:");
1782 	VALUE v = rb_ivar_get(klass, id__attached__);
1783 
1784 	if (CLASS_OR_MODULE_P(v)) {
1785 	    rb_str_append(s, rb_inspect(v));
1786 	}
1787 	else {
1788 	    rb_str_append(s, rb_any_to_s(v));
1789 	}
1790 	rb_str_cat2(s, ">");
1791 
1792 	return s;
1793     }
1794     refined_class = rb_refinement_module_get_refined_class(klass);
1795     if (!NIL_P(refined_class)) {
1796 	VALUE s = rb_usascii_str_new2("#<refinement:");
1797 
1798 	rb_str_concat(s, rb_inspect(refined_class));
1799 	rb_str_cat2(s, "@");
1800 	CONST_ID(id_defined_at, "__defined_at__");
1801 	defined_at = rb_attr_get(klass, id_defined_at);
1802 	rb_str_concat(s, rb_inspect(defined_at));
1803 	rb_str_cat2(s, ">");
1804 	return s;
1805     }
1806     return rb_str_dup(rb_class_name(klass));
1807 }
1808 
1809 /*
1810  *  call-seq:
1811  *     mod.freeze       -> mod
1812  *
1813  *  Prevents further modifications to <i>mod</i>.
1814  *
1815  *  This method returns self.
1816  */
1817 
1818 static VALUE
rb_mod_freeze(VALUE mod)1819 rb_mod_freeze(VALUE mod)
1820 {
1821     rb_class_name(mod);
1822     return rb_obj_freeze(mod);
1823 }
1824 
1825 /*
1826  *  call-seq:
1827  *     mod === obj    -> true or false
1828  *
1829  *  Case Equality---Returns <code>true</code> if <i>obj</i> is an
1830  *  instance of <i>mod</i> or an instance of one of <i>mod</i>'s descendants.
1831  *  Of limited use for modules, but can be used in <code>case</code> statements
1832  *  to classify objects by class.
1833  */
1834 
1835 static VALUE
rb_mod_eqq(VALUE mod,VALUE arg)1836 rb_mod_eqq(VALUE mod, VALUE arg)
1837 {
1838     return rb_obj_is_kind_of(arg, mod);
1839 }
1840 
1841 /**
1842  * call-seq:
1843  *   mod <= other   ->  true, false, or nil
1844  *
1845  * Returns true if <i>mod</i> is a subclass of <i>other</i> or
1846  * is the same as <i>other</i>. Returns
1847  * <code>nil</code> if there's no relationship between the two.
1848  * (Think of the relationship in terms of the class definition:
1849  * "class A < B" implies "A < B".)
1850  *--
1851  * Determines if \a mod inherits \a arg. Equivalent to \c Module\#<= in Ruby
1852  *
1853  * \param[in] mod a Module object
1854  * \param[in] arg another Module object or an iclass of a module
1855  * \retval Qtrue if \a mod inherits \a arg, or \a mod equals \a arg
1856  * \retval Qfalse if \a arg inherits \a mod
1857  * \retval Qnil if otherwise
1858  *++
1859  */
1860 
1861 VALUE
rb_class_inherited_p(VALUE mod,VALUE arg)1862 rb_class_inherited_p(VALUE mod, VALUE arg)
1863 {
1864     if (mod == arg) return Qtrue;
1865     if (!CLASS_OR_MODULE_P(arg) && !RB_TYPE_P(arg, T_ICLASS)) {
1866 	rb_raise(rb_eTypeError, "compared with non class/module");
1867     }
1868     if (class_search_ancestor(mod, RCLASS_ORIGIN(arg))) {
1869 	return Qtrue;
1870     }
1871     /* not mod < arg; check if mod > arg */
1872     if (class_search_ancestor(arg, mod)) {
1873 	return Qfalse;
1874     }
1875     return Qnil;
1876 }
1877 
1878 /*
1879  * call-seq:
1880  *   mod < other   ->  true, false, or nil
1881  *
1882  * Returns true if <i>mod</i> is a subclass of <i>other</i>. Returns
1883  * <code>nil</code> if there's no relationship between the two.
1884  * (Think of the relationship in terms of the class definition:
1885  * "class A < B" implies "A < B".)
1886  *
1887  */
1888 
1889 static VALUE
rb_mod_lt(VALUE mod,VALUE arg)1890 rb_mod_lt(VALUE mod, VALUE arg)
1891 {
1892     if (mod == arg) return Qfalse;
1893     return rb_class_inherited_p(mod, arg);
1894 }
1895 
1896 
1897 /*
1898  * call-seq:
1899  *   mod >= other   ->  true, false, or nil
1900  *
1901  * Returns true if <i>mod</i> is an ancestor of <i>other</i>, or the
1902  * two modules are the same. Returns
1903  * <code>nil</code> if there's no relationship between the two.
1904  * (Think of the relationship in terms of the class definition:
1905  * "class A < B" implies "B > A".)
1906  *
1907  */
1908 
1909 static VALUE
rb_mod_ge(VALUE mod,VALUE arg)1910 rb_mod_ge(VALUE mod, VALUE arg)
1911 {
1912     if (!CLASS_OR_MODULE_P(arg)) {
1913 	rb_raise(rb_eTypeError, "compared with non class/module");
1914     }
1915 
1916     return rb_class_inherited_p(arg, mod);
1917 }
1918 
1919 /*
1920  * call-seq:
1921  *   mod > other   ->  true, false, or nil
1922  *
1923  * Returns true if <i>mod</i> is an ancestor of <i>other</i>. Returns
1924  * <code>nil</code> if there's no relationship between the two.
1925  * (Think of the relationship in terms of the class definition:
1926  * "class A < B" implies "B > A".)
1927  *
1928  */
1929 
1930 static VALUE
rb_mod_gt(VALUE mod,VALUE arg)1931 rb_mod_gt(VALUE mod, VALUE arg)
1932 {
1933     if (mod == arg) return Qfalse;
1934     return rb_mod_ge(mod, arg);
1935 }
1936 
1937 /*
1938  *  call-seq:
1939  *     module <=> other_module   -> -1, 0, +1, or nil
1940  *
1941  *  Comparison---Returns -1, 0, +1 or nil depending on whether +module+
1942  *  includes +other_module+, they are the same, or if +module+ is included by
1943  *  +other_module+.
1944  *
1945  *  Returns +nil+ if +module+ has no relationship with +other_module+, if
1946  *  +other_module+ is not a module, or if the two values are incomparable.
1947  */
1948 
1949 static VALUE
rb_mod_cmp(VALUE mod,VALUE arg)1950 rb_mod_cmp(VALUE mod, VALUE arg)
1951 {
1952     VALUE cmp;
1953 
1954     if (mod == arg) return INT2FIX(0);
1955     if (!CLASS_OR_MODULE_P(arg)) {
1956 	return Qnil;
1957     }
1958 
1959     cmp = rb_class_inherited_p(mod, arg);
1960     if (NIL_P(cmp)) return Qnil;
1961     if (cmp) {
1962 	return INT2FIX(-1);
1963     }
1964     return INT2FIX(1);
1965 }
1966 
1967 static VALUE
rb_module_s_alloc(VALUE klass)1968 rb_module_s_alloc(VALUE klass)
1969 {
1970     VALUE mod = rb_module_new();
1971 
1972     RBASIC_SET_CLASS(mod, klass);
1973     return mod;
1974 }
1975 
1976 static VALUE
rb_class_s_alloc(VALUE klass)1977 rb_class_s_alloc(VALUE klass)
1978 {
1979     return rb_class_boot(0);
1980 }
1981 
1982 /*
1983  *  call-seq:
1984  *    Module.new                  -> mod
1985  *    Module.new {|mod| block }   -> mod
1986  *
1987  *  Creates a new anonymous module. If a block is given, it is passed
1988  *  the module object, and the block is evaluated in the context of this
1989  *  module like <code>module_eval</code>.
1990  *
1991  *     fred = Module.new do
1992  *       def meth1
1993  *         "hello"
1994  *       end
1995  *       def meth2
1996  *         "bye"
1997  *       end
1998  *     end
1999  *     a = "my string"
2000  *     a.extend(fred)   #=> "my string"
2001  *     a.meth1          #=> "hello"
2002  *     a.meth2          #=> "bye"
2003  *
2004  *  Assign the module to a constant (name starting uppercase) if you
2005  *  want to treat it like a regular module.
2006  */
2007 
2008 static VALUE
rb_mod_initialize(VALUE module)2009 rb_mod_initialize(VALUE module)
2010 {
2011     if (rb_block_given_p()) {
2012 	rb_mod_module_exec(1, &module, module);
2013     }
2014     return Qnil;
2015 }
2016 
2017 /* :nodoc: */
2018 static VALUE
rb_mod_initialize_clone(VALUE clone,VALUE orig)2019 rb_mod_initialize_clone(VALUE clone, VALUE orig)
2020 {
2021     VALUE ret;
2022     ret = rb_obj_init_dup_clone(clone, orig);
2023     if (OBJ_FROZEN(orig))
2024         rb_class_name(clone);
2025     return ret;
2026 }
2027 
2028 /*
2029  *  call-seq:
2030  *     Class.new(super_class=Object)               -> a_class
2031  *     Class.new(super_class=Object) { |mod| ... } -> a_class
2032  *
2033  *  Creates a new anonymous (unnamed) class with the given superclass
2034  *  (or <code>Object</code> if no parameter is given). You can give a
2035  *  class a name by assigning the class object to a constant.
2036  *
2037  *  If a block is given, it is passed the class object, and the block
2038  *  is evaluated in the context of this class like
2039  *  <code>class_eval</code>.
2040  *
2041  *     fred = Class.new do
2042  *       def meth1
2043  *         "hello"
2044  *       end
2045  *       def meth2
2046  *         "bye"
2047  *       end
2048  *     end
2049  *
2050  *     a = fred.new     #=> #<#<Class:0x100381890>:0x100376b98>
2051  *     a.meth1          #=> "hello"
2052  *     a.meth2          #=> "bye"
2053  *
2054  *  Assign the class to a constant (name starting uppercase) if you
2055  *  want to treat it like a regular class.
2056  */
2057 
2058 static VALUE
rb_class_initialize(int argc,VALUE * argv,VALUE klass)2059 rb_class_initialize(int argc, VALUE *argv, VALUE klass)
2060 {
2061     VALUE super;
2062 
2063     if (RCLASS_SUPER(klass) != 0 || klass == rb_cBasicObject) {
2064 	rb_raise(rb_eTypeError, "already initialized class");
2065     }
2066     if (rb_check_arity(argc, 0, 1) == 0) {
2067 	super = rb_cObject;
2068     }
2069     else {
2070         super = argv[0];
2071 	rb_check_inheritable(super);
2072 	if (super != rb_cBasicObject && !RCLASS_SUPER(super)) {
2073 	    rb_raise(rb_eTypeError, "can't inherit uninitialized class");
2074 	}
2075     }
2076     RCLASS_SET_SUPER(klass, super);
2077     rb_make_metaclass(klass, RBASIC(super)->klass);
2078     rb_class_inherited(super, klass);
2079     rb_mod_initialize(klass);
2080 
2081     return klass;
2082 }
2083 
2084 /*! \private */
2085 void
rb_undefined_alloc(VALUE klass)2086 rb_undefined_alloc(VALUE klass)
2087 {
2088     rb_raise(rb_eTypeError, "allocator undefined for %"PRIsVALUE,
2089 	     klass);
2090 }
2091 
2092 static rb_alloc_func_t class_get_alloc_func(VALUE klass);
2093 static VALUE class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass);
2094 
2095 /*
2096  *  call-seq:
2097  *     class.allocate()   ->   obj
2098  *
2099  *  Allocates space for a new object of <i>class</i>'s class and does not
2100  *  call initialize on the new instance. The returned object must be an
2101  *  instance of <i>class</i>.
2102  *
2103  *      klass = Class.new do
2104  *        def initialize(*args)
2105  *          @initialized = true
2106  *        end
2107  *
2108  *        def initialized?
2109  *          @initialized || false
2110  *        end
2111  *      end
2112  *
2113  *      klass.allocate.initialized? #=> false
2114  *
2115  */
2116 
2117 static VALUE
rb_class_alloc_m(VALUE klass)2118 rb_class_alloc_m(VALUE klass)
2119 {
2120     rb_alloc_func_t allocator = class_get_alloc_func(klass);
2121     if (!rb_obj_respond_to(klass, rb_intern("allocate"), 1)) {
2122         rb_raise(rb_eTypeError, "calling %"PRIsVALUE".allocate is prohibited",
2123                  klass);
2124     }
2125     return class_call_alloc_func(allocator, klass);
2126 }
2127 
2128 static VALUE
rb_class_alloc(VALUE klass)2129 rb_class_alloc(VALUE klass)
2130 {
2131     rb_alloc_func_t allocator = class_get_alloc_func(klass);
2132     return class_call_alloc_func(allocator, klass);
2133 }
2134 
2135 static rb_alloc_func_t
class_get_alloc_func(VALUE klass)2136 class_get_alloc_func(VALUE klass)
2137 {
2138     rb_alloc_func_t allocator;
2139 
2140     if (RCLASS_SUPER(klass) == 0 && klass != rb_cBasicObject) {
2141 	rb_raise(rb_eTypeError, "can't instantiate uninitialized class");
2142     }
2143     if (FL_TEST(klass, FL_SINGLETON)) {
2144 	rb_raise(rb_eTypeError, "can't create instance of singleton class");
2145     }
2146     allocator = rb_get_alloc_func(klass);
2147     if (!allocator) {
2148 	rb_undefined_alloc(klass);
2149     }
2150     return allocator;
2151 }
2152 
2153 static VALUE
class_call_alloc_func(rb_alloc_func_t allocator,VALUE klass)2154 class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass)
2155 {
2156     VALUE obj;
2157 
2158     RUBY_DTRACE_CREATE_HOOK(OBJECT, rb_class2name(klass));
2159 
2160     obj = (*allocator)(klass);
2161 
2162     if (rb_obj_class(obj) != rb_class_real(klass)) {
2163 	rb_raise(rb_eTypeError, "wrong instance allocation");
2164     }
2165     return obj;
2166 }
2167 
2168 /**
2169  * Allocates an instance of \a klass
2170  *
2171  * \note It calls the allocator defined by {rb_define_alloc_func}.
2172  *   So you cannot use this function to define an allocator.
2173  *   Use {rb_newobj_of}, {TypedData_Make_Struct} or others, instead.
2174  * \note Usually prefer rb_class_new_instance to rb_obj_alloc and rb_obj_call_init
2175  * \param[in] klass a Class object
2176  * \sa rb_class_new_instance
2177  * \sa rb_obj_call_init
2178  * \sa rb_define_alloc_func
2179  * \sa rb_newobj_of
2180  * \sa TypedData_Make_Struct
2181  */
2182 VALUE
rb_obj_alloc(VALUE klass)2183 rb_obj_alloc(VALUE klass)
2184 {
2185     Check_Type(klass, T_CLASS);
2186     return rb_class_alloc(klass);
2187 }
2188 
2189 static VALUE
rb_class_allocate_instance(VALUE klass)2190 rb_class_allocate_instance(VALUE klass)
2191 {
2192     NEWOBJ_OF(obj, struct RObject, klass, T_OBJECT | (RGENGC_WB_PROTECTED_OBJECT ? FL_WB_PROTECTED : 0));
2193     return (VALUE)obj;
2194 }
2195 
2196 /*
2197  *  call-seq:
2198  *     class.new(args, ...)    ->  obj
2199  *
2200  *  Calls <code>allocate</code> to create a new object of
2201  *  <i>class</i>'s class, then invokes that object's
2202  *  <code>initialize</code> method, passing it <i>args</i>.
2203  *  This is the method that ends up getting called whenever
2204  *  an object is constructed using .new.
2205  *
2206  */
2207 
2208 static VALUE
rb_class_s_new(int argc,const VALUE * argv,VALUE klass)2209 rb_class_s_new(int argc, const VALUE *argv, VALUE klass)
2210 {
2211     VALUE obj;
2212 
2213     obj = rb_class_alloc(klass);
2214     rb_obj_call_init(obj, argc, argv);
2215 
2216     return obj;
2217 }
2218 
2219 /**
2220  * Allocates and initializes an instance of \a klass.
2221  *
2222  * Equivalent to \c Class\#new in Ruby
2223  *
2224  * \param[in] argc  the number of arguments to \c #initialize
2225  * \param[in] argv  a pointer to an array of arguments to \c #initialize
2226  * \param[in] klass a Class object
2227  * \return the new instance of \a klass
2228  * \sa rb_obj_call_init
2229  * \sa rb_obj_alloc
2230  */
2231 VALUE
rb_class_new_instance(int argc,const VALUE * argv,VALUE klass)2232 rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
2233 {
2234     Check_Type(klass, T_CLASS);
2235     return rb_class_s_new(argc, argv, klass);
2236 }
2237 
2238 /**
2239  *  call-seq:
2240  *     class.superclass -> a_super_class or nil
2241  *
2242  *  Returns the superclass of <i>class</i>, or <code>nil</code>.
2243  *
2244  *     File.superclass          #=> IO
2245  *     IO.superclass            #=> Object
2246  *     Object.superclass        #=> BasicObject
2247  *     class Foo; end
2248  *     class Bar < Foo; end
2249  *     Bar.superclass           #=> Foo
2250  *
2251  *  Returns nil when the given class does not have a parent class:
2252  *
2253  *     BasicObject.superclass   #=> nil
2254  *
2255  *--
2256  * Returns the superclass of \a klass. Equivalent to \c Class\#superclass in Ruby.
2257  *
2258  * It skips modules.
2259  * \param[in] klass a Class object
2260  * \return the superclass, or \c Qnil if \a klass does not have a parent class.
2261  * \sa rb_class_get_superclass
2262  *++
2263  */
2264 
2265 VALUE
rb_class_superclass(VALUE klass)2266 rb_class_superclass(VALUE klass)
2267 {
2268     VALUE super = RCLASS_SUPER(klass);
2269 
2270     if (!super) {
2271 	if (klass == rb_cBasicObject) return Qnil;
2272 	rb_raise(rb_eTypeError, "uninitialized class");
2273     }
2274     while (RB_TYPE_P(super, T_ICLASS)) {
2275 	super = RCLASS_SUPER(super);
2276     }
2277     if (!super) {
2278 	return Qnil;
2279     }
2280     return super;
2281 }
2282 
2283 /**
2284  * Returns the superclass of \a klass
2285  * The return value might be an iclass of a module, unlike rb_class_superclass.
2286  *
2287  * Also it returns Qfalse when \a klass does not have a parent class.
2288  * \sa rb_class_superclass
2289  */
2290 VALUE
rb_class_get_superclass(VALUE klass)2291 rb_class_get_superclass(VALUE klass)
2292 {
2293     return RCLASS(klass)->super;
2294 }
2295 
2296 /*! \private */
2297 #define id_for_var(obj, name, part, type) \
2298     id_for_setter(obj, name, type, "`%1$s' is not allowed as "#part" "#type" variable name")
2299 /*! \private */
2300 #define id_for_setter(obj, name, type, message) \
2301     check_setter_id(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message))
2302 static ID
check_setter_id(VALUE obj,VALUE * pname,int (* valid_id_p)(ID),int (* valid_name_p)(VALUE),const char * message,size_t message_len)2303 check_setter_id(VALUE obj, VALUE *pname,
2304 		int (*valid_id_p)(ID), int (*valid_name_p)(VALUE),
2305 		const char *message, size_t message_len)
2306 {
2307     ID id = rb_check_id(pname);
2308     VALUE name = *pname;
2309 
2310     if (id ? !valid_id_p(id) : !valid_name_p(name)) {
2311 	rb_name_err_raise_str(rb_fstring_new(message, message_len),
2312 			      obj, name);
2313     }
2314     return id;
2315 }
2316 
2317 static int
rb_is_attr_name(VALUE name)2318 rb_is_attr_name(VALUE name)
2319 {
2320     return rb_is_local_name(name) || rb_is_const_name(name);
2321 }
2322 
2323 static int
rb_is_attr_id(ID id)2324 rb_is_attr_id(ID id)
2325 {
2326     return rb_is_local_id(id) || rb_is_const_id(id);
2327 }
2328 
2329 static const char wrong_constant_name[] = "wrong constant name %1$s";
2330 static const char invalid_attribute_name[] = "invalid attribute name `%1$s'";
2331 
2332 static ID
id_for_attr(VALUE obj,VALUE name)2333 id_for_attr(VALUE obj, VALUE name)
2334 {
2335     ID id = id_for_setter(obj, name, attr, invalid_attribute_name);
2336     if (!id) id = rb_intern_str(name);
2337     return id;
2338 }
2339 
2340 /*
2341  *  call-seq:
2342  *     attr_reader(symbol, ...)  -> nil
2343  *     attr(symbol, ...)         -> nil
2344  *     attr_reader(string, ...)  -> nil
2345  *     attr(string, ...)         -> nil
2346  *
2347  *  Creates instance variables and corresponding methods that return the
2348  *  value of each instance variable. Equivalent to calling
2349  *  ``<code>attr</code><i>:name</i>'' on each name in turn.
2350  *  String arguments are converted to symbols.
2351  */
2352 
2353 static VALUE
rb_mod_attr_reader(int argc,VALUE * argv,VALUE klass)2354 rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass)
2355 {
2356     int i;
2357 
2358     for (i=0; i<argc; i++) {
2359 	rb_attr(klass, id_for_attr(klass, argv[i]), TRUE, FALSE, TRUE);
2360     }
2361     return Qnil;
2362 }
2363 
2364 /**
2365  *  call-seq:
2366  *    attr(name, ...) -> nil
2367  *    attr(name, true) -> nil
2368  *    attr(name, false) -> nil
2369  *
2370  *  The first form is equivalent to <code>attr_reader</code>.
2371  *  The second form is equivalent to <code>attr_accessor(name)</code> but deprecated.
2372  *  The last form is equivalent to <code>attr_reader(name)</code> but deprecated.
2373  *--
2374  * \private
2375  * \todo can be static?
2376  *++
2377  */
2378 VALUE
rb_mod_attr(int argc,VALUE * argv,VALUE klass)2379 rb_mod_attr(int argc, VALUE *argv, VALUE klass)
2380 {
2381     if (argc == 2 && (argv[1] == Qtrue || argv[1] == Qfalse)) {
2382 	rb_warning("optional boolean argument is obsoleted");
2383 	rb_attr(klass, id_for_attr(klass, argv[0]), 1, RTEST(argv[1]), TRUE);
2384 	return Qnil;
2385     }
2386     return rb_mod_attr_reader(argc, argv, klass);
2387 }
2388 
2389 /*
2390  *  call-seq:
2391  *      attr_writer(symbol, ...)    -> nil
2392  *      attr_writer(string, ...)    -> nil
2393  *
2394  *  Creates an accessor method to allow assignment to the attribute
2395  *  <i>symbol</i><code>.id2name</code>.
2396  *  String arguments are converted to symbols.
2397  */
2398 
2399 static VALUE
rb_mod_attr_writer(int argc,VALUE * argv,VALUE klass)2400 rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass)
2401 {
2402     int i;
2403 
2404     for (i=0; i<argc; i++) {
2405 	rb_attr(klass, id_for_attr(klass, argv[i]), FALSE, TRUE, TRUE);
2406     }
2407     return Qnil;
2408 }
2409 
2410 /*
2411  *  call-seq:
2412  *     attr_accessor(symbol, ...)    -> nil
2413  *     attr_accessor(string, ...)    -> nil
2414  *
2415  *  Defines a named attribute for this module, where the name is
2416  *  <i>symbol.</i><code>id2name</code>, creating an instance variable
2417  *  (<code>@name</code>) and a corresponding access method to read it.
2418  *  Also creates a method called <code>name=</code> to set the attribute.
2419  *  String arguments are converted to symbols.
2420  *
2421  *     module Mod
2422  *       attr_accessor(:one, :two)
2423  *     end
2424  *     Mod.instance_methods.sort   #=> [:one, :one=, :two, :two=]
2425  */
2426 
2427 static VALUE
rb_mod_attr_accessor(int argc,VALUE * argv,VALUE klass)2428 rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass)
2429 {
2430     int i;
2431 
2432     for (i=0; i<argc; i++) {
2433 	rb_attr(klass, id_for_attr(klass, argv[i]), TRUE, TRUE, TRUE);
2434     }
2435     return Qnil;
2436 }
2437 
2438 /*
2439  *  call-seq:
2440  *     mod.const_get(sym, inherit=true)    -> obj
2441  *     mod.const_get(str, inherit=true)    -> obj
2442  *
2443  *  Checks for a constant with the given name in <i>mod</i>.
2444  *  If +inherit+ is set, the lookup will also search
2445  *  the ancestors (and +Object+ if <i>mod</i> is a +Module+).
2446  *
2447  *  The value of the constant is returned if a definition is found,
2448  *  otherwise a +NameError+ is raised.
2449  *
2450  *     Math.const_get(:PI)   #=> 3.14159265358979
2451  *
2452  *  This method will recursively look up constant names if a namespaced
2453  *  class name is provided.  For example:
2454  *
2455  *     module Foo; class Bar; end end
2456  *     Object.const_get 'Foo::Bar'
2457  *
2458  *  The +inherit+ flag is respected on each lookup.  For example:
2459  *
2460  *     module Foo
2461  *       class Bar
2462  *         VAL = 10
2463  *       end
2464  *
2465  *       class Baz < Bar; end
2466  *     end
2467  *
2468  *     Object.const_get 'Foo::Baz::VAL'         # => 10
2469  *     Object.const_get 'Foo::Baz::VAL', false  # => NameError
2470  *
2471  *  If the argument is not a valid constant name a +NameError+ will be
2472  *  raised with a warning "wrong constant name".
2473  *
2474  *	Object.const_get 'foobar' #=> NameError: wrong constant name foobar
2475  *
2476  */
2477 
2478 static VALUE
rb_mod_const_get(int argc,VALUE * argv,VALUE mod)2479 rb_mod_const_get(int argc, VALUE *argv, VALUE mod)
2480 {
2481     VALUE name, recur;
2482     rb_encoding *enc;
2483     const char *pbeg, *p, *path, *pend;
2484     ID id;
2485 
2486     rb_check_arity(argc, 1, 2);
2487     name = argv[0];
2488     recur = (argc == 1) ? Qtrue : argv[1];
2489 
2490     if (SYMBOL_P(name)) {
2491 	if (!rb_is_const_sym(name)) goto wrong_name;
2492 	id = rb_check_id(&name);
2493 	if (!id) return rb_const_missing(mod, name);
2494 	return RTEST(recur) ? rb_const_get(mod, id) : rb_const_get_at(mod, id);
2495     }
2496 
2497     path = StringValuePtr(name);
2498     enc = rb_enc_get(name);
2499 
2500     if (!rb_enc_asciicompat(enc)) {
2501 	rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2502     }
2503 
2504     pbeg = p = path;
2505     pend = path + RSTRING_LEN(name);
2506 
2507     if (p >= pend || !*p) {
2508       wrong_name:
2509 	rb_name_err_raise(wrong_constant_name, mod, name);
2510     }
2511 
2512     if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2513 	mod = rb_cObject;
2514 	p += 2;
2515 	pbeg = p;
2516     }
2517 
2518     while (p < pend) {
2519 	VALUE part;
2520 	long len, beglen;
2521 
2522 	while (p < pend && *p != ':') p++;
2523 
2524 	if (pbeg == p) goto wrong_name;
2525 
2526 	id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2527 	beglen = pbeg-path;
2528 
2529 	if (p < pend && p[0] == ':') {
2530 	    if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2531 	    p += 2;
2532 	    pbeg = p;
2533 	}
2534 
2535 	if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2536 	    rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2537 		     QUOTE(name));
2538 	}
2539 
2540 	if (!id) {
2541 	    part = rb_str_subseq(name, beglen, len);
2542 	    OBJ_FREEZE(part);
2543 	    if (!rb_is_const_name(part)) {
2544 		name = part;
2545 		goto wrong_name;
2546 	    }
2547 	    else if (!rb_method_basic_definition_p(CLASS_OF(mod), id_const_missing)) {
2548 		part = rb_str_intern(part);
2549 		mod = rb_const_missing(mod, part);
2550 		continue;
2551 	    }
2552 	    else {
2553 		rb_mod_const_missing(mod, part);
2554 	    }
2555 	}
2556 	if (!rb_is_const_id(id)) {
2557 	    name = ID2SYM(id);
2558 	    goto wrong_name;
2559 	}
2560 #if 0
2561         mod = rb_const_get_0(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2562 #else
2563         if (!RTEST(recur)) {
2564             mod = rb_const_get_at(mod, id);
2565         }
2566         else if (beglen == 0) {
2567             mod = rb_const_get(mod, id);
2568         }
2569         else {
2570             mod = rb_const_get_from(mod, id);
2571         }
2572 #endif
2573     }
2574 
2575     return mod;
2576 }
2577 
2578 /*
2579  *  call-seq:
2580  *     mod.const_set(sym, obj)    -> obj
2581  *     mod.const_set(str, obj)    -> obj
2582  *
2583  *  Sets the named constant to the given object, returning that object.
2584  *  Creates a new constant if no constant with the given name previously
2585  *  existed.
2586  *
2587  *     Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0)   #=> 3.14285714285714
2588  *     Math::HIGH_SCHOOL_PI - Math::PI              #=> 0.00126448926734968
2589  *
2590  *  If +sym+ or +str+ is not a valid constant name a +NameError+ will be
2591  *  raised with a warning "wrong constant name".
2592  *
2593  *	Object.const_set('foobar', 42) #=> NameError: wrong constant name foobar
2594  *
2595  */
2596 
2597 static VALUE
rb_mod_const_set(VALUE mod,VALUE name,VALUE value)2598 rb_mod_const_set(VALUE mod, VALUE name, VALUE value)
2599 {
2600     ID id = id_for_setter(mod, name, const, wrong_constant_name);
2601     if (!id) id = rb_intern_str(name);
2602     rb_const_set(mod, id, value);
2603 
2604     return value;
2605 }
2606 
2607 /*
2608  *  call-seq:
2609  *     mod.const_defined?(sym, inherit=true)   -> true or false
2610  *     mod.const_defined?(str, inherit=true)   -> true or false
2611  *
2612  *  Says whether _mod_ or its ancestors have a constant with the given name:
2613  *
2614  *    Float.const_defined?(:EPSILON)      #=> true, found in Float itself
2615  *    Float.const_defined?("String")      #=> true, found in Object (ancestor)
2616  *    BasicObject.const_defined?(:Hash)   #=> false
2617  *
2618  *  If _mod_ is a +Module+, additionally +Object+ and its ancestors are checked:
2619  *
2620  *    Math.const_defined?(:String)   #=> true, found in Object
2621  *
2622  *  In each of the checked classes or modules, if the constant is not present
2623  *  but there is an autoload for it, +true+ is returned directly without
2624  *  autoloading:
2625  *
2626  *    module Admin
2627  *      autoload :User, 'admin/user'
2628  *    end
2629  *    Admin.const_defined?(:User)   #=> true
2630  *
2631  *  If the constant is not found the callback +const_missing+ is *not* called
2632  *  and the method returns +false+.
2633  *
2634  *  If +inherit+ is false, the lookup only checks the constants in the receiver:
2635  *
2636  *    IO.const_defined?(:SYNC)          #=> true, found in File::Constants (ancestor)
2637  *    IO.const_defined?(:SYNC, false)   #=> false, not found in IO itself
2638  *
2639  *  In this case, the same logic for autoloading applies.
2640  *
2641  *  If the argument is not a valid constant name a +NameError+ is raised with the
2642  *  message "wrong constant name _name_":
2643  *
2644  *    Hash.const_defined? 'foobar'   #=> NameError: wrong constant name foobar
2645  *
2646  */
2647 
2648 static VALUE
rb_mod_const_defined(int argc,VALUE * argv,VALUE mod)2649 rb_mod_const_defined(int argc, VALUE *argv, VALUE mod)
2650 {
2651     VALUE name, recur;
2652     rb_encoding *enc;
2653     const char *pbeg, *p, *path, *pend;
2654     ID id;
2655 
2656     rb_check_arity(argc, 1, 2);
2657     name = argv[0];
2658     recur = (argc == 1) ? Qtrue : argv[1];
2659 
2660     if (SYMBOL_P(name)) {
2661 	if (!rb_is_const_sym(name)) goto wrong_name;
2662 	id = rb_check_id(&name);
2663 	if (!id) return Qfalse;
2664 	return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id);
2665     }
2666 
2667     path = StringValuePtr(name);
2668     enc = rb_enc_get(name);
2669 
2670     if (!rb_enc_asciicompat(enc)) {
2671 	rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2672     }
2673 
2674     pbeg = p = path;
2675     pend = path + RSTRING_LEN(name);
2676 
2677     if (p >= pend || !*p) {
2678       wrong_name:
2679 	rb_name_err_raise(wrong_constant_name, mod, name);
2680     }
2681 
2682     if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2683 	mod = rb_cObject;
2684 	p += 2;
2685 	pbeg = p;
2686     }
2687 
2688     while (p < pend) {
2689 	VALUE part;
2690 	long len, beglen;
2691 
2692 	while (p < pend && *p != ':') p++;
2693 
2694 	if (pbeg == p) goto wrong_name;
2695 
2696 	id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2697 	beglen = pbeg-path;
2698 
2699 	if (p < pend && p[0] == ':') {
2700 	    if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2701 	    p += 2;
2702 	    pbeg = p;
2703 	}
2704 
2705 	if (!id) {
2706 	    part = rb_str_subseq(name, beglen, len);
2707 	    OBJ_FREEZE(part);
2708 	    if (!rb_is_const_name(part)) {
2709 		name = part;
2710 		goto wrong_name;
2711 	    }
2712 	    else {
2713 		return Qfalse;
2714 	    }
2715 	}
2716 	if (!rb_is_const_id(id)) {
2717 	    name = ID2SYM(id);
2718 	    goto wrong_name;
2719 	}
2720 
2721 #if 0
2722         mod = rb_const_search(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2723         if (mod == Qundef) return Qfalse;
2724 #else
2725         if (!RTEST(recur)) {
2726 	    if (!rb_const_defined_at(mod, id))
2727 		return Qfalse;
2728             if (p == pend) return Qtrue;
2729 	    mod = rb_const_get_at(mod, id);
2730 	}
2731         else if (beglen == 0) {
2732             if (!rb_const_defined(mod, id))
2733                 return Qfalse;
2734             if (p == pend) return Qtrue;
2735             mod = rb_const_get(mod, id);
2736         }
2737         else {
2738             if (!rb_const_defined_from(mod, id))
2739                 return Qfalse;
2740             if (p == pend) return Qtrue;
2741             mod = rb_const_get_from(mod, id);
2742         }
2743 #endif
2744 
2745 	if (p < pend && !RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2746 	    rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2747 		     QUOTE(name));
2748 	}
2749     }
2750 
2751     return Qtrue;
2752 }
2753 
2754 /*
2755  *  call-seq:
2756  *     obj.instance_variable_get(symbol)    -> obj
2757  *     obj.instance_variable_get(string)    -> obj
2758  *
2759  *  Returns the value of the given instance variable, or nil if the
2760  *  instance variable is not set. The <code>@</code> part of the
2761  *  variable name should be included for regular instance
2762  *  variables. Throws a <code>NameError</code> exception if the
2763  *  supplied symbol is not valid as an instance variable name.
2764  *  String arguments are converted to symbols.
2765  *
2766  *     class Fred
2767  *       def initialize(p1, p2)
2768  *         @a, @b = p1, p2
2769  *       end
2770  *     end
2771  *     fred = Fred.new('cat', 99)
2772  *     fred.instance_variable_get(:@a)    #=> "cat"
2773  *     fred.instance_variable_get("@b")   #=> 99
2774  */
2775 
2776 static VALUE
rb_obj_ivar_get(VALUE obj,VALUE iv)2777 rb_obj_ivar_get(VALUE obj, VALUE iv)
2778 {
2779     ID id = id_for_var(obj, iv, an, instance);
2780 
2781     if (!id) {
2782 	return Qnil;
2783     }
2784     return rb_ivar_get(obj, id);
2785 }
2786 
2787 /*
2788  *  call-seq:
2789  *     obj.instance_variable_set(symbol, obj)    -> obj
2790  *     obj.instance_variable_set(string, obj)    -> obj
2791  *
2792  *  Sets the instance variable named by <i>symbol</i> to the given
2793  *  object, thereby frustrating the efforts of the class's
2794  *  author to attempt to provide proper encapsulation. The variable
2795  *  does not have to exist prior to this call.
2796  *  If the instance variable name is passed as a string, that string
2797  *  is converted to a symbol.
2798  *
2799  *     class Fred
2800  *       def initialize(p1, p2)
2801  *         @a, @b = p1, p2
2802  *       end
2803  *     end
2804  *     fred = Fred.new('cat', 99)
2805  *     fred.instance_variable_set(:@a, 'dog')   #=> "dog"
2806  *     fred.instance_variable_set(:@c, 'cat')   #=> "cat"
2807  *     fred.inspect                             #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
2808  */
2809 
2810 static VALUE
rb_obj_ivar_set(VALUE obj,VALUE iv,VALUE val)2811 rb_obj_ivar_set(VALUE obj, VALUE iv, VALUE val)
2812 {
2813     ID id = id_for_var(obj, iv, an, instance);
2814     if (!id) id = rb_intern_str(iv);
2815     return rb_ivar_set(obj, id, val);
2816 }
2817 
2818 /*
2819  *  call-seq:
2820  *     obj.instance_variable_defined?(symbol)    -> true or false
2821  *     obj.instance_variable_defined?(string)    -> true or false
2822  *
2823  *  Returns <code>true</code> if the given instance variable is
2824  *  defined in <i>obj</i>.
2825  *  String arguments are converted to symbols.
2826  *
2827  *     class Fred
2828  *       def initialize(p1, p2)
2829  *         @a, @b = p1, p2
2830  *       end
2831  *     end
2832  *     fred = Fred.new('cat', 99)
2833  *     fred.instance_variable_defined?(:@a)    #=> true
2834  *     fred.instance_variable_defined?("@b")   #=> true
2835  *     fred.instance_variable_defined?("@c")   #=> false
2836  */
2837 
2838 static VALUE
rb_obj_ivar_defined(VALUE obj,VALUE iv)2839 rb_obj_ivar_defined(VALUE obj, VALUE iv)
2840 {
2841     ID id = id_for_var(obj, iv, an, instance);
2842 
2843     if (!id) {
2844 	return Qfalse;
2845     }
2846     return rb_ivar_defined(obj, id);
2847 }
2848 
2849 /*
2850  *  call-seq:
2851  *     mod.class_variable_get(symbol)    -> obj
2852  *     mod.class_variable_get(string)    -> obj
2853  *
2854  *  Returns the value of the given class variable (or throws a
2855  *  <code>NameError</code> exception). The <code>@@</code> part of the
2856  *  variable name should be included for regular class variables.
2857  *  String arguments are converted to symbols.
2858  *
2859  *     class Fred
2860  *       @@foo = 99
2861  *     end
2862  *     Fred.class_variable_get(:@@foo)     #=> 99
2863  */
2864 
2865 static VALUE
rb_mod_cvar_get(VALUE obj,VALUE iv)2866 rb_mod_cvar_get(VALUE obj, VALUE iv)
2867 {
2868     ID id = id_for_var(obj, iv, a, class);
2869 
2870     if (!id) {
2871 	rb_name_err_raise("uninitialized class variable %1$s in %2$s",
2872 			  obj, iv);
2873     }
2874     return rb_cvar_get(obj, id);
2875 }
2876 
2877 /*
2878  *  call-seq:
2879  *     obj.class_variable_set(symbol, obj)    -> obj
2880  *     obj.class_variable_set(string, obj)    -> obj
2881  *
2882  *  Sets the class variable named by <i>symbol</i> to the given
2883  *  object.
2884  *  If the class variable name is passed as a string, that string
2885  *  is converted to a symbol.
2886  *
2887  *     class Fred
2888  *       @@foo = 99
2889  *       def foo
2890  *         @@foo
2891  *       end
2892  *     end
2893  *     Fred.class_variable_set(:@@foo, 101)     #=> 101
2894  *     Fred.new.foo                             #=> 101
2895  */
2896 
2897 static VALUE
rb_mod_cvar_set(VALUE obj,VALUE iv,VALUE val)2898 rb_mod_cvar_set(VALUE obj, VALUE iv, VALUE val)
2899 {
2900     ID id = id_for_var(obj, iv, a, class);
2901     if (!id) id = rb_intern_str(iv);
2902     rb_cvar_set(obj, id, val);
2903     return val;
2904 }
2905 
2906 /*
2907  *  call-seq:
2908  *     obj.class_variable_defined?(symbol)    -> true or false
2909  *     obj.class_variable_defined?(string)    -> true or false
2910  *
2911  *  Returns <code>true</code> if the given class variable is defined
2912  *  in <i>obj</i>.
2913  *  String arguments are converted to symbols.
2914  *
2915  *     class Fred
2916  *       @@foo = 99
2917  *     end
2918  *     Fred.class_variable_defined?(:@@foo)    #=> true
2919  *     Fred.class_variable_defined?(:@@bar)    #=> false
2920  */
2921 
2922 static VALUE
rb_mod_cvar_defined(VALUE obj,VALUE iv)2923 rb_mod_cvar_defined(VALUE obj, VALUE iv)
2924 {
2925     ID id = id_for_var(obj, iv, a, class);
2926 
2927     if (!id) {
2928 	return Qfalse;
2929     }
2930     return rb_cvar_defined(obj, id);
2931 }
2932 
2933 /*
2934  *  call-seq:
2935  *     mod.singleton_class?    -> true or false
2936  *
2937  *  Returns <code>true</code> if <i>mod</i> is a singleton class or
2938  *  <code>false</code> if it is an ordinary class or module.
2939  *
2940  *     class C
2941  *     end
2942  *     C.singleton_class?                  #=> false
2943  *     C.singleton_class.singleton_class?  #=> true
2944  */
2945 
2946 static VALUE
rb_mod_singleton_p(VALUE klass)2947 rb_mod_singleton_p(VALUE klass)
2948 {
2949     if (RB_TYPE_P(klass, T_CLASS) && FL_TEST(klass, FL_SINGLETON))
2950 	return Qtrue;
2951     return Qfalse;
2952 }
2953 
2954 /*! \private */
2955 static const struct conv_method_tbl {
2956     const char method[6];
2957     unsigned short id;
2958 } conv_method_names[] = {
2959 #define M(n) {#n, (unsigned short)idTo_##n}
2960     M(int),
2961     M(ary),
2962     M(str),
2963     M(sym),
2964     M(hash),
2965     M(proc),
2966     M(io),
2967     M(a),
2968     M(s),
2969     M(i),
2970     M(r),
2971 #undef M
2972 };
2973 #define IMPLICIT_CONVERSIONS 7
2974 
2975 static int
conv_method_index(const char * method)2976 conv_method_index(const char *method)
2977 {
2978     static const char prefix[] = "to_";
2979 
2980     if (strncmp(prefix, method, sizeof(prefix)-1) == 0) {
2981 	const char *const meth = &method[sizeof(prefix)-1];
2982 	int i;
2983 	for (i=0; i < numberof(conv_method_names); i++) {
2984 	    if (conv_method_names[i].method[0] == meth[0] &&
2985 		strcmp(conv_method_names[i].method, meth) == 0) {
2986 		return i;
2987 	    }
2988 	}
2989     }
2990     return numberof(conv_method_names);
2991 }
2992 
2993 static VALUE
convert_type_with_id(VALUE val,const char * tname,ID method,int raise,int index)2994 convert_type_with_id(VALUE val, const char *tname, ID method, int raise, int index)
2995 {
2996     VALUE r = rb_check_funcall(val, method, 0, 0);
2997     if (r == Qundef) {
2998 	if (raise) {
2999 	    const char *msg =
3000 		((index < 0 ? conv_method_index(rb_id2name(method)) : index)
3001 		 < IMPLICIT_CONVERSIONS) ?
3002 		"no implicit conversion of" : "can't convert";
3003 	    const char *cname = NIL_P(val) ? "nil" :
3004 		val == Qtrue ? "true" :
3005 		val == Qfalse ? "false" :
3006 		NULL;
3007 	    if (cname)
3008 		rb_raise(rb_eTypeError, "%s %s into %s", msg, cname, tname);
3009 	    rb_raise(rb_eTypeError, "%s %"PRIsVALUE" into %s", msg,
3010 		     rb_obj_class(val),
3011 		     tname);
3012 	}
3013 	return Qnil;
3014     }
3015     return r;
3016 }
3017 
3018 static VALUE
convert_type(VALUE val,const char * tname,const char * method,int raise)3019 convert_type(VALUE val, const char *tname, const char *method, int raise)
3020 {
3021     int i = conv_method_index(method);
3022     ID m = i < numberof(conv_method_names) ?
3023 	conv_method_names[i].id : rb_intern(method);
3024     return convert_type_with_id(val, tname, m, raise, i);
3025 }
3026 
3027 /*! \private */
3028 NORETURN(static void conversion_mismatch(VALUE, const char *, const char *, VALUE));
3029 static void
conversion_mismatch(VALUE val,const char * tname,const char * method,VALUE result)3030 conversion_mismatch(VALUE val, const char *tname, const char *method, VALUE result)
3031 {
3032     VALUE cname = rb_obj_class(val);
3033     rb_raise(rb_eTypeError,
3034 	     "can't convert %"PRIsVALUE" to %s (%"PRIsVALUE"#%s gives %"PRIsVALUE")",
3035 	     cname, tname, cname, method, rb_obj_class(result));
3036 }
3037 
3038 /*!
3039  * Converts an object into another type.
3040  * Calls the specified conversion method if necessary.
3041  *
3042  * \param[in] val    the object to be converted
3043  * \param[in] type   a value of \c ruby_value_type
3044  * \param[in] tname  name of the target type.
3045  *   only used for error messages.
3046  * \param[in] method name of the method
3047  * \return an object of the specified type
3048  * \throw TypeError on failure
3049  * \sa rb_check_convert_type
3050  */
3051 VALUE
rb_convert_type(VALUE val,int type,const char * tname,const char * method)3052 rb_convert_type(VALUE val, int type, const char *tname, const char *method)
3053 {
3054     VALUE v;
3055 
3056     if (TYPE(val) == type) return val;
3057     v = convert_type(val, tname, method, TRUE);
3058     if (TYPE(v) != type) {
3059 	conversion_mismatch(val, tname, method, v);
3060     }
3061     return v;
3062 }
3063 
3064 /*! \private */
3065 VALUE
rb_convert_type_with_id(VALUE val,int type,const char * tname,ID method)3066 rb_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
3067 {
3068     VALUE v;
3069 
3070     if (TYPE(val) == type) return val;
3071     v = convert_type_with_id(val, tname, method, TRUE, -1);
3072     if (TYPE(v) != type) {
3073 	conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v);
3074     }
3075     return v;
3076 }
3077 
3078 /*!
3079  * Tries to convert an object into another type.
3080  * Calls the specified conversion method if necessary.
3081  *
3082  * \param[in] val    the object to be converted
3083  * \param[in] type   a value of \c ruby_value_type
3084  * \param[in] tname  name of the target type.
3085  *   only used for error messages.
3086  * \param[in] method name of the method
3087  * \return an object of the specified type, or Qnil if no such conversion method defined.
3088  * \throw TypeError if the conversion method returns an unexpected type of value.
3089  * \sa rb_convert_type
3090  * \sa rb_check_convert_type_with_id
3091  */
3092 VALUE
rb_check_convert_type(VALUE val,int type,const char * tname,const char * method)3093 rb_check_convert_type(VALUE val, int type, const char *tname, const char *method)
3094 {
3095     VALUE v;
3096 
3097     /* always convert T_DATA */
3098     if (TYPE(val) == type && type != T_DATA) return val;
3099     v = convert_type(val, tname, method, FALSE);
3100     if (NIL_P(v)) return Qnil;
3101     if (TYPE(v) != type) {
3102 	conversion_mismatch(val, tname, method, v);
3103     }
3104     return v;
3105 }
3106 
3107 /*! \private */
3108 MJIT_FUNC_EXPORTED VALUE
rb_check_convert_type_with_id(VALUE val,int type,const char * tname,ID method)3109 rb_check_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
3110 {
3111     VALUE v;
3112 
3113     /* always convert T_DATA */
3114     if (TYPE(val) == type && type != T_DATA) return val;
3115     v = convert_type_with_id(val, tname, method, FALSE, -1);
3116     if (NIL_P(v)) return Qnil;
3117     if (TYPE(v) != type) {
3118 	conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v);
3119     }
3120     return v;
3121 }
3122 
3123 #define try_to_int(val, mid, raise) \
3124     convert_type_with_id(val, "Integer", mid, raise, -1)
3125 
3126 ALWAYS_INLINE(static VALUE rb_to_integer(VALUE val, const char *method, ID mid));
3127 static inline VALUE
rb_to_integer(VALUE val,const char * method,ID mid)3128 rb_to_integer(VALUE val, const char *method, ID mid)
3129 {
3130     VALUE v;
3131 
3132     if (RB_INTEGER_TYPE_P(val)) return val;
3133     v = try_to_int(val, mid, TRUE);
3134     if (!RB_INTEGER_TYPE_P(v)) {
3135         conversion_mismatch(val, "Integer", method, v);
3136     }
3137     return v;
3138 }
3139 
3140 /**
3141  * Tries to convert \a val into \c Integer.
3142  * It calls the specified conversion method if necessary.
3143  *
3144  * \param[in] val     a Ruby object
3145  * \param[in] method  a name of a method
3146  * \return an \c Integer object on success,
3147  *   or \c Qnil if no such conversion method defined.
3148  * \exception TypeError if the conversion method returns a non-Integer object.
3149  */
3150 VALUE
rb_check_to_integer(VALUE val,const char * method)3151 rb_check_to_integer(VALUE val, const char *method)
3152 {
3153     VALUE v;
3154 
3155     if (FIXNUM_P(val)) return val;
3156     if (RB_TYPE_P(val, T_BIGNUM)) return val;
3157     v = convert_type(val, "Integer", method, FALSE);
3158     if (!RB_INTEGER_TYPE_P(v)) {
3159         return Qnil;
3160     }
3161     return v;
3162 }
3163 
3164 /**
3165  * Converts \a val into \c Integer.
3166  * It calls \a #to_int method if necessary.
3167  *
3168  * \param[in] val a Ruby object
3169  * \return an \c Integer object
3170  * \exception TypeError on failure
3171  */
3172 VALUE
rb_to_int(VALUE val)3173 rb_to_int(VALUE val)
3174 {
3175     return rb_to_integer(val, "to_int", idTo_int);
3176 }
3177 
3178 /**
3179  * Tries to convert \a val into Integer.
3180  * It calls \c #to_int method if necessary.
3181  *
3182  * \param[in] val a Ruby object
3183  * \return an Integer object on success,
3184  *   or \c Qnil if \c #to_int is not defined.
3185  * \exception TypeError if \c #to_int returns a non-Integer object.
3186  */
3187 VALUE
rb_check_to_int(VALUE val)3188 rb_check_to_int(VALUE val)
3189 {
3190     if (RB_INTEGER_TYPE_P(val)) return val;
3191     val = try_to_int(val, idTo_int, FALSE);
3192     if (RB_INTEGER_TYPE_P(val)) return val;
3193     return Qnil;
3194 }
3195 
3196 static VALUE
rb_check_to_i(VALUE val)3197 rb_check_to_i(VALUE val)
3198 {
3199     if (RB_INTEGER_TYPE_P(val)) return val;
3200     val = try_to_int(val, idTo_i, FALSE);
3201     if (RB_INTEGER_TYPE_P(val)) return val;
3202     return Qnil;
3203 }
3204 
3205 static VALUE
rb_convert_to_integer(VALUE val,int base,int raise_exception)3206 rb_convert_to_integer(VALUE val, int base, int raise_exception)
3207 {
3208     VALUE tmp;
3209 
3210     if (RB_FLOAT_TYPE_P(val)) {
3211         double f;
3212         if (base != 0) goto arg_error;
3213         f = RFLOAT_VALUE(val);
3214         if (!raise_exception && !isfinite(f)) return Qnil;
3215         if (FIXABLE(f)) return LONG2FIX((long)f);
3216         return rb_dbl2big(f);
3217     }
3218     else if (RB_INTEGER_TYPE_P(val)) {
3219         if (base != 0) goto arg_error;
3220         return val;
3221     }
3222     else if (RB_TYPE_P(val, T_STRING)) {
3223         return rb_str_convert_to_inum(val, base, TRUE, raise_exception);
3224     }
3225     else if (NIL_P(val)) {
3226         if (base != 0) goto arg_error;
3227         if (!raise_exception) return Qnil;
3228         rb_raise(rb_eTypeError, "can't convert nil into Integer");
3229     }
3230     if (base != 0) {
3231         tmp = rb_check_string_type(val);
3232         if (!NIL_P(tmp)) return rb_str_convert_to_inum(tmp, base, TRUE, raise_exception);
3233       arg_error:
3234         if (!raise_exception) return Qnil;
3235         rb_raise(rb_eArgError, "base specified for non string value");
3236     }
3237 
3238     tmp = rb_protect(rb_check_to_int, val, NULL);
3239     if (RB_INTEGER_TYPE_P(tmp)) return tmp;
3240     rb_set_errinfo(Qnil);
3241 
3242     if (!raise_exception) {
3243         VALUE result = rb_protect(rb_check_to_i, val, NULL);
3244         rb_set_errinfo(Qnil);
3245         return result;
3246     }
3247 
3248     return rb_to_integer(val, "to_i", idTo_i);
3249 }
3250 
3251 /**
3252  * Equivalent to \c Kernel\#Integer in Ruby.
3253  *
3254  * Converts \a val into \c Integer in a slightly more strict manner
3255  * than \c #to_i.
3256  */
3257 VALUE
rb_Integer(VALUE val)3258 rb_Integer(VALUE val)
3259 {
3260     return rb_convert_to_integer(val, 0, TRUE);
3261 }
3262 
3263 static int
opts_exception_p(VALUE opts)3264 opts_exception_p(VALUE opts)
3265 {
3266     static ID kwds[1];
3267     VALUE exception;
3268     if (!kwds[0]) {
3269         kwds[0] = idException;
3270     }
3271     rb_get_kwargs(opts, kwds, 0, 1, &exception);
3272     return exception != Qfalse;
3273 }
3274 
3275 /*
3276  *  call-seq:
3277  *     Integer(arg, base=0, exception: true)    -> integer
3278  *
3279  *  Converts <i>arg</i> to an <code>Integer</code>.
3280  *  Numeric types are converted directly (with floating point numbers
3281  *  being truncated).  <i>base</i> (0, or between 2 and 36) is a base for
3282  *  integer string representation.  If <i>arg</i> is a <code>String</code>,
3283  *  when <i>base</i> is omitted or equals zero, radix indicators
3284  *  (<code>0</code>, <code>0b</code>, and <code>0x</code>) are honored.
3285  *  In any case, strings should be strictly conformed to numeric
3286  *  representation. This behavior is different from that of
3287  *  <code>String#to_i</code>.  Non string values will be converted by first
3288  *  trying <code>to_int</code>, then <code>to_i</code>.
3289  *
3290  *  Passing <code>nil</code> raises a TypeError, while passing a String that
3291  *  does not conform with numeric representation raises an ArgumentError.
3292  *  This behavior can be altered by passing <code>exception: false</code>,
3293  *  in this case a not convertible value will return <code>nil</code>.
3294  *
3295  *     Integer(123.999)    #=> 123
3296  *     Integer("0x1a")     #=> 26
3297  *     Integer(Time.new)   #=> 1204973019
3298  *     Integer("0930", 10) #=> 930
3299  *     Integer("111", 2)   #=> 7
3300  *     Integer(nil)        #=> TypeError: can't convert nil into Integer
3301  *     Integer("x")        #=> ArgumentError: invalid value for Integer(): "x"
3302  *
3303  *     Integer("x", exception: false)        #=> nil
3304  *
3305  */
3306 
3307 static VALUE
rb_f_integer(int argc,VALUE * argv,VALUE obj)3308 rb_f_integer(int argc, VALUE *argv, VALUE obj)
3309 {
3310     VALUE arg = Qnil, opts = Qnil;
3311     int base = 0;
3312 
3313     if (argc > 1) {
3314         int narg = 1;
3315         VALUE vbase = rb_check_to_int(argv[1]);
3316         if (!NIL_P(vbase)) {
3317             base = NUM2INT(vbase);
3318             narg = 2;
3319         }
3320         if (argc > narg) {
3321             VALUE hash = rb_check_hash_type(argv[argc-1]);
3322             if (!NIL_P(hash)) {
3323                 opts = rb_extract_keywords(&hash);
3324                 if (!hash) --argc;
3325             }
3326         }
3327     }
3328     rb_check_arity(argc, 1, 2);
3329     arg = argv[0];
3330 
3331     return rb_convert_to_integer(arg, base, opts_exception_p(opts));
3332 }
3333 
3334 static double
rb_cstr_to_dbl_raise(const char * p,int badcheck,int raise,int * error)3335 rb_cstr_to_dbl_raise(const char *p, int badcheck, int raise, int *error)
3336 {
3337     const char *q;
3338     char *end;
3339     double d;
3340     const char *ellipsis = "";
3341     int w;
3342     enum {max_width = 20};
3343 #define OutOfRange() ((end - p > max_width) ? \
3344                       (w = max_width, ellipsis = "...") : \
3345                       (w = (int)(end - p), ellipsis = ""))
3346 
3347     if (!p) return 0.0;
3348     q = p;
3349     while (ISSPACE(*p)) p++;
3350 
3351     if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3352         return 0.0;
3353     }
3354 
3355     d = strtod(p, &end);
3356     if (errno == ERANGE) {
3357         OutOfRange();
3358         rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3359         errno = 0;
3360     }
3361     if (p == end) {
3362         if (badcheck) {
3363           bad:
3364             if (raise)
3365                 rb_invalid_str(q, "Float()");
3366             else {
3367                 if (error) *error = 1;
3368                 return 0.0;
3369             }
3370         }
3371         return d;
3372     }
3373     if (*end) {
3374         char buf[DBL_DIG * 4 + 10];
3375         char *n = buf;
3376         char *const init_e = buf + DBL_DIG * 4;
3377         char *e = init_e;
3378         char prev = 0;
3379         int dot_seen = FALSE;
3380 
3381         switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3382         if (*p == '0') {
3383             prev = *n++ = '0';
3384             while (*++p == '0');
3385         }
3386         while (p < end && n < e) prev = *n++ = *p++;
3387         while (*p) {
3388             if (*p == '_') {
3389                 /* remove an underscore between digits */
3390                 if (n == buf || !ISDIGIT(prev) || (++p, !ISDIGIT(*p))) {
3391                     if (badcheck) goto bad;
3392                     break;
3393                 }
3394             }
3395             prev = *p++;
3396             if (e == init_e && (prev == 'e' || prev == 'E' || prev == 'p' || prev == 'P')) {
3397                 e = buf + sizeof(buf) - 1;
3398                 *n++ = prev;
3399                 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3400                 if (*p == '0') {
3401                     prev = *n++ = '0';
3402                     while (*++p == '0');
3403                 }
3404                 continue;
3405             }
3406             else if (ISSPACE(prev)) {
3407                 while (ISSPACE(*p)) ++p;
3408                 if (*p) {
3409                     if (badcheck) goto bad;
3410                     break;
3411                 }
3412             }
3413             else if (prev == '.' ? dot_seen++ : !ISDIGIT(prev)) {
3414                 if (badcheck) goto bad;
3415                 break;
3416             }
3417             if (n < e) *n++ = prev;
3418         }
3419         *n = '\0';
3420         p = buf;
3421 
3422         if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3423             return 0.0;
3424         }
3425 
3426         d = strtod(p, &end);
3427         if (errno == ERANGE) {
3428             OutOfRange();
3429             rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3430             errno = 0;
3431         }
3432         if (badcheck) {
3433             if (!end || p == end) goto bad;
3434             while (*end && ISSPACE(*end)) end++;
3435             if (*end) goto bad;
3436         }
3437     }
3438     if (errno == ERANGE) {
3439         errno = 0;
3440         OutOfRange();
3441         rb_raise(rb_eArgError, "Float %.*s%s out of range", w, q, ellipsis);
3442     }
3443     return d;
3444 }
3445 
3446 /*!
3447  * Parses a string representation of a floating point number.
3448  *
3449  * \param[in] p  a string representation of a floating number
3450  * \param[in] badcheck raises an exception on parse error if \a badcheck is non-zero.
3451  * \return the floating point number in the string on success,
3452  *   0.0 on parse error and \a badcheck is zero.
3453  * \note it always fails to parse a hexadecimal representation like "0xAB.CDp+1" when
3454  *   \a badcheck is zero, even though it would success if \a badcheck was non-zero.
3455  *   This inconsistency is coming from a historical compatibility reason. [ruby-dev:40822]
3456  */
3457 double
rb_cstr_to_dbl(const char * p,int badcheck)3458 rb_cstr_to_dbl(const char *p, int badcheck)
3459 {
3460     return rb_cstr_to_dbl_raise(p, badcheck, TRUE, NULL);
3461 }
3462 
3463 static double
rb_str_to_dbl_raise(VALUE str,int badcheck,int raise,int * error)3464 rb_str_to_dbl_raise(VALUE str, int badcheck, int raise, int *error)
3465 {
3466     char *s;
3467     long len;
3468     double ret;
3469     VALUE v = 0;
3470 
3471     StringValue(str);
3472     s = RSTRING_PTR(str);
3473     len = RSTRING_LEN(str);
3474     if (s) {
3475 	if (badcheck && memchr(s, '\0', len)) {
3476             if (raise)
3477                 rb_raise(rb_eArgError, "string for Float contains null byte");
3478             else {
3479                 if (error) *error = 1;
3480                 return 0.0;
3481             }
3482 	}
3483 	if (s[len]) {		/* no sentinel somehow */
3484 	    char *p = ALLOCV(v, (size_t)len + 1);
3485 	    MEMCPY(p, s, char, len);
3486 	    p[len] = '\0';
3487 	    s = p;
3488 	}
3489     }
3490     ret = rb_cstr_to_dbl_raise(s, badcheck, raise, error);
3491     if (v)
3492 	ALLOCV_END(v);
3493     return ret;
3494 }
3495 
3496 FUNC_MINIMIZED(double rb_str_to_dbl(VALUE str, int badcheck));
3497 
3498 /*!
3499  * Parses a string representation of a floating point number.
3500  *
3501  * \param[in] str  a \c String object representation of a floating number
3502  * \param[in] badcheck raises an exception on parse error if \a badcheck is non-zero.
3503  * \return the floating point number in the string on success,
3504  *   0.0 on parse error and \a badcheck is zero.
3505  * \note it always fails to parse a hexadecimal representation like "0xAB.CDp+1" when
3506  *   \a badcheck is zero, even though it would success if \a badcheck was non-zero.
3507  *   This inconsistency is coming from a historical compatibility reason. [ruby-dev:40822]
3508  */
3509 double
rb_str_to_dbl(VALUE str,int badcheck)3510 rb_str_to_dbl(VALUE str, int badcheck)
3511 {
3512     return rb_str_to_dbl_raise(str, badcheck, TRUE, NULL);
3513 }
3514 
3515 /*! \cond INTERNAL_MACRO */
3516 #define fix2dbl_without_to_f(x) (double)FIX2LONG(x)
3517 #define big2dbl_without_to_f(x) rb_big2dbl(x)
3518 #define int2dbl_without_to_f(x) \
3519     (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : big2dbl_without_to_f(x))
3520 #define num2dbl_without_to_f(x) \
3521     (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : \
3522      RB_TYPE_P(x, T_BIGNUM) ? big2dbl_without_to_f(x) : \
3523      (Check_Type(x, T_FLOAT), RFLOAT_VALUE(x)))
3524 static inline double
rat2dbl_without_to_f(VALUE x)3525 rat2dbl_without_to_f(VALUE x)
3526 {
3527     VALUE num = rb_rational_num(x);
3528     VALUE den = rb_rational_den(x);
3529     return num2dbl_without_to_f(num) / num2dbl_without_to_f(den);
3530 }
3531 
3532 #define special_const_to_float(val, pre, post) \
3533     switch (val) { \
3534       case Qnil: \
3535 	rb_raise_static(rb_eTypeError, pre "nil" post); \
3536       case Qtrue: \
3537 	rb_raise_static(rb_eTypeError, pre "true" post); \
3538       case Qfalse: \
3539 	rb_raise_static(rb_eTypeError, pre "false" post); \
3540     }
3541 /*! \endcond */
3542 
3543 static inline void
conversion_to_float(VALUE val)3544 conversion_to_float(VALUE val)
3545 {
3546     special_const_to_float(val, "can't convert ", " into Float");
3547 }
3548 
3549 static inline void
implicit_conversion_to_float(VALUE val)3550 implicit_conversion_to_float(VALUE val)
3551 {
3552     special_const_to_float(val, "no implicit conversion to float from ", "");
3553 }
3554 
3555 static int
to_float(VALUE * valp,int raise_exception)3556 to_float(VALUE *valp, int raise_exception)
3557 {
3558     VALUE val = *valp;
3559     if (SPECIAL_CONST_P(val)) {
3560 	if (FIXNUM_P(val)) {
3561 	    *valp = DBL2NUM(fix2dbl_without_to_f(val));
3562 	    return T_FLOAT;
3563 	}
3564 	else if (FLONUM_P(val)) {
3565 	    return T_FLOAT;
3566 	}
3567 	else if (raise_exception) {
3568 	    conversion_to_float(val);
3569 	}
3570     }
3571     else {
3572 	int type = BUILTIN_TYPE(val);
3573 	switch (type) {
3574 	  case T_FLOAT:
3575 	    return T_FLOAT;
3576 	  case T_BIGNUM:
3577 	    *valp = DBL2NUM(big2dbl_without_to_f(val));
3578 	    return T_FLOAT;
3579 	  case T_RATIONAL:
3580 	    *valp = DBL2NUM(rat2dbl_without_to_f(val));
3581 	    return T_FLOAT;
3582 	  case T_STRING:
3583 	    return T_STRING;
3584 	}
3585     }
3586     return T_NONE;
3587 }
3588 
3589 static VALUE
convert_type_to_float_protected(VALUE val)3590 convert_type_to_float_protected(VALUE val)
3591 {
3592     return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3593 }
3594 
3595 static VALUE
rb_convert_to_float(VALUE val,int raise_exception)3596 rb_convert_to_float(VALUE val, int raise_exception)
3597 {
3598     switch (to_float(&val, raise_exception)) {
3599       case T_FLOAT:
3600 	return val;
3601       case T_STRING:
3602         if (!raise_exception) {
3603             int e = 0;
3604             double x = rb_str_to_dbl_raise(val, TRUE, raise_exception, &e);
3605             return e ? Qnil : DBL2NUM(x);
3606         }
3607         return DBL2NUM(rb_str_to_dbl(val, TRUE));
3608       case T_NONE:
3609         if (SPECIAL_CONST_P(val) && !raise_exception)
3610             return Qnil;
3611     }
3612 
3613     if (!raise_exception) {
3614         int state;
3615         VALUE result = rb_protect(convert_type_to_float_protected, val, &state);
3616         if (state) rb_set_errinfo(Qnil);
3617         return result;
3618     }
3619 
3620     return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3621 }
3622 
3623 FUNC_MINIMIZED(VALUE rb_Float(VALUE val));
3624 
3625 /*!
3626  * Equivalent to \c Kernel\#Float in Ruby.
3627  *
3628  * Converts \a val into \c Float in a slightly more strict manner
3629  * than \c #to_f.
3630  */
3631 VALUE
rb_Float(VALUE val)3632 rb_Float(VALUE val)
3633 {
3634     return rb_convert_to_float(val, TRUE);
3635 }
3636 
3637 /*
3638  *  call-seq:
3639  *     Float(arg, exception: true)    -> float
3640  *
3641  *  Returns <i>arg</i> converted to a float. Numeric types are converted
3642  *  directly, and with exception to string and nil the rest are converted using <i>arg</i>.to_f.
3643  *  Converting a <code>string</code> with invalid characters will result in a <code>ArgumentError</code>.
3644  *  Converting <code>nil</code> generates a <code>TypeError</code>.
3645  *  Exceptions can be suppressed by passing <code>exception: false</code>.
3646  *
3647  *     Float(1)                 #=> 1.0
3648  *     Float("123.456")         #=> 123.456
3649  *     Float("123.0_badstring") #=> ArgumentError: invalid value for Float(): "123.0_badstring"
3650  *     Float(nil)               #=> TypeError: can't convert nil into Float
3651  *     Float("123.0_badstring", exception: false)  #=> nil
3652  */
3653 
3654 static VALUE
rb_f_float(int argc,VALUE * argv,VALUE obj)3655 rb_f_float(int argc, VALUE *argv, VALUE obj)
3656 {
3657     VALUE arg = Qnil, opts = Qnil;
3658 
3659     rb_scan_args(argc, argv, "1:", &arg, &opts);
3660     return rb_convert_to_float(arg, opts_exception_p(opts));
3661 }
3662 
3663 static VALUE
numeric_to_float(VALUE val)3664 numeric_to_float(VALUE val)
3665 {
3666     if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3667 	rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into Float",
3668 		 rb_obj_class(val));
3669     }
3670     return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3671 }
3672 
3673 /*!
3674  * Converts a \c Numeric object into \c Float.
3675  * \param[in] val a \c Numeric object
3676  * \exception TypeError if \a val is not a \c Numeric or other conversion failures.
3677  */
3678 VALUE
rb_to_float(VALUE val)3679 rb_to_float(VALUE val)
3680 {
3681     switch (to_float(&val, TRUE)) {
3682       case T_FLOAT:
3683 	return val;
3684     }
3685     return numeric_to_float(val);
3686 }
3687 
3688 /*!
3689  * Tries to convert an object into \c Float.
3690  * It calls \c #to_f if necessary.
3691  *
3692  * It returns \c Qnil if the object is not a \c Numeric
3693  * or \c #to_f is not defined on the object.
3694  */
3695 VALUE
rb_check_to_float(VALUE val)3696 rb_check_to_float(VALUE val)
3697 {
3698     if (RB_TYPE_P(val, T_FLOAT)) return val;
3699     if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3700 	return Qnil;
3701     }
3702     return rb_check_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3703 }
3704 
3705 static inline int
basic_to_f_p(VALUE klass)3706 basic_to_f_p(VALUE klass)
3707 {
3708     return rb_method_basic_definition_p(klass, id_to_f);
3709 }
3710 
3711 /*! \private */
3712 double
rb_num_to_dbl(VALUE val)3713 rb_num_to_dbl(VALUE val)
3714 {
3715     if (SPECIAL_CONST_P(val)) {
3716 	if (FIXNUM_P(val)) {
3717 	    if (basic_to_f_p(rb_cInteger))
3718 		return fix2dbl_without_to_f(val);
3719 	}
3720 	else if (FLONUM_P(val)) {
3721 	    return rb_float_flonum_value(val);
3722 	}
3723 	else {
3724 	    conversion_to_float(val);
3725 	}
3726     }
3727     else {
3728 	switch (BUILTIN_TYPE(val)) {
3729 	  case T_FLOAT:
3730 	    return rb_float_noflonum_value(val);
3731 	  case T_BIGNUM:
3732 	    if (basic_to_f_p(rb_cInteger))
3733 		return big2dbl_without_to_f(val);
3734 	    break;
3735 	  case T_RATIONAL:
3736 	    if (basic_to_f_p(rb_cRational))
3737 		return rat2dbl_without_to_f(val);
3738 	    break;
3739 	}
3740     }
3741     val = numeric_to_float(val);
3742     return RFLOAT_VALUE(val);
3743 }
3744 
3745 /*!
3746  * Converts a \c Numeric object to \c double.
3747  * \param[in] val a \c Numeric object
3748  * \return the converted value
3749  * \exception TypeError if \a val is not a \c Numeric or
3750  *   it does not support conversion to a floating point number.
3751  */
3752 double
rb_num2dbl(VALUE val)3753 rb_num2dbl(VALUE val)
3754 {
3755     if (SPECIAL_CONST_P(val)) {
3756 	if (FIXNUM_P(val)) {
3757 	    return fix2dbl_without_to_f(val);
3758 	}
3759 	else if (FLONUM_P(val)) {
3760 	    return rb_float_flonum_value(val);
3761 	}
3762 	else {
3763 	    implicit_conversion_to_float(val);
3764 	}
3765     }
3766     else {
3767 	switch (BUILTIN_TYPE(val)) {
3768 	  case T_FLOAT:
3769 	    return rb_float_noflonum_value(val);
3770 	  case T_BIGNUM:
3771 	    return big2dbl_without_to_f(val);
3772 	  case T_RATIONAL:
3773 	    return rat2dbl_without_to_f(val);
3774 	  case T_STRING:
3775 	    rb_raise(rb_eTypeError, "no implicit conversion to float from string");
3776 	}
3777     }
3778     val = rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3779     return RFLOAT_VALUE(val);
3780 }
3781 
3782 /*!
3783  * Equivalent to \c Kernel\#String in Ruby.
3784  *
3785  * Converts \a val into \c String by trying \c #to_str at first and
3786  * then trying \c #to_s.
3787  */
3788 VALUE
rb_String(VALUE val)3789 rb_String(VALUE val)
3790 {
3791     VALUE tmp = rb_check_string_type(val);
3792     if (NIL_P(tmp))
3793 	tmp = rb_convert_type_with_id(val, T_STRING, "String", idTo_s);
3794     return tmp;
3795 }
3796 
3797 
3798 /*
3799  *  call-seq:
3800  *     String(arg)   -> string
3801  *
3802  *  Returns <i>arg</i> as a <code>String</code>.
3803  *
3804  *  First tries to call its <code>to_str</code> method, then its <code>to_s</code> method.
3805  *
3806  *     String(self)        #=> "main"
3807  *     String(self.class)  #=> "Object"
3808  *     String(123456)      #=> "123456"
3809  */
3810 
3811 static VALUE
rb_f_string(VALUE obj,VALUE arg)3812 rb_f_string(VALUE obj, VALUE arg)
3813 {
3814     return rb_String(arg);
3815 }
3816 
3817 /*!
3818  * Equivalent to \c Kernel\#Array in Ruby.
3819  */
3820 VALUE
rb_Array(VALUE val)3821 rb_Array(VALUE val)
3822 {
3823     VALUE tmp = rb_check_array_type(val);
3824 
3825     if (NIL_P(tmp)) {
3826 	tmp = rb_check_to_array(val);
3827 	if (NIL_P(tmp)) {
3828 	    return rb_ary_new3(1, val);
3829 	}
3830     }
3831     return tmp;
3832 }
3833 
3834 /*
3835  *  call-seq:
3836  *     Array(arg)    -> array
3837  *
3838  *  Returns +arg+ as an Array.
3839  *
3840  *  First tries to call <code>to_ary</code> on +arg+, then <code>to_a</code>.
3841  *  If +arg+ does not respond to <code>to_ary</code> or <code>to_a</code>,
3842  *  returns an Array of length 1 containing +arg+.
3843  *
3844  *  If <code>to_ary</code> or <code>to_a</code> returns something other than
3845  *  an Array, raises a <code>TypeError</code>.
3846  *
3847  *     Array(["a", "b"])  #=> ["a", "b"]
3848  *     Array(1..5)        #=> [1, 2, 3, 4, 5]
3849  *     Array(key: :value) #=> [[:key, :value]]
3850  *     Array(nil)         #=> []
3851  *     Array(1)           #=> [1]
3852  */
3853 
3854 static VALUE
rb_f_array(VALUE obj,VALUE arg)3855 rb_f_array(VALUE obj, VALUE arg)
3856 {
3857     return rb_Array(arg);
3858 }
3859 
3860 /**
3861  * Equivalent to \c Kernel\#Hash in Ruby
3862  */
3863 VALUE
rb_Hash(VALUE val)3864 rb_Hash(VALUE val)
3865 {
3866     VALUE tmp;
3867 
3868     if (NIL_P(val)) return rb_hash_new();
3869     tmp = rb_check_hash_type(val);
3870     if (NIL_P(tmp)) {
3871 	if (RB_TYPE_P(val, T_ARRAY) && RARRAY_LEN(val) == 0)
3872 	    return rb_hash_new();
3873 	rb_raise(rb_eTypeError, "can't convert %s into Hash", rb_obj_classname(val));
3874     }
3875     return tmp;
3876 }
3877 
3878 /*
3879  *  call-seq:
3880  *     Hash(arg)    -> hash
3881  *
3882  *  Converts <i>arg</i> to a <code>Hash</code> by calling
3883  *  <i>arg</i><code>.to_hash</code>. Returns an empty <code>Hash</code> when
3884  *  <i>arg</i> is <tt>nil</tt> or <tt>[]</tt>.
3885  *
3886  *     Hash([])          #=> {}
3887  *     Hash(nil)         #=> {}
3888  *     Hash(key: :value) #=> {:key => :value}
3889  *     Hash([1, 2, 3])   #=> TypeError
3890  */
3891 
3892 static VALUE
rb_f_hash(VALUE obj,VALUE arg)3893 rb_f_hash(VALUE obj, VALUE arg)
3894 {
3895     return rb_Hash(arg);
3896 }
3897 
3898 /*! \private */
3899 struct dig_method {
3900     VALUE klass;
3901     int basic;
3902 };
3903 
3904 static ID id_dig;
3905 
3906 static int
dig_basic_p(VALUE obj,struct dig_method * cache)3907 dig_basic_p(VALUE obj, struct dig_method *cache)
3908 {
3909     VALUE klass = RBASIC_CLASS(obj);
3910     if (klass != cache->klass) {
3911 	cache->klass = klass;
3912 	cache->basic = rb_method_basic_definition_p(klass, id_dig);
3913     }
3914     return cache->basic;
3915 }
3916 
3917 static void
no_dig_method(int found,VALUE recv,ID mid,int argc,const VALUE * argv,VALUE data)3918 no_dig_method(int found, VALUE recv, ID mid, int argc, const VALUE *argv, VALUE data)
3919 {
3920     if (!found) {
3921 	rb_raise(rb_eTypeError, "%"PRIsVALUE" does not have #dig method",
3922 		 CLASS_OF(data));
3923     }
3924 }
3925 
3926 /*! \private */
3927 VALUE
rb_obj_dig(int argc,VALUE * argv,VALUE obj,VALUE notfound)3928 rb_obj_dig(int argc, VALUE *argv, VALUE obj, VALUE notfound)
3929 {
3930     struct dig_method hash = {Qnil}, ary = {Qnil}, strt = {Qnil};
3931 
3932     for (; argc > 0; ++argv, --argc) {
3933 	if (NIL_P(obj)) return notfound;
3934 	if (!SPECIAL_CONST_P(obj)) {
3935 	    switch (BUILTIN_TYPE(obj)) {
3936 	      case T_HASH:
3937 		if (dig_basic_p(obj, &hash)) {
3938 		    obj = rb_hash_aref(obj, *argv);
3939 		    continue;
3940 		}
3941 		break;
3942 	      case T_ARRAY:
3943 		if (dig_basic_p(obj, &ary)) {
3944 		    obj = rb_ary_at(obj, *argv);
3945 		    continue;
3946 		}
3947 		break;
3948 	      case T_STRUCT:
3949 		if (dig_basic_p(obj, &strt)) {
3950 		    obj = rb_struct_lookup(obj, *argv);
3951 		    continue;
3952 		}
3953 		break;
3954 	    }
3955 	}
3956 	return rb_check_funcall_with_hook(obj, id_dig, argc, argv,
3957 					  no_dig_method, obj);
3958     }
3959     return obj;
3960 }
3961 
3962 /*
3963  *  Document-class: Class
3964  *
3965  *  Classes in Ruby are first-class objects---each is an instance of
3966  *  class <code>Class</code>.
3967  *
3968  *  Typically, you create a new class by using:
3969  *
3970  *    class Name
3971  *     # some code describing the class behavior
3972  *    end
3973  *
3974  *  When a new class is created, an object of type Class is initialized and
3975  *  assigned to a global constant (<code>Name</code> in this case).
3976  *
3977  *  When <code>Name.new</code> is called to create a new object, the
3978  *  <code>new</code> method in <code>Class</code> is run by default.
3979  *  This can be demonstrated by overriding <code>new</code> in
3980  *  <code>Class</code>:
3981  *
3982  *     class Class
3983  *       alias old_new new
3984  *       def new(*args)
3985  *         print "Creating a new ", self.name, "\n"
3986  *         old_new(*args)
3987  *       end
3988  *     end
3989  *
3990  *     class Name
3991  *     end
3992  *
3993  *     n = Name.new
3994  *
3995  *  <em>produces:</em>
3996  *
3997  *     Creating a new Name
3998  *
3999  *  Classes, modules, and objects are interrelated. In the diagram
4000  *  that follows, the vertical arrows represent inheritance, and the
4001  *  parentheses metaclasses. All metaclasses are instances
4002  *  of the class `Class'.
4003  *                             +---------+             +-...
4004  *                             |         |             |
4005  *             BasicObject-----|-->(BasicObject)-------|-...
4006  *                 ^           |         ^             |
4007  *                 |           |         |             |
4008  *              Object---------|----->(Object)---------|-...
4009  *                 ^           |         ^             |
4010  *                 |           |         |             |
4011  *                 +-------+   |         +--------+    |
4012  *                 |       |   |         |        |    |
4013  *                 |    Module-|---------|--->(Module)-|-...
4014  *                 |       ^   |         |        ^    |
4015  *                 |       |   |         |        |    |
4016  *                 |     Class-|---------|---->(Class)-|-...
4017  *                 |       ^   |         |        ^    |
4018  *                 |       +---+         |        +----+
4019  *                 |                     |
4020  *    obj--->OtherClass---------->(OtherClass)-----------...
4021  *
4022  */
4023 
4024 
4025 /*  Document-class: BasicObject
4026  *
4027  *  BasicObject is the parent class of all classes in Ruby.  It's an explicit
4028  *  blank class.
4029  *
4030  *  BasicObject can be used for creating object hierarchies independent of
4031  *  Ruby's object hierarchy, proxy objects like the Delegator class, or other
4032  *  uses where namespace pollution from Ruby's methods and classes must be
4033  *  avoided.
4034  *
4035  *  To avoid polluting BasicObject for other users an appropriately named
4036  *  subclass of BasicObject should be created instead of directly modifying
4037  *  BasicObject:
4038  *
4039  *    class MyObjectSystem < BasicObject
4040  *    end
4041  *
4042  *  BasicObject does not include Kernel (for methods like +puts+) and
4043  *  BasicObject is outside of the namespace of the standard library so common
4044  *  classes will not be found without using a full class path.
4045  *
4046  *  A variety of strategies can be used to provide useful portions of the
4047  *  standard library to subclasses of BasicObject.  A subclass could
4048  *  <code>include Kernel</code> to obtain +puts+, +exit+, etc.  A custom
4049  *  Kernel-like module could be created and included or delegation can be used
4050  *  via #method_missing:
4051  *
4052  *    class MyObjectSystem < BasicObject
4053  *      DELEGATE = [:puts, :p]
4054  *
4055  *      def method_missing(name, *args, &block)
4056  *        super unless DELEGATE.include? name
4057  *        ::Kernel.send(name, *args, &block)
4058  *      end
4059  *
4060  *      def respond_to_missing?(name, include_private = false)
4061  *        DELEGATE.include?(name) or super
4062  *      end
4063  *    end
4064  *
4065  *  Access to classes and modules from the Ruby standard library can be
4066  *  obtained in a BasicObject subclass by referencing the desired constant
4067  *  from the root like <code>::File</code> or <code>::Enumerator</code>.
4068  *  Like #method_missing, #const_missing can be used to delegate constant
4069  *  lookup to +Object+:
4070  *
4071  *    class MyObjectSystem < BasicObject
4072  *      def self.const_missing(name)
4073  *        ::Object.const_get(name)
4074  *      end
4075  *    end
4076  */
4077 
4078 /*  Document-class: Object
4079  *
4080  *  Object is the default root of all Ruby objects.  Object inherits from
4081  *  BasicObject which allows creating alternate object hierarchies.  Methods
4082  *  on Object are available to all classes unless explicitly overridden.
4083  *
4084  *  Object mixes in the Kernel module, making the built-in kernel functions
4085  *  globally accessible.  Although the instance methods of Object are defined
4086  *  by the Kernel module, we have chosen to document them here for clarity.
4087  *
4088  *  When referencing constants in classes inheriting from Object you do not
4089  *  need to use the full namespace.  For example, referencing +File+ inside
4090  *  +YourClass+ will find the top-level File class.
4091  *
4092  *  In the descriptions of Object's methods, the parameter <i>symbol</i> refers
4093  *  to a symbol, which is either a quoted string or a Symbol (such as
4094  *  <code>:name</code>).
4095  */
4096 
4097 /*!
4098  *--
4099  * \private
4100  * Initializes the world of objects and classes.
4101  *
4102  * At first, the function bootstraps the class hierarchy.
4103  * It initializes the most fundamental classes and their metaclasses.
4104  * - \c BasicObject
4105  * - \c Object
4106  * - \c Module
4107  * - \c Class
4108  * After the bootstrap step, the class hierarchy becomes as the following
4109  * diagram.
4110  *
4111  * \image html boottime-classes.png
4112  *
4113  * Then, the function defines classes, modules and methods as usual.
4114  * \ingroup class
4115  *++
4116  */
4117 
4118 void
InitVM_Object(void)4119 InitVM_Object(void)
4120 {
4121     Init_class_hierarchy();
4122 
4123 #if 0
4124     // teach RDoc about these classes
4125     rb_cBasicObject = rb_define_class("BasicObject", Qnil);
4126     rb_cObject = rb_define_class("Object", rb_cBasicObject);
4127     rb_cModule = rb_define_class("Module", rb_cObject);
4128     rb_cClass =  rb_define_class("Class",  rb_cModule);
4129 #endif
4130 
4131 #undef rb_intern
4132 #define rb_intern(str) rb_intern_const(str)
4133 
4134     rb_define_private_method(rb_cBasicObject, "initialize", rb_obj_dummy, 0);
4135     rb_define_alloc_func(rb_cBasicObject, rb_class_allocate_instance);
4136     rb_define_method(rb_cBasicObject, "==", rb_obj_equal, 1);
4137     rb_define_method(rb_cBasicObject, "equal?", rb_obj_equal, 1);
4138     rb_define_method(rb_cBasicObject, "!", rb_obj_not, 0);
4139     rb_define_method(rb_cBasicObject, "!=", rb_obj_not_equal, 1);
4140 
4141     rb_define_private_method(rb_cBasicObject, "singleton_method_added", rb_obj_dummy, 1);
4142     rb_define_private_method(rb_cBasicObject, "singleton_method_removed", rb_obj_dummy, 1);
4143     rb_define_private_method(rb_cBasicObject, "singleton_method_undefined", rb_obj_dummy, 1);
4144 
4145     /* Document-module: Kernel
4146      *
4147      * The Kernel module is included by class Object, so its methods are
4148      * available in every Ruby object.
4149      *
4150      * The Kernel instance methods are documented in class Object while the
4151      * module methods are documented here.  These methods are called without a
4152      * receiver and thus can be called in functional form:
4153      *
4154      *   sprintf "%.1f", 1.234 #=> "1.2"
4155      *
4156      */
4157     rb_mKernel = rb_define_module("Kernel");
4158     rb_include_module(rb_cObject, rb_mKernel);
4159     rb_define_private_method(rb_cClass, "inherited", rb_obj_dummy, 1);
4160     rb_define_private_method(rb_cModule, "included", rb_obj_dummy, 1);
4161     rb_define_private_method(rb_cModule, "extended", rb_obj_dummy, 1);
4162     rb_define_private_method(rb_cModule, "prepended", rb_obj_dummy, 1);
4163     rb_define_private_method(rb_cModule, "method_added", rb_obj_dummy, 1);
4164     rb_define_private_method(rb_cModule, "method_removed", rb_obj_dummy, 1);
4165     rb_define_private_method(rb_cModule, "method_undefined", rb_obj_dummy, 1);
4166 
4167     rb_define_method(rb_mKernel, "nil?", rb_false, 0);
4168     rb_define_method(rb_mKernel, "===", rb_equal, 1);
4169     rb_define_method(rb_mKernel, "=~", rb_obj_match, 1);
4170     rb_define_method(rb_mKernel, "!~", rb_obj_not_match, 1);
4171     rb_define_method(rb_mKernel, "eql?", rb_obj_equal, 1);
4172     rb_define_method(rb_mKernel, "hash", rb_obj_hash, 0);
4173     rb_define_method(rb_mKernel, "<=>", rb_obj_cmp, 1);
4174 
4175     rb_define_method(rb_mKernel, "class", rb_obj_class, 0);
4176     rb_define_method(rb_mKernel, "singleton_class", rb_obj_singleton_class, 0);
4177     rb_define_method(rb_mKernel, "clone", rb_obj_clone2, -1);
4178     rb_define_method(rb_mKernel, "dup", rb_obj_dup, 0);
4179     rb_define_method(rb_mKernel, "itself", rb_obj_itself, 0);
4180     rb_define_method(rb_mKernel, "yield_self", rb_obj_yield_self, 0);
4181     rb_define_method(rb_mKernel, "then", rb_obj_yield_self, 0);
4182     rb_define_method(rb_mKernel, "initialize_copy", rb_obj_init_copy, 1);
4183     rb_define_method(rb_mKernel, "initialize_dup", rb_obj_init_dup_clone, 1);
4184     rb_define_method(rb_mKernel, "initialize_clone", rb_obj_init_dup_clone, 1);
4185 
4186     rb_define_method(rb_mKernel, "taint", rb_obj_taint, 0);
4187     rb_define_method(rb_mKernel, "tainted?", rb_obj_tainted, 0);
4188     rb_define_method(rb_mKernel, "untaint", rb_obj_untaint, 0);
4189     rb_define_method(rb_mKernel, "untrust", rb_obj_untrust, 0);
4190     rb_define_method(rb_mKernel, "untrusted?", rb_obj_untrusted, 0);
4191     rb_define_method(rb_mKernel, "trust", rb_obj_trust, 0);
4192     rb_define_method(rb_mKernel, "freeze", rb_obj_freeze, 0);
4193     rb_define_method(rb_mKernel, "frozen?", rb_obj_frozen_p, 0);
4194 
4195     rb_define_method(rb_mKernel, "to_s", rb_any_to_s, 0);
4196     rb_define_method(rb_mKernel, "inspect", rb_obj_inspect, 0);
4197     rb_define_method(rb_mKernel, "methods", rb_obj_methods, -1); /* in class.c */
4198     rb_define_method(rb_mKernel, "singleton_methods", rb_obj_singleton_methods, -1); /* in class.c */
4199     rb_define_method(rb_mKernel, "protected_methods", rb_obj_protected_methods, -1); /* in class.c */
4200     rb_define_method(rb_mKernel, "private_methods", rb_obj_private_methods, -1); /* in class.c */
4201     rb_define_method(rb_mKernel, "public_methods", rb_obj_public_methods, -1); /* in class.c */
4202     rb_define_method(rb_mKernel, "instance_variables", rb_obj_instance_variables, 0); /* in variable.c */
4203     rb_define_method(rb_mKernel, "instance_variable_get", rb_obj_ivar_get, 1);
4204     rb_define_method(rb_mKernel, "instance_variable_set", rb_obj_ivar_set, 2);
4205     rb_define_method(rb_mKernel, "instance_variable_defined?", rb_obj_ivar_defined, 1);
4206     rb_define_method(rb_mKernel, "remove_instance_variable",
4207 		     rb_obj_remove_instance_variable, 1); /* in variable.c */
4208 
4209     rb_define_method(rb_mKernel, "instance_of?", rb_obj_is_instance_of, 1);
4210     rb_define_method(rb_mKernel, "kind_of?", rb_obj_is_kind_of, 1);
4211     rb_define_method(rb_mKernel, "is_a?", rb_obj_is_kind_of, 1);
4212     rb_define_method(rb_mKernel, "tap", rb_obj_tap, 0);
4213 
4214     rb_define_global_function("sprintf", rb_f_sprintf, -1); /* in sprintf.c */
4215     rb_define_global_function("format", rb_f_sprintf, -1);  /* in sprintf.c */
4216 
4217     rb_define_global_function("Integer", rb_f_integer, -1);
4218     rb_define_global_function("Float", rb_f_float, -1);
4219 
4220     rb_define_global_function("String", rb_f_string, 1);
4221     rb_define_global_function("Array", rb_f_array, 1);
4222     rb_define_global_function("Hash", rb_f_hash, 1);
4223 
4224     rb_cNilClass = rb_define_class("NilClass", rb_cObject);
4225     rb_define_method(rb_cNilClass, "to_i", nil_to_i, 0);
4226     rb_define_method(rb_cNilClass, "to_f", nil_to_f, 0);
4227     rb_define_method(rb_cNilClass, "to_s", nil_to_s, 0);
4228     rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0);
4229     rb_define_method(rb_cNilClass, "to_h", nil_to_h, 0);
4230     rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0);
4231     rb_define_method(rb_cNilClass, "=~", nil_match, 1);
4232     rb_define_method(rb_cNilClass, "&", false_and, 1);
4233     rb_define_method(rb_cNilClass, "|", false_or, 1);
4234     rb_define_method(rb_cNilClass, "^", false_xor, 1);
4235     rb_define_method(rb_cNilClass, "===", rb_equal, 1);
4236 
4237     rb_define_method(rb_cNilClass, "nil?", rb_true, 0);
4238     rb_undef_alloc_func(rb_cNilClass);
4239     rb_undef_method(CLASS_OF(rb_cNilClass), "new");
4240     /*
4241      * An obsolete alias of +nil+
4242      */
4243     rb_define_global_const("NIL", Qnil);
4244     rb_deprecate_constant(rb_cObject, "NIL");
4245 
4246     rb_define_method(rb_cModule, "freeze", rb_mod_freeze, 0);
4247     rb_define_method(rb_cModule, "===", rb_mod_eqq, 1);
4248     rb_define_method(rb_cModule, "==", rb_obj_equal, 1);
4249     rb_define_method(rb_cModule, "<=>",  rb_mod_cmp, 1);
4250     rb_define_method(rb_cModule, "<",  rb_mod_lt, 1);
4251     rb_define_method(rb_cModule, "<=", rb_class_inherited_p, 1);
4252     rb_define_method(rb_cModule, ">",  rb_mod_gt, 1);
4253     rb_define_method(rb_cModule, ">=", rb_mod_ge, 1);
4254     rb_define_method(rb_cModule, "initialize_copy", rb_mod_init_copy, 1); /* in class.c */
4255     rb_define_method(rb_cModule, "to_s", rb_mod_to_s, 0);
4256     rb_define_alias(rb_cModule, "inspect", "to_s");
4257     rb_define_method(rb_cModule, "included_modules", rb_mod_included_modules, 0); /* in class.c */
4258     rb_define_method(rb_cModule, "include?", rb_mod_include_p, 1); /* in class.c */
4259     rb_define_method(rb_cModule, "name", rb_mod_name, 0);  /* in variable.c */
4260     rb_define_method(rb_cModule, "ancestors", rb_mod_ancestors, 0); /* in class.c */
4261 
4262     rb_define_method(rb_cModule, "attr", rb_mod_attr, -1);
4263     rb_define_method(rb_cModule, "attr_reader", rb_mod_attr_reader, -1);
4264     rb_define_method(rb_cModule, "attr_writer", rb_mod_attr_writer, -1);
4265     rb_define_method(rb_cModule, "attr_accessor", rb_mod_attr_accessor, -1);
4266 
4267     rb_define_alloc_func(rb_cModule, rb_module_s_alloc);
4268     rb_define_method(rb_cModule, "initialize", rb_mod_initialize, 0);
4269     rb_define_method(rb_cModule, "initialize_clone", rb_mod_initialize_clone, 1);
4270     rb_define_method(rb_cModule, "instance_methods", rb_class_instance_methods, -1); /* in class.c */
4271     rb_define_method(rb_cModule, "public_instance_methods",
4272 		     rb_class_public_instance_methods, -1);    /* in class.c */
4273     rb_define_method(rb_cModule, "protected_instance_methods",
4274 		     rb_class_protected_instance_methods, -1); /* in class.c */
4275     rb_define_method(rb_cModule, "private_instance_methods",
4276 		     rb_class_private_instance_methods, -1);   /* in class.c */
4277 
4278     rb_define_method(rb_cModule, "constants", rb_mod_constants, -1); /* in variable.c */
4279     rb_define_method(rb_cModule, "const_get", rb_mod_const_get, -1);
4280     rb_define_method(rb_cModule, "const_set", rb_mod_const_set, 2);
4281     rb_define_method(rb_cModule, "const_defined?", rb_mod_const_defined, -1);
4282     rb_define_private_method(rb_cModule, "remove_const",
4283 			     rb_mod_remove_const, 1); /* in variable.c */
4284     rb_define_method(rb_cModule, "const_missing",
4285 		     rb_mod_const_missing, 1); /* in variable.c */
4286     rb_define_method(rb_cModule, "class_variables",
4287 		     rb_mod_class_variables, -1); /* in variable.c */
4288     rb_define_method(rb_cModule, "remove_class_variable",
4289 		     rb_mod_remove_cvar, 1); /* in variable.c */
4290     rb_define_method(rb_cModule, "class_variable_get", rb_mod_cvar_get, 1);
4291     rb_define_method(rb_cModule, "class_variable_set", rb_mod_cvar_set, 2);
4292     rb_define_method(rb_cModule, "class_variable_defined?", rb_mod_cvar_defined, 1);
4293     rb_define_method(rb_cModule, "public_constant", rb_mod_public_constant, -1); /* in variable.c */
4294     rb_define_method(rb_cModule, "private_constant", rb_mod_private_constant, -1); /* in variable.c */
4295     rb_define_method(rb_cModule, "deprecate_constant", rb_mod_deprecate_constant, -1); /* in variable.c */
4296     rb_define_method(rb_cModule, "singleton_class?", rb_mod_singleton_p, 0);
4297 
4298     rb_define_method(rb_cClass, "allocate", rb_class_alloc_m, 0);
4299     rb_define_method(rb_cClass, "new", rb_class_s_new, -1);
4300     rb_define_method(rb_cClass, "initialize", rb_class_initialize, -1);
4301     rb_define_method(rb_cClass, "superclass", rb_class_superclass, 0);
4302     rb_define_alloc_func(rb_cClass, rb_class_s_alloc);
4303     rb_undef_method(rb_cClass, "extend_object");
4304     rb_undef_method(rb_cClass, "append_features");
4305     rb_undef_method(rb_cClass, "prepend_features");
4306 
4307     /*
4308      * Document-class: Data
4309      *
4310      * This is a deprecated class, base class for C extensions using
4311      * Data_Make_Struct or Data_Wrap_Struct.
4312      */
4313     rb_cData = rb_define_class("Data", rb_cObject);
4314     rb_undef_alloc_func(rb_cData);
4315     rb_deprecate_constant(rb_cObject, "Data");
4316 
4317     rb_cTrueClass = rb_define_class("TrueClass", rb_cObject);
4318     rb_define_method(rb_cTrueClass, "to_s", true_to_s, 0);
4319     rb_define_alias(rb_cTrueClass, "inspect", "to_s");
4320     rb_define_method(rb_cTrueClass, "&", true_and, 1);
4321     rb_define_method(rb_cTrueClass, "|", true_or, 1);
4322     rb_define_method(rb_cTrueClass, "^", true_xor, 1);
4323     rb_define_method(rb_cTrueClass, "===", rb_equal, 1);
4324     rb_undef_alloc_func(rb_cTrueClass);
4325     rb_undef_method(CLASS_OF(rb_cTrueClass), "new");
4326     /*
4327      * An obsolete alias of +true+
4328      */
4329     rb_define_global_const("TRUE", Qtrue);
4330     rb_deprecate_constant(rb_cObject, "TRUE");
4331 
4332     rb_cFalseClass = rb_define_class("FalseClass", rb_cObject);
4333     rb_define_method(rb_cFalseClass, "to_s", false_to_s, 0);
4334     rb_define_alias(rb_cFalseClass, "inspect", "to_s");
4335     rb_define_method(rb_cFalseClass, "&", false_and, 1);
4336     rb_define_method(rb_cFalseClass, "|", false_or, 1);
4337     rb_define_method(rb_cFalseClass, "^", false_xor, 1);
4338     rb_define_method(rb_cFalseClass, "===", rb_equal, 1);
4339     rb_undef_alloc_func(rb_cFalseClass);
4340     rb_undef_method(CLASS_OF(rb_cFalseClass), "new");
4341     /*
4342      * An obsolete alias of +false+
4343      */
4344     rb_define_global_const("FALSE", Qfalse);
4345     rb_deprecate_constant(rb_cObject, "FALSE");
4346 }
4347 
4348 void
Init_Object(void)4349 Init_Object(void)
4350 {
4351     id_dig = rb_intern_const("dig");
4352     InitVM(Object);
4353 }
4354 
4355 /*!
4356  * \}
4357  */
4358