1 /**********************************************************************
6 created at: Thu Jul 15 12:01:24 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
12 **********************************************************************/
14 #include "ruby/internal/config.h"
25 #include "internal/array.h"
26 #include "internal/class.h"
27 #include "internal/error.h"
28 #include "internal/eval.h"
29 #include "internal/inits.h"
30 #include "internal/numeric.h"
31 #include "internal/object.h"
32 #include "internal/struct.h"
33 #include "internal/string.h"
34 #include "internal/symbol.h"
35 #include "internal/variable.h"
37 #include "ruby/encoding.h"
39 #include "ruby/util.h"
40 #include "ruby/assert.h"
48 VALUE rb_cBasicObject
;
59 static VALUE rb_cNilClass_to_s
;
60 static VALUE rb_cTrueClass_to_s
;
61 static VALUE rb_cFalseClass_to_s
;
63 /*! \cond INTERNAL_MACRO */
67 #define id_match idEqTilde
68 #define id_inspect idInspect
69 #define id_init_copy idInitialize_copy
70 #define id_init_clone idInitialize_clone
71 #define id_init_dup idInitialize_dup
72 #define id_const_missing idConst_missing
73 #define id_to_f idTo_f
75 #define CLASS_OR_MODULE_P(obj) \
76 (!SPECIAL_CONST_P(obj) && \
77 (BUILTIN_TYPE(obj) == T_CLASS || BUILTIN_TYPE(obj) == T_MODULE))
82 rb_obj_hide(VALUE obj
)
84 if (!SPECIAL_CONST_P(obj
)) {
85 RBASIC_CLEAR_CLASS(obj
);
91 rb_obj_reveal(VALUE obj
, VALUE klass
)
93 if (!SPECIAL_CONST_P(obj
)) {
94 RBASIC_SET_CLASS(obj
, klass
);
100 rb_obj_setup(VALUE obj
, VALUE klass
, VALUE type
)
102 RBASIC(obj
)->flags
= type
;
103 RBASIC_SET_CLASS(obj
, klass
);
109 * obj === other -> true or false
111 * Case Equality -- For class Object, effectively the same as calling
112 * <code>#==</code>, but typically overridden by descendants to provide
113 * meaningful semantics in +case+ statements.
115 #define case_equal rb_equal
116 /* The default implementation of #=== is
117 * to call #== with the rb_equal() optimization. */
120 rb_equal(VALUE obj1
, VALUE obj2
)
124 if (obj1
== obj2
) return Qtrue
;
125 result
= rb_equal_opt(obj1
, obj2
);
126 if (result
== Qundef
) {
127 result
= rb_funcall(obj1
, id_eq
, 1, obj2
);
129 return RBOOL(RTEST(result
));
133 rb_eql(VALUE obj1
, VALUE obj2
)
137 if (obj1
== obj2
) return Qtrue
;
138 result
= rb_eql_opt(obj1
, obj2
);
139 if (result
== Qundef
) {
140 result
= rb_funcall(obj1
, id_eql
, 1, obj2
);
142 return RBOOL(RTEST(result
));
147 * obj == other -> true or false
148 * obj.equal?(other) -> true or false
149 * obj.eql?(other) -> true or false
151 * Equality --- At the Object level, #== returns <code>true</code>
152 * only if +obj+ and +other+ are the same object. Typically, this
153 * method is overridden in descendant classes to provide
154 * class-specific meaning.
156 * Unlike #==, the #equal? method should never be overridden by
157 * subclasses as it is used to determine object identity (that is,
158 * <code>a.equal?(b)</code> if and only if <code>a</code> is the same
159 * object as <code>b</code>):
164 * obj == other #=> true
165 * obj.equal? other #=> false
166 * obj.equal? obj #=> true
168 * The #eql? method returns <code>true</code> if +obj+ and +other+
169 * refer to the same hash key. This is used by Hash to test members
170 * for equality. For any pair of objects where #eql? returns +true+,
171 * the #hash value of both objects must be equal. So any subclass
172 * that overrides #eql? should also override #hash appropriately.
174 * For objects of class Object, #eql? is synonymous
175 * with #==. Subclasses normally continue this tradition by aliasing
176 * #eql? to their overridden #== method, but there are exceptions.
177 * Numeric types, for example, perform type conversion across #==,
178 * but not across #eql?, so:
181 * 1.eql? 1.0 #=> false
186 MJIT_FUNC_EXPORTED VALUE
187 rb_obj_equal(VALUE obj1
, VALUE obj2
)
189 return RBOOL(obj1
== obj2
);
192 VALUE
rb_obj_hash(VALUE obj
);
196 * !obj -> true or false
204 MJIT_FUNC_EXPORTED VALUE
205 rb_obj_not(VALUE obj
)
207 return RTEST(obj
) ? Qfalse
: Qtrue
;
212 * obj != other -> true or false
214 * Returns true if two objects are not-equal, otherwise false.
220 MJIT_FUNC_EXPORTED VALUE
221 rb_obj_not_equal(VALUE obj1
, VALUE obj2
)
223 VALUE result
= rb_funcall(obj1
, id_eq
, 1, obj2
);
224 return RTEST(result
) ? Qfalse
: Qtrue
;
228 rb_class_real(VALUE cl
)
231 ((RBASIC(cl
)->flags
& FL_SINGLETON
) || BUILTIN_TYPE(cl
) == T_ICLASS
)) {
232 cl
= RCLASS_SUPER(cl
);
238 rb_obj_class(VALUE obj
)
240 return rb_class_real(CLASS_OF(obj
));
245 * obj.singleton_class -> class
247 * Returns the singleton class of <i>obj</i>. This method creates
248 * a new singleton class if <i>obj</i> does not have one.
250 * If <i>obj</i> is <code>nil</code>, <code>true</code>, or
251 * <code>false</code>, it returns NilClass, TrueClass, or FalseClass,
253 * If <i>obj</i> is an Integer, a Float or a Symbol, it raises a TypeError.
255 * Object.new.singleton_class #=> #<Class:#<Object:0xb7ce1e24>>
256 * String.singleton_class #=> #<Class:String>
257 * nil.singleton_class #=> NilClass
261 rb_obj_singleton_class(VALUE obj
)
263 return rb_singleton_class(obj
);
267 MJIT_FUNC_EXPORTED
void
268 rb_obj_copy_ivar(VALUE dest
, VALUE obj
)
272 uint32_t len
= ROBJECT_EMBED_LEN_MAX
;
274 if (RBASIC(obj
)->flags
& ROBJECT_EMBED
) {
275 src_buf
= ROBJECT(obj
)->as
.ary
;
277 // embedded -> embedded
278 if (RBASIC(dest
)->flags
& ROBJECT_EMBED
) {
279 dst_buf
= ROBJECT(dest
)->as
.ary
;
281 // embedded -> extended
283 dst_buf
= ROBJECT(dest
)->as
.heap
.ivptr
;
286 // extended -> extended
288 uint32_t src_len
= ROBJECT(obj
)->as
.heap
.numiv
;
289 uint32_t dst_len
= ROBJECT(dest
)->as
.heap
.numiv
;
291 len
= src_len
< dst_len
? src_len
: dst_len
;
292 dst_buf
= ROBJECT(dest
)->as
.heap
.ivptr
;
293 src_buf
= ROBJECT(obj
)->as
.heap
.ivptr
;
296 MEMCPY(dst_buf
, src_buf
, VALUE
, len
);
300 init_copy(VALUE dest
, VALUE obj
)
302 if (OBJ_FROZEN(dest
)) {
303 rb_raise(rb_eTypeError
, "[bug] frozen object (%s) allocated", rb_obj_classname(dest
));
305 RBASIC(dest
)->flags
&= ~(T_MASK
|FL_EXIVAR
);
306 RBASIC(dest
)->flags
|= RBASIC(obj
)->flags
& (T_MASK
|FL_EXIVAR
);
307 rb_copy_wb_protected_attribute(dest
, obj
);
308 rb_copy_generic_ivar(dest
, obj
);
309 rb_gc_copy_finalizer(dest
, obj
);
310 if (RB_TYPE_P(obj
, T_OBJECT
)) {
311 rb_obj_copy_ivar(dest
, obj
);
315 static VALUE
immutable_obj_clone(VALUE obj
, VALUE kwfreeze
);
316 static VALUE
mutable_obj_clone(VALUE obj
, VALUE kwfreeze
);
317 PUREFUNC(static inline int special_object_p(VALUE obj
)); /*!< \private */
319 special_object_p(VALUE obj
)
321 if (SPECIAL_CONST_P(obj
)) return TRUE
;
322 switch (BUILTIN_TYPE(obj
)) {
328 /* not a comprehensive list */
336 obj_freeze_opt(VALUE freeze
)
344 rb_raise(rb_eArgError
, "unexpected value for freeze: %"PRIsVALUE
, rb_obj_class(freeze
));
351 rb_obj_clone2(rb_execution_context_t
*ec
, VALUE obj
, VALUE freeze
)
353 VALUE kwfreeze
= obj_freeze_opt(freeze
);
354 if (!special_object_p(obj
))
355 return mutable_obj_clone(obj
, kwfreeze
);
356 return immutable_obj_clone(obj
, kwfreeze
);
361 rb_immutable_obj_clone(int argc
, VALUE
*argv
, VALUE obj
)
363 VALUE kwfreeze
= rb_get_freeze_opt(argc
, argv
);
364 return immutable_obj_clone(obj
, kwfreeze
);
368 rb_get_freeze_opt(int argc
, VALUE
*argv
)
370 static ID keyword_ids
[1];
372 VALUE kwfreeze
= Qnil
;
374 if (!keyword_ids
[0]) {
375 CONST_ID(keyword_ids
[0], "freeze");
377 rb_scan_args(argc
, argv
, "0:", &opt
);
379 rb_get_kwargs(opt
, keyword_ids
, 0, 1, &kwfreeze
);
380 if (kwfreeze
!= Qundef
)
381 kwfreeze
= obj_freeze_opt(kwfreeze
);
387 immutable_obj_clone(VALUE obj
, VALUE kwfreeze
)
389 if (kwfreeze
== Qfalse
)
390 rb_raise(rb_eArgError
, "can't unfreeze %"PRIsVALUE
,
396 mutable_obj_clone(VALUE obj
, VALUE kwfreeze
)
398 VALUE clone
, singleton
;
401 clone
= rb_obj_alloc(rb_obj_class(obj
));
403 singleton
= rb_singleton_class_clone_and_attach(obj
, clone
);
404 RBASIC_SET_CLASS(clone
, singleton
);
405 if (FL_TEST(singleton
, FL_SINGLETON
)) {
406 rb_singleton_class_attached(singleton
, clone
);
409 init_copy(clone
, obj
);
413 rb_funcall(clone
, id_init_clone
, 1, obj
);
414 RBASIC(clone
)->flags
|= RBASIC(obj
)->flags
& FL_FREEZE
;
418 static VALUE freeze_true_hash
;
419 if (!freeze_true_hash
) {
420 freeze_true_hash
= rb_hash_new();
421 rb_gc_register_mark_object(freeze_true_hash
);
422 rb_hash_aset(freeze_true_hash
, ID2SYM(idFreeze
), Qtrue
);
423 rb_obj_freeze(freeze_true_hash
);
427 argv
[1] = freeze_true_hash
;
428 rb_funcallv_kw(clone
, id_init_clone
, 2, argv
, RB_PASS_KEYWORDS
);
429 RBASIC(clone
)->flags
|= FL_FREEZE
;
434 static VALUE freeze_false_hash
;
435 if (!freeze_false_hash
) {
436 freeze_false_hash
= rb_hash_new();
437 rb_gc_register_mark_object(freeze_false_hash
);
438 rb_hash_aset(freeze_false_hash
, ID2SYM(idFreeze
), Qfalse
);
439 rb_obj_freeze(freeze_false_hash
);
443 argv
[1] = freeze_false_hash
;
444 rb_funcallv_kw(clone
, id_init_clone
, 2, argv
, RB_PASS_KEYWORDS
);
448 rb_bug("invalid kwfreeze passed to mutable_obj_clone");
455 rb_obj_clone(VALUE obj
)
457 if (special_object_p(obj
)) return obj
;
458 return mutable_obj_clone(obj
, Qnil
);
463 * obj.dup -> an_object
465 * Produces a shallow copy of <i>obj</i>---the instance variables of
466 * <i>obj</i> are copied, but not the objects they reference.
468 * This method may have class-specific behavior. If so, that
469 * behavior will be documented under the #+initialize_copy+ method of
472 * === on dup vs clone
474 * In general, #clone and #dup may have different semantics in
475 * descendant classes. While #clone is used to duplicate an object,
476 * including its internal state, #dup typically uses the class of the
477 * descendant object to create the new instance.
479 * When using #dup, any modules that the object has been extended with will not
487 * def foo; 'foo'; end
490 * s1 = Klass.new #=> #<Klass:0x401b3a38>
491 * s1.extend(Foo) #=> #<Klass:0x401b3a38>
494 * s2 = s1.clone #=> #<Klass:0x401be280>
497 * s3 = s1.dup #=> #<Klass:0x401c1084>
498 * s3.foo #=> NoMethodError: undefined method `foo' for #<Klass:0x401c1084>
501 rb_obj_dup(VALUE obj
)
505 if (special_object_p(obj
)) {
508 dup
= rb_obj_alloc(rb_obj_class(obj
));
510 rb_funcall(dup
, id_init_dup
, 1, obj
);
519 * Returns the receiver.
521 * string = "my string"
522 * string.itself.object_id == string.object_id #=> true
527 rb_obj_itself(VALUE obj
)
533 rb_obj_size(VALUE self
, VALUE args
, VALUE obj
)
539 block_given_p(rb_execution_context_t
*ec
, VALUE self
)
541 return RBOOL(rb_block_given_p());
547 * Default implementation of \c #initialize_copy
548 * \param[in,out] obj the receiver being initialized
549 * \param[in] orig the object to be copied from.
553 rb_obj_init_copy(VALUE obj
, VALUE orig
)
555 if (obj
== orig
) return obj
;
556 rb_check_frozen(obj
);
557 if (TYPE(obj
) != TYPE(orig
) || rb_obj_class(obj
) != rb_obj_class(orig
)) {
558 rb_raise(rb_eTypeError
, "initialize_copy should take same class object");
566 * Default implementation of \c #initialize_dup
568 * \param[in,out] obj the receiver being initialized
569 * \param[in] orig the object to be dup from.
573 rb_obj_init_dup_clone(VALUE obj
, VALUE orig
)
575 rb_funcall(obj
, id_init_copy
, 1, orig
);
582 * Default implementation of \c #initialize_clone
584 * \param[in] The number of arguments
585 * \param[in] The array of arguments
586 * \param[in] obj the receiver being initialized
590 rb_obj_init_clone(int argc
, VALUE
*argv
, VALUE obj
)
593 if (rb_scan_args(argc
, argv
, "1:", &orig
, &opts
) < argc
) {
594 /* Ignore a freeze keyword */
595 rb_get_freeze_opt(1, &opts
);
597 rb_funcall(obj
, id_init_copy
, 1, orig
);
605 * Returns a string representing <i>obj</i>. The default #to_s prints
606 * the object's class and an encoding of the object id. As a special
607 * case, the top-level object that is the initial execution context
608 * of Ruby programs returns ``main''.
612 rb_any_to_s(VALUE obj
)
615 VALUE cname
= rb_class_name(CLASS_OF(obj
));
617 str
= rb_sprintf("#<%"PRIsVALUE
":%p>", cname
, (void*)obj
);
623 rb_inspect(VALUE obj
)
625 VALUE str
= rb_obj_as_string(rb_funcallv(obj
, id_inspect
, 0, 0));
627 rb_encoding
*enc
= rb_default_internal_encoding();
628 if (enc
== NULL
) enc
= rb_default_external_encoding();
629 if (!rb_enc_asciicompat(enc
)) {
630 if (!rb_enc_str_asciionly_p(str
))
631 return rb_str_escape(str
);
634 if (rb_enc_get(str
) != enc
&& !rb_enc_str_asciionly_p(str
))
635 return rb_str_escape(str
);
640 inspect_i(st_data_t k
, st_data_t v
, st_data_t a
)
643 VALUE value
= (VALUE
)v
;
644 VALUE str
= (VALUE
)a
;
646 /* need not to show internal data */
647 if (CLASS_OF(value
) == 0) return ST_CONTINUE
;
648 if (!rb_is_instance_id(id
)) return ST_CONTINUE
;
649 if (RSTRING_PTR(str
)[0] == '-') { /* first element */
650 RSTRING_PTR(str
)[0] = '#';
651 rb_str_cat2(str
, " ");
654 rb_str_cat2(str
, ", ");
656 rb_str_catf(str
, "%"PRIsVALUE
"=%+"PRIsVALUE
,
657 rb_id2str(id
), value
);
663 inspect_obj(VALUE obj
, VALUE str
, int recur
)
666 rb_str_cat2(str
, " ...");
669 rb_ivar_foreach(obj
, inspect_i
, str
);
671 rb_str_cat2(str
, ">");
672 RSTRING_PTR(str
)[0] = '#';
679 * obj.inspect -> string
681 * Returns a string containing a human-readable representation of <i>obj</i>.
682 * The default #inspect shows the object's class name, an encoding of
683 * its memory address, and a list of the instance variables and their
684 * values (by calling #inspect on each of them). User defined classes
685 * should override this method to provide a better representation of
686 * <i>obj</i>. When overriding this method, it should return a string
687 * whose encoding is compatible with the default external encoding.
689 * [ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]"
690 * Time.new.inspect #=> "2008-03-08 19:43:39 +0900"
694 * Foo.new.inspect #=> "#<Foo:0x0300c868>"
701 * Bar.new.inspect #=> "#<Bar:0x0300c868 @bar=1>"
705 rb_obj_inspect(VALUE obj
)
707 if (rb_ivar_count(obj
) > 0) {
709 VALUE c
= rb_class_name(CLASS_OF(obj
));
711 str
= rb_sprintf("-<%"PRIsVALUE
":%p", c
, (void*)obj
);
712 return rb_exec_recursive(inspect_obj
, obj
, str
);
715 return rb_any_to_s(obj
);
720 class_or_module_required(VALUE c
)
722 switch (OBJ_BUILTIN_TYPE(c
)) {
729 rb_raise(rb_eTypeError
, "class or module required");
734 static VALUE
class_search_ancestor(VALUE cl
, VALUE c
);
738 * obj.instance_of?(class) -> true or false
740 * Returns <code>true</code> if <i>obj</i> is an instance of the given
741 * class. See also Object#kind_of?.
748 * b.instance_of? A #=> false
749 * b.instance_of? B #=> true
750 * b.instance_of? C #=> false
754 rb_obj_is_instance_of(VALUE obj
, VALUE c
)
756 c
= class_or_module_required(c
);
757 return RBOOL(rb_obj_class(obj
) == c
);
763 * obj.is_a?(class) -> true or false
764 * obj.kind_of?(class) -> true or false
766 * Returns <code>true</code> if <i>class</i> is the class of
767 * <i>obj</i>, or if <i>class</i> is one of the superclasses of
768 * <i>obj</i> or modules included in <i>obj</i>.
780 * b.is_a? C #=> false
783 * b.kind_of? A #=> true
784 * b.kind_of? B #=> true
785 * b.kind_of? C #=> false
786 * b.kind_of? M #=> true
790 rb_obj_is_kind_of(VALUE obj
, VALUE c
)
792 VALUE cl
= CLASS_OF(obj
);
794 // Note: YJIT needs this function to never allocate and never raise when
795 // `c` is a class or a module.
796 c
= class_or_module_required(c
);
797 return RBOOL(class_search_ancestor(cl
, RCLASS_ORIGIN(c
)));
801 class_search_ancestor(VALUE cl
, VALUE c
)
804 if (cl
== c
|| RCLASS_M_TBL(cl
) == RCLASS_M_TBL(c
))
806 cl
= RCLASS_SUPER(cl
);
813 rb_class_search_ancestor(VALUE cl
, VALUE c
)
815 cl
= class_or_module_required(cl
);
816 c
= class_or_module_required(c
);
817 return class_search_ancestor(cl
, RCLASS_ORIGIN(c
));
822 * Document-method: inherited
825 * inherited(subclass)
827 * Callback invoked whenever a subclass of the current class is created.
832 * def self.inherited(subclass)
833 * puts "New subclass: #{subclass}"
848 #define rb_obj_class_inherited rb_obj_dummy1
850 /* Document-method: method_added
853 * method_added(method_name)
855 * Invoked as a callback whenever an instance method is added to the
859 * def self.method_added(method_name)
860 * puts "Adding #{method_name.inspect}"
862 * def self.some_class_method() end
863 * def some_instance_method() end
868 * Adding :some_instance_method
871 #define rb_obj_mod_method_added rb_obj_dummy1
873 /* Document-method: method_removed
876 * method_removed(method_name)
878 * Invoked as a callback whenever an instance method is removed from the
882 * def self.method_removed(method_name)
883 * puts "Removing #{method_name.inspect}"
885 * def self.some_class_method() end
886 * def some_instance_method() end
888 * remove_method :some_class_method
890 * remove_method :some_instance_method
895 * Removing :some_instance_method
898 #define rb_obj_mod_method_removed rb_obj_dummy1
900 /* Document-method: method_undefined
903 * method_undefined(method_name)
905 * Invoked as a callback whenever an instance method is undefined from the
909 * def self.method_undefined(method_name)
910 * puts "Undefining #{method_name.inspect}"
912 * def self.some_class_method() end
913 * def some_instance_method() end
915 * undef_method :some_class_method
917 * undef_method :some_instance_method
922 * Undefining :some_instance_method
925 #define rb_obj_mod_method_undefined rb_obj_dummy1
928 * Document-method: singleton_method_added
931 * singleton_method_added(symbol)
933 * Invoked as a callback whenever a singleton method is added to the
937 * def Chatty.singleton_method_added(id)
938 * puts "Adding #{id.id2name}"
942 * def Chatty.three() end
947 * Adding singleton_method_added
952 #define rb_obj_singleton_method_added rb_obj_dummy1
955 * Document-method: singleton_method_removed
958 * singleton_method_removed(symbol)
960 * Invoked as a callback whenever a singleton method is removed from
964 * def Chatty.singleton_method_removed(id)
965 * puts "Removing #{id.id2name}"
969 * def Chatty.three() end
971 * remove_method :three
981 #define rb_obj_singleton_method_removed rb_obj_dummy1
984 * Document-method: singleton_method_undefined
987 * singleton_method_undefined(symbol)
989 * Invoked as a callback whenever a singleton method is undefined in
993 * def Chatty.singleton_method_undefined(id)
994 * puts "Undefining #{id.id2name}"
996 * def Chatty.one() end
1002 * <em>produces:</em>
1006 #define rb_obj_singleton_method_undefined rb_obj_dummy1
1009 * Document-method: extended
1012 * extended(othermod)
1014 * The equivalent of <tt>included</tt>, but for extended modules.
1017 * def self.extended(mod)
1018 * puts "#{self} extended in #{mod}"
1024 * # => prints "A extended in Enumerable"
1026 #define rb_obj_mod_extended rb_obj_dummy1
1029 * Document-method: included
1032 * included(othermod)
1034 * Callback invoked whenever the receiver is included in another
1035 * module or class. This should be used in preference to
1036 * <tt>Module.append_features</tt> if your code wants to perform some
1037 * action when a module is included in another.
1040 * def A.included(mod)
1041 * puts "#{self} included in #{mod}"
1047 * # => prints "A included in Enumerable"
1049 #define rb_obj_mod_included rb_obj_dummy1
1052 * Document-method: prepended
1055 * prepended(othermod)
1057 * The equivalent of <tt>included</tt>, but for prepended modules.
1060 * def self.prepended(mod)
1061 * puts "#{self} prepended to #{mod}"
1067 * # => prints "A prepended to Enumerable"
1069 #define rb_obj_mod_prepended rb_obj_dummy1
1072 * Document-method: initialize
1077 * Returns a new BasicObject.
1079 #define rb_obj_initialize rb_obj_dummy0
1092 rb_obj_dummy0(VALUE _
)
1094 return rb_obj_dummy();
1098 rb_obj_dummy1(VALUE _x
, VALUE _y
)
1100 return rb_obj_dummy();
1105 * obj.tainted? -> false
1107 * Returns false. This method is deprecated and will be removed in Ruby 3.2.
1111 rb_obj_tainted(VALUE obj
)
1113 rb_warn_deprecated_to_remove_at(3.2, "Object#tainted?", NULL
);
1121 * Returns object. This method is deprecated and will be removed in Ruby 3.2.
1125 rb_obj_taint(VALUE obj
)
1127 rb_warn_deprecated_to_remove_at(3.2, "Object#taint", NULL
);
1134 * obj.untaint -> obj
1136 * Returns object. This method is deprecated and will be removed in Ruby 3.2.
1140 rb_obj_untaint(VALUE obj
)
1142 rb_warn_deprecated_to_remove_at(3.2, "Object#untaint", NULL
);
1148 * obj.untrusted? -> false
1150 * Returns false. This method is deprecated and will be removed in Ruby 3.2.
1154 rb_obj_untrusted(VALUE obj
)
1156 rb_warn_deprecated_to_remove_at(3.2, "Object#untrusted?", NULL
);
1162 * obj.untrust -> obj
1164 * Returns object. This method is deprecated and will be removed in Ruby 3.2.
1168 rb_obj_untrust(VALUE obj
)
1170 rb_warn_deprecated_to_remove_at(3.2, "Object#untrust", NULL
);
1179 * Returns object. This method is deprecated and will be removed in Ruby 3.2.
1183 rb_obj_trust(VALUE obj
)
1185 rb_warn_deprecated_to_remove_at(3.2, "Object#trust", NULL
);
1190 rb_obj_infect(VALUE victim
, VALUE carrier
)
1192 rb_warn_deprecated_to_remove_at(3.2, "rb_obj_infect", NULL
);
1199 * Prevents further modifications to <i>obj</i>. A
1200 * FrozenError will be raised if modification is attempted.
1201 * There is no way to unfreeze a frozen object. See also
1204 * This method returns self.
1206 * a = [ "a", "b", "c" ]
1210 * <em>produces:</em>
1212 * prog.rb:3:in `<<': can't modify frozen Array (FrozenError)
1215 * Objects of the following classes are always frozen: Integer,
1220 rb_obj_freeze(VALUE obj
)
1222 if (!OBJ_FROZEN(obj
)) {
1224 if (SPECIAL_CONST_P(obj
)) {
1225 rb_bug("special consts should be frozen.");
1232 rb_obj_frozen_p(VALUE obj
)
1234 return RBOOL(OBJ_FROZEN(obj
));
1239 * Document-class: NilClass
1241 * The class of the singleton object <code>nil</code>.
1248 * Always returns the empty string.
1251 MJIT_FUNC_EXPORTED VALUE
1252 rb_nil_to_s(VALUE obj
)
1254 return rb_cNilClass_to_s
;
1258 * Document-method: to_a
1263 * Always returns an empty array.
1271 return rb_ary_new2(0);
1275 * Document-method: to_h
1280 * Always returns an empty hash.
1288 return rb_hash_new();
1293 * nil.inspect -> "nil"
1295 * Always returns the string "nil".
1299 nil_inspect(VALUE obj
)
1301 return rb_usascii_str_new2("nil");
1306 * nil =~ other -> nil
1308 * Dummy pattern matching -- always returns nil.
1312 nil_match(VALUE obj1
, VALUE obj2
)
1317 /***********************************************************************
1318 * Document-class: TrueClass
1320 * The global value <code>true</code> is the only instance of class
1321 * TrueClass and represents a logically true value in
1322 * boolean expressions. The class provides operators allowing
1323 * <code>true</code> to be used in logical expressions.
1329 * true.to_s -> "true"
1331 * The string representation of <code>true</code> is "true".
1334 MJIT_FUNC_EXPORTED VALUE
1335 rb_true_to_s(VALUE obj
)
1337 return rb_cTrueClass_to_s
;
1343 * true & obj -> true or false
1345 * And---Returns <code>false</code> if <i>obj</i> is
1346 * <code>nil</code> or <code>false</code>, <code>true</code> otherwise.
1350 true_and(VALUE obj
, VALUE obj2
)
1352 return RBOOL(RTEST(obj2
));
1357 * true | obj -> true
1359 * Or---Returns <code>true</code>. As <i>obj</i> is an argument to
1360 * a method call, it is always evaluated; there is no short-circuit
1361 * evaluation in this case.
1364 * true || puts("logical or")
1366 * <em>produces:</em>
1372 true_or(VALUE obj
, VALUE obj2
)
1380 * true ^ obj -> !obj
1382 * Exclusive Or---Returns <code>true</code> if <i>obj</i> is
1383 * <code>nil</code> or <code>false</code>, <code>false</code>
1388 true_xor(VALUE obj
, VALUE obj2
)
1390 return RTEST(obj2
)?Qfalse
:Qtrue
;
1395 * Document-class: FalseClass
1397 * The global value <code>false</code> is the only instance of class
1398 * FalseClass and represents a logically false value in
1399 * boolean expressions. The class provides operators allowing
1400 * <code>false</code> to participate correctly in logical expressions.
1406 * false.to_s -> "false"
1408 * The string representation of <code>false</code> is "false".
1411 MJIT_FUNC_EXPORTED VALUE
1412 rb_false_to_s(VALUE obj
)
1414 return rb_cFalseClass_to_s
;
1419 * false & obj -> false
1420 * nil & obj -> false
1422 * And---Returns <code>false</code>. <i>obj</i> is always
1423 * evaluated as it is the argument to a method call---there is no
1424 * short-circuit evaluation in this case.
1428 false_and(VALUE obj
, VALUE obj2
)
1436 * false | obj -> true or false
1437 * nil | obj -> true or false
1439 * Or---Returns <code>false</code> if <i>obj</i> is
1440 * <code>nil</code> or <code>false</code>; <code>true</code> otherwise.
1443 #define false_or true_and
1447 * false ^ obj -> true or false
1448 * nil ^ obj -> true or false
1450 * Exclusive Or---If <i>obj</i> is <code>nil</code> or
1451 * <code>false</code>, returns <code>false</code>; otherwise, returns
1452 * <code>true</code>.
1456 #define false_xor true_and
1462 * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1473 * obj.nil? -> true or false
1475 * Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
1477 * Object.new.nil? #=> false
1482 MJIT_FUNC_EXPORTED VALUE
1491 * obj =~ other -> nil
1493 * This method is deprecated.
1495 * This is not only useless but also troublesome because it may hide a
1500 rb_obj_match(VALUE obj1
, VALUE obj2
)
1502 if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED
)) {
1503 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED
, "deprecated Object#=~ is called on %"PRIsVALUE
1504 "; it always returns nil", rb_obj_class(obj1
));
1511 * obj !~ other -> true or false
1513 * Returns true if two objects do not match (using the <i>=~</i>
1514 * method), otherwise false.
1518 rb_obj_not_match(VALUE obj1
, VALUE obj2
)
1520 VALUE result
= rb_funcall(obj1
, id_match
, 1, obj2
);
1521 return RTEST(result
) ? Qfalse
: Qtrue
;
1527 * obj <=> other -> 0 or nil
1529 * Returns 0 if +obj+ and +other+ are the same object
1530 * or <code>obj == other</code>, otherwise nil.
1532 * The #<=> is used by various methods to compare objects, for example
1533 * Enumerable#sort, Enumerable#max etc.
1535 * Your implementation of #<=> should return one of the following values: -1, 0,
1536 * 1 or nil. -1 means self is smaller than other. 0 means self is equal to other.
1537 * 1 means self is bigger than other. Nil means the two values could not be
1540 * When you define #<=>, you can include Comparable to gain the
1541 * methods #<=, #<, #==, #>=, #> and #between?.
1544 rb_obj_cmp(VALUE obj1
, VALUE obj2
)
1546 if (rb_equal(obj1
, obj2
))
1551 /***********************************************************************
1553 * Document-class: Module
1555 * A Module is a collection of methods and constants. The
1556 * methods in a module may be instance methods or module methods.
1557 * Instance methods appear as methods in a class when the module is
1558 * included, module methods do not. Conversely, module methods may be
1559 * called without creating an encapsulating object, while instance
1560 * methods may not. (See Module#module_function.)
1562 * In the descriptions that follow, the parameter <i>sym</i> refers
1563 * to a symbol, which is either a quoted string or a
1564 * Symbol (such as <code>:name</code>).
1573 * Mod.class #=> Module
1574 * Mod.constants #=> [:CONST, :PI, :E]
1575 * Mod.instance_methods #=> [:meth]
1581 * mod.to_s -> string
1583 * Returns a string representing this module or class. For basic
1584 * classes and modules, this is the name. For singletons, we
1585 * show information on the thing we're attached to as well.
1588 MJIT_FUNC_EXPORTED VALUE
1589 rb_mod_to_s(VALUE klass
)
1592 VALUE refined_class
, defined_at
;
1594 if (FL_TEST(klass
, FL_SINGLETON
)) {
1595 VALUE s
= rb_usascii_str_new2("#<Class:");
1596 VALUE v
= rb_ivar_get(klass
, id__attached__
);
1598 if (CLASS_OR_MODULE_P(v
)) {
1599 rb_str_append(s
, rb_inspect(v
));
1602 rb_str_append(s
, rb_any_to_s(v
));
1604 rb_str_cat2(s
, ">");
1608 refined_class
= rb_refinement_module_get_refined_class(klass
);
1609 if (!NIL_P(refined_class
)) {
1610 VALUE s
= rb_usascii_str_new2("#<refinement:");
1612 rb_str_concat(s
, rb_inspect(refined_class
));
1613 rb_str_cat2(s
, "@");
1614 CONST_ID(id_defined_at
, "__defined_at__");
1615 defined_at
= rb_attr_get(klass
, id_defined_at
);
1616 rb_str_concat(s
, rb_inspect(defined_at
));
1617 rb_str_cat2(s
, ">");
1620 return rb_class_name(klass
);
1627 * Prevents further modifications to <i>mod</i>.
1629 * This method returns self.
1633 rb_mod_freeze(VALUE mod
)
1636 return rb_obj_freeze(mod
);
1641 * mod === obj -> true or false
1643 * Case Equality---Returns <code>true</code> if <i>obj</i> is an
1644 * instance of <i>mod</i> or an instance of one of <i>mod</i>'s descendants.
1645 * Of limited use for modules, but can be used in <code>case</code> statements
1646 * to classify objects by class.
1650 rb_mod_eqq(VALUE mod
, VALUE arg
)
1652 return rb_obj_is_kind_of(arg
, mod
);
1657 * mod <= other -> true, false, or nil
1659 * Returns true if <i>mod</i> is a subclass of <i>other</i> or
1660 * is the same as <i>other</i>. Returns
1661 * <code>nil</code> if there's no relationship between the two.
1662 * (Think of the relationship in terms of the class definition:
1663 * "class A < B" implies "A < B".)
1667 rb_class_inherited_p(VALUE mod
, VALUE arg
)
1669 if (mod
== arg
) return Qtrue
;
1670 if (!CLASS_OR_MODULE_P(arg
) && !RB_TYPE_P(arg
, T_ICLASS
)) {
1671 rb_raise(rb_eTypeError
, "compared with non class/module");
1673 if (class_search_ancestor(mod
, RCLASS_ORIGIN(arg
))) {
1676 /* not mod < arg; check if mod > arg */
1677 if (class_search_ancestor(arg
, mod
)) {
1685 * mod < other -> true, false, or nil
1687 * Returns true if <i>mod</i> is a subclass of <i>other</i>. Returns
1688 * <code>nil</code> if there's no relationship between the two.
1689 * (Think of the relationship in terms of the class definition:
1690 * "class A < B" implies "A < B".)
1695 rb_mod_lt(VALUE mod
, VALUE arg
)
1697 if (mod
== arg
) return Qfalse
;
1698 return rb_class_inherited_p(mod
, arg
);
1704 * mod >= other -> true, false, or nil
1706 * Returns true if <i>mod</i> is an ancestor of <i>other</i>, or the
1707 * two modules are the same. Returns
1708 * <code>nil</code> if there's no relationship between the two.
1709 * (Think of the relationship in terms of the class definition:
1710 * "class A < B" implies "B > A".)
1715 rb_mod_ge(VALUE mod
, VALUE arg
)
1717 if (!CLASS_OR_MODULE_P(arg
)) {
1718 rb_raise(rb_eTypeError
, "compared with non class/module");
1721 return rb_class_inherited_p(arg
, mod
);
1726 * mod > other -> true, false, or nil
1728 * Returns true if <i>mod</i> is an ancestor of <i>other</i>. Returns
1729 * <code>nil</code> if there's no relationship between the two.
1730 * (Think of the relationship in terms of the class definition:
1731 * "class A < B" implies "B > A".)
1736 rb_mod_gt(VALUE mod
, VALUE arg
)
1738 if (mod
== arg
) return Qfalse
;
1739 return rb_mod_ge(mod
, arg
);
1744 * module <=> other_module -> -1, 0, +1, or nil
1746 * Comparison---Returns -1, 0, +1 or nil depending on whether +module+
1747 * includes +other_module+, they are the same, or if +module+ is included by
1750 * Returns +nil+ if +module+ has no relationship with +other_module+, if
1751 * +other_module+ is not a module, or if the two values are incomparable.
1755 rb_mod_cmp(VALUE mod
, VALUE arg
)
1759 if (mod
== arg
) return INT2FIX(0);
1760 if (!CLASS_OR_MODULE_P(arg
)) {
1764 cmp
= rb_class_inherited_p(mod
, arg
);
1765 if (NIL_P(cmp
)) return Qnil
;
1772 static VALUE
rb_mod_initialize_exec(VALUE module
);
1777 * Module.new {|mod| block } -> mod
1779 * Creates a new anonymous module. If a block is given, it is passed
1780 * the module object, and the block is evaluated in the context of this
1781 * module like #module_eval.
1783 * fred = Module.new do
1792 * a.extend(fred) #=> "my string"
1793 * a.meth1 #=> "hello"
1796 * Assign the module to a constant (name starting uppercase) if you
1797 * want to treat it like a regular module.
1801 rb_mod_initialize(VALUE module
)
1803 rb_module_check_initializable(module
);
1804 return rb_mod_initialize_exec(module
);
1808 rb_mod_initialize_exec(VALUE module
)
1810 if (rb_block_given_p()) {
1811 rb_mod_module_exec(1, &module
, module
);
1818 rb_mod_initialize_clone(int argc
, VALUE
* argv
, VALUE clone
)
1820 VALUE ret
, orig
, opts
;
1821 rb_scan_args(argc
, argv
, "1:", &orig
, &opts
);
1822 ret
= rb_obj_init_clone(argc
, argv
, clone
);
1823 if (OBJ_FROZEN(orig
))
1824 rb_class_name(clone
);
1830 * Class.new(super_class=Object) -> a_class
1831 * Class.new(super_class=Object) { |mod| ... } -> a_class
1833 * Creates a new anonymous (unnamed) class with the given superclass
1834 * (or Object if no parameter is given). You can give a
1835 * class a name by assigning the class object to a constant.
1837 * If a block is given, it is passed the class object, and the block
1838 * is evaluated in the context of this class like
1841 * fred = Class.new do
1850 * a = fred.new #=> #<#<Class:0x100381890>:0x100376b98>
1851 * a.meth1 #=> "hello"
1854 * Assign the class to a constant (name starting uppercase) if you
1855 * want to treat it like a regular class.
1859 rb_class_initialize(int argc
, VALUE
*argv
, VALUE klass
)
1863 if (RCLASS_SUPER(klass
) != 0 || klass
== rb_cBasicObject
) {
1864 rb_raise(rb_eTypeError
, "already initialized class");
1866 if (rb_check_arity(argc
, 0, 1) == 0) {
1871 rb_check_inheritable(super
);
1872 if (super
!= rb_cBasicObject
&& !RCLASS_SUPER(super
)) {
1873 rb_raise(rb_eTypeError
, "can't inherit uninitialized class");
1876 RCLASS_SET_SUPER(klass
, super
);
1877 rb_make_metaclass(klass
, RBASIC(super
)->klass
);
1878 rb_class_inherited(super
, klass
);
1879 rb_mod_initialize_exec(klass
);
1886 rb_undefined_alloc(VALUE klass
)
1888 rb_raise(rb_eTypeError
, "allocator undefined for %"PRIsVALUE
,
1892 static rb_alloc_func_t
class_get_alloc_func(VALUE klass
);
1893 static VALUE
class_call_alloc_func(rb_alloc_func_t allocator
, VALUE klass
);
1897 * class.allocate() -> obj
1899 * Allocates space for a new object of <i>class</i>'s class and does not
1900 * call initialize on the new instance. The returned object must be an
1901 * instance of <i>class</i>.
1903 * klass = Class.new do
1904 * def initialize(*args)
1905 * @initialized = true
1909 * @initialized || false
1913 * klass.allocate.initialized? #=> false
1918 rb_class_alloc_m(VALUE klass
)
1920 rb_alloc_func_t allocator
= class_get_alloc_func(klass
);
1921 if (!rb_obj_respond_to(klass
, rb_intern("allocate"), 1)) {
1922 rb_raise(rb_eTypeError
, "calling %"PRIsVALUE
".allocate is prohibited",
1925 return class_call_alloc_func(allocator
, klass
);
1929 rb_class_alloc(VALUE klass
)
1931 rb_alloc_func_t allocator
= class_get_alloc_func(klass
);
1932 return class_call_alloc_func(allocator
, klass
);
1935 static rb_alloc_func_t
1936 class_get_alloc_func(VALUE klass
)
1938 rb_alloc_func_t allocator
;
1940 if (RCLASS_SUPER(klass
) == 0 && klass
!= rb_cBasicObject
) {
1941 rb_raise(rb_eTypeError
, "can't instantiate uninitialized class");
1943 if (FL_TEST(klass
, FL_SINGLETON
)) {
1944 rb_raise(rb_eTypeError
, "can't create instance of singleton class");
1946 allocator
= rb_get_alloc_func(klass
);
1948 rb_undefined_alloc(klass
);
1954 class_call_alloc_func(rb_alloc_func_t allocator
, VALUE klass
)
1958 RUBY_DTRACE_CREATE_HOOK(OBJECT
, rb_class2name(klass
));
1960 obj
= (*allocator
)(klass
);
1962 if (rb_obj_class(obj
) != rb_class_real(klass
)) {
1963 rb_raise(rb_eTypeError
, "wrong instance allocation");
1969 rb_obj_alloc(VALUE klass
)
1971 Check_Type(klass
, T_CLASS
);
1972 return rb_class_alloc(klass
);
1977 * class.new(args, ...) -> obj
1979 * Calls #allocate to create a new object of <i>class</i>'s class,
1980 * then invokes that object's #initialize method, passing it
1981 * <i>args</i>. This is the method that ends up getting called
1982 * whenever an object is constructed using <code>.new</code>.
1987 rb_class_new_instance_pass_kw(int argc
, const VALUE
*argv
, VALUE klass
)
1991 obj
= rb_class_alloc(klass
);
1992 rb_obj_call_init_kw(obj
, argc
, argv
, RB_PASS_CALLED_KEYWORDS
);
1998 rb_class_new_instance_kw(int argc
, const VALUE
*argv
, VALUE klass
, int kw_splat
)
2001 Check_Type(klass
, T_CLASS
);
2003 obj
= rb_class_alloc(klass
);
2004 rb_obj_call_init_kw(obj
, argc
, argv
, kw_splat
);
2010 rb_class_new_instance(int argc
, const VALUE
*argv
, VALUE klass
)
2013 Check_Type(klass
, T_CLASS
);
2015 obj
= rb_class_alloc(klass
);
2016 rb_obj_call_init_kw(obj
, argc
, argv
, RB_NO_KEYWORDS
);
2023 * class.superclass -> a_super_class or nil
2025 * Returns the superclass of <i>class</i>, or <code>nil</code>.
2027 * File.superclass #=> IO
2028 * IO.superclass #=> Object
2029 * Object.superclass #=> BasicObject
2031 * class Bar < Foo; end
2032 * Bar.superclass #=> Foo
2034 * Returns nil when the given class does not have a parent class:
2036 * BasicObject.superclass #=> nil
2039 * Returns the superclass of \a klass. Equivalent to \c Class\#superclass in Ruby.
2042 * \param[in] klass a Class object
2043 * \return the superclass, or \c Qnil if \a klass does not have a parent class.
2044 * \sa rb_class_get_superclass
2049 rb_class_superclass(VALUE klass
)
2051 VALUE super
= RCLASS_SUPER(klass
);
2054 if (klass
== rb_cBasicObject
) return Qnil
;
2055 rb_raise(rb_eTypeError
, "uninitialized class");
2057 while (RB_TYPE_P(super
, T_ICLASS
)) {
2058 super
= RCLASS_SUPER(super
);
2067 rb_class_get_superclass(VALUE klass
)
2069 return RCLASS(klass
)->super
;
2072 static const char bad_instance_name
[] = "`%1$s' is not allowed as an instance variable name";
2073 static const char bad_class_name
[] = "`%1$s' is not allowed as a class variable name";
2074 static const char bad_const_name
[] = "wrong constant name %1$s";
2075 static const char bad_attr_name
[] = "invalid attribute name `%1$s'";
2076 #define wrong_constant_name bad_const_name
2079 #define id_for_var(obj, name, type) id_for_setter(obj, name, type, bad_##type##_name)
2081 #define id_for_setter(obj, name, type, message) \
2082 check_setter_id(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message))
2084 check_setter_id(VALUE obj
, VALUE
*pname
,
2085 int (*valid_id_p
)(ID
), int (*valid_name_p
)(VALUE
),
2086 const char *message
, size_t message_len
)
2088 ID id
= rb_check_id(pname
);
2089 VALUE name
= *pname
;
2091 if (id
? !valid_id_p(id
) : !valid_name_p(name
)) {
2092 rb_name_err_raise_str(rb_fstring_new(message
, message_len
),
2099 rb_is_attr_name(VALUE name
)
2101 return rb_is_local_name(name
) || rb_is_const_name(name
);
2105 rb_is_attr_id(ID id
)
2107 return rb_is_local_id(id
) || rb_is_const_id(id
);
2111 id_for_attr(VALUE obj
, VALUE name
)
2113 ID id
= id_for_var(obj
, name
, attr
);
2114 if (!id
) id
= rb_intern_str(name
);
2120 * attr_reader(symbol, ...) -> array
2121 * attr(symbol, ...) -> array
2122 * attr_reader(string, ...) -> array
2123 * attr(string, ...) -> array
2125 * Creates instance variables and corresponding methods that return the
2126 * value of each instance variable. Equivalent to calling
2127 * ``<code>attr</code><i>:name</i>'' on each name in turn.
2128 * String arguments are converted to symbols.
2129 * Returns an array of defined method names as symbols.
2133 rb_mod_attr_reader(int argc
, VALUE
*argv
, VALUE klass
)
2136 VALUE names
= rb_ary_new2(argc
);
2138 for (i
=0; i
<argc
; i
++) {
2139 ID id
= id_for_attr(klass
, argv
[i
]);
2140 rb_attr(klass
, id
, TRUE
, FALSE
, TRUE
);
2141 rb_ary_push(names
, ID2SYM(id
));
2148 * attr(name, ...) -> array
2149 * attr(name, true) -> array
2150 * attr(name, false) -> array
2152 * The first form is equivalent to #attr_reader.
2153 * The second form is equivalent to <code>attr_accessor(name)</code> but deprecated.
2154 * The last form is equivalent to <code>attr_reader(name)</code> but deprecated.
2155 * Returns an array of defined method names as symbols.
2158 * \todo can be static?
2162 rb_mod_attr(int argc
, VALUE
*argv
, VALUE klass
)
2164 if (argc
== 2 && (argv
[1] == Qtrue
|| argv
[1] == Qfalse
)) {
2165 ID id
= id_for_attr(klass
, argv
[0]);
2166 VALUE names
= rb_ary_new();
2168 rb_category_warning(RB_WARN_CATEGORY_DEPRECATED
, "optional boolean argument is obsoleted");
2169 rb_attr(klass
, id
, 1, RTEST(argv
[1]), TRUE
);
2170 rb_ary_push(names
, ID2SYM(id
));
2171 if (argv
[1] == Qtrue
) rb_ary_push(names
, ID2SYM(rb_id_attrset(id
)));
2174 return rb_mod_attr_reader(argc
, argv
, klass
);
2179 * attr_writer(symbol, ...) -> array
2180 * attr_writer(string, ...) -> array
2182 * Creates an accessor method to allow assignment to the attribute
2183 * <i>symbol</i><code>.id2name</code>.
2184 * String arguments are converted to symbols.
2185 * Returns an array of defined method names as symbols.
2189 rb_mod_attr_writer(int argc
, VALUE
*argv
, VALUE klass
)
2192 VALUE names
= rb_ary_new2(argc
);
2194 for (i
=0; i
<argc
; i
++) {
2195 ID id
= id_for_attr(klass
, argv
[i
]);
2196 rb_attr(klass
, id
, FALSE
, TRUE
, TRUE
);
2197 rb_ary_push(names
, ID2SYM(rb_id_attrset(id
)));
2204 * attr_accessor(symbol, ...) -> array
2205 * attr_accessor(string, ...) -> array
2207 * Defines a named attribute for this module, where the name is
2208 * <i>symbol.</i><code>id2name</code>, creating an instance variable
2209 * (<code>@name</code>) and a corresponding access method to read it.
2210 * Also creates a method called <code>name=</code> to set the attribute.
2211 * String arguments are converted to symbols.
2212 * Returns an array of defined method names as symbols.
2215 * attr_accessor(:one, :two) #=> [:one, :one=, :two, :two=]
2217 * Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
2221 rb_mod_attr_accessor(int argc
, VALUE
*argv
, VALUE klass
)
2224 VALUE names
= rb_ary_new2(argc
* 2);
2226 for (i
=0; i
<argc
; i
++) {
2227 ID id
= id_for_attr(klass
, argv
[i
]);
2229 rb_attr(klass
, id
, TRUE
, TRUE
, TRUE
);
2230 rb_ary_push(names
, ID2SYM(id
));
2231 rb_ary_push(names
, ID2SYM(rb_id_attrset(id
)));
2238 * mod.const_get(sym, inherit=true) -> obj
2239 * mod.const_get(str, inherit=true) -> obj
2241 * Checks for a constant with the given name in <i>mod</i>.
2242 * If +inherit+ is set, the lookup will also search
2243 * the ancestors (and +Object+ if <i>mod</i> is a +Module+).
2245 * The value of the constant is returned if a definition is found,
2246 * otherwise a +NameError+ is raised.
2248 * Math.const_get(:PI) #=> 3.14159265358979
2250 * This method will recursively look up constant names if a namespaced
2251 * class name is provided. For example:
2253 * module Foo; class Bar; end end
2254 * Object.const_get 'Foo::Bar'
2256 * The +inherit+ flag is respected on each lookup. For example:
2263 * class Baz < Bar; end
2266 * Object.const_get 'Foo::Baz::VAL' # => 10
2267 * Object.const_get 'Foo::Baz::VAL', false # => NameError
2269 * If the argument is not a valid constant name a +NameError+ will be
2270 * raised with a warning "wrong constant name".
2272 * Object.const_get 'foobar' #=> NameError: wrong constant name foobar
2277 rb_mod_const_get(int argc
, VALUE
*argv
, VALUE mod
)
2281 const char *pbeg
, *p
, *path
, *pend
;
2284 rb_check_arity(argc
, 1, 2);
2286 recur
= (argc
== 1) ? Qtrue
: argv
[1];
2288 if (SYMBOL_P(name
)) {
2289 if (!rb_is_const_sym(name
)) goto wrong_name
;
2290 id
= rb_check_id(&name
);
2291 if (!id
) return rb_const_missing(mod
, name
);
2292 return RTEST(recur
) ? rb_const_get(mod
, id
) : rb_const_get_at(mod
, id
);
2295 path
= StringValuePtr(name
);
2296 enc
= rb_enc_get(name
);
2298 if (!rb_enc_asciicompat(enc
)) {
2299 rb_raise(rb_eArgError
, "invalid class path encoding (non ASCII)");
2303 pend
= path
+ RSTRING_LEN(name
);
2305 if (p
>= pend
|| !*p
) {
2309 if (p
+ 2 < pend
&& p
[0] == ':' && p
[1] == ':') {
2319 while (p
< pend
&& *p
!= ':') p
++;
2321 if (pbeg
== p
) goto wrong_name
;
2323 id
= rb_check_id_cstr(pbeg
, len
= p
-pbeg
, enc
);
2326 if (p
< pend
&& p
[0] == ':') {
2327 if (p
+ 2 >= pend
|| p
[1] != ':') goto wrong_name
;
2332 if (!RB_TYPE_P(mod
, T_MODULE
) && !RB_TYPE_P(mod
, T_CLASS
)) {
2333 rb_raise(rb_eTypeError
, "%"PRIsVALUE
" does not refer to class/module",
2338 part
= rb_str_subseq(name
, beglen
, len
);
2340 if (!rb_is_const_name(part
)) {
2344 else if (!rb_method_basic_definition_p(CLASS_OF(mod
), id_const_missing
)) {
2345 part
= rb_str_intern(part
);
2346 mod
= rb_const_missing(mod
, part
);
2350 rb_mod_const_missing(mod
, part
);
2353 if (!rb_is_const_id(id
)) {
2358 mod
= rb_const_get_0(mod
, id
, beglen
> 0 || !RTEST(recur
), RTEST(recur
), FALSE
);
2360 if (!RTEST(recur
)) {
2361 mod
= rb_const_get_at(mod
, id
);
2363 else if (beglen
== 0) {
2364 mod
= rb_const_get(mod
, id
);
2367 mod
= rb_const_get_from(mod
, id
);
2375 rb_name_err_raise(wrong_constant_name
, mod
, name
);
2376 UNREACHABLE_RETURN(Qundef
);
2381 * mod.const_set(sym, obj) -> obj
2382 * mod.const_set(str, obj) -> obj
2384 * Sets the named constant to the given object, returning that object.
2385 * Creates a new constant if no constant with the given name previously
2388 * Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714
2389 * Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968
2391 * If +sym+ or +str+ is not a valid constant name a +NameError+ will be
2392 * raised with a warning "wrong constant name".
2394 * Object.const_set('foobar', 42) #=> NameError: wrong constant name foobar
2399 rb_mod_const_set(VALUE mod
, VALUE name
, VALUE value
)
2401 ID id
= id_for_var(mod
, name
, const);
2402 if (!id
) id
= rb_intern_str(name
);
2403 rb_const_set(mod
, id
, value
);
2410 * mod.const_defined?(sym, inherit=true) -> true or false
2411 * mod.const_defined?(str, inherit=true) -> true or false
2413 * Says whether _mod_ or its ancestors have a constant with the given name:
2415 * Float.const_defined?(:EPSILON) #=> true, found in Float itself
2416 * Float.const_defined?("String") #=> true, found in Object (ancestor)
2417 * BasicObject.const_defined?(:Hash) #=> false
2419 * If _mod_ is a +Module+, additionally +Object+ and its ancestors are checked:
2421 * Math.const_defined?(:String) #=> true, found in Object
2423 * In each of the checked classes or modules, if the constant is not present
2424 * but there is an autoload for it, +true+ is returned directly without
2428 * autoload :User, 'admin/user'
2430 * Admin.const_defined?(:User) #=> true
2432 * If the constant is not found the callback +const_missing+ is *not* called
2433 * and the method returns +false+.
2435 * If +inherit+ is false, the lookup only checks the constants in the receiver:
2437 * IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor)
2438 * IO.const_defined?(:SYNC, false) #=> false, not found in IO itself
2440 * In this case, the same logic for autoloading applies.
2442 * If the argument is not a valid constant name a +NameError+ is raised with the
2443 * message "wrong constant name _name_":
2445 * Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar
2450 rb_mod_const_defined(int argc
, VALUE
*argv
, VALUE mod
)
2454 const char *pbeg
, *p
, *path
, *pend
;
2457 rb_check_arity(argc
, 1, 2);
2459 recur
= (argc
== 1) ? Qtrue
: argv
[1];
2461 if (SYMBOL_P(name
)) {
2462 if (!rb_is_const_sym(name
)) goto wrong_name
;
2463 id
= rb_check_id(&name
);
2464 if (!id
) return Qfalse
;
2465 return RTEST(recur
) ? rb_const_defined(mod
, id
) : rb_const_defined_at(mod
, id
);
2468 path
= StringValuePtr(name
);
2469 enc
= rb_enc_get(name
);
2471 if (!rb_enc_asciicompat(enc
)) {
2472 rb_raise(rb_eArgError
, "invalid class path encoding (non ASCII)");
2476 pend
= path
+ RSTRING_LEN(name
);
2478 if (p
>= pend
|| !*p
) {
2482 if (p
+ 2 < pend
&& p
[0] == ':' && p
[1] == ':') {
2492 while (p
< pend
&& *p
!= ':') p
++;
2494 if (pbeg
== p
) goto wrong_name
;
2496 id
= rb_check_id_cstr(pbeg
, len
= p
-pbeg
, enc
);
2499 if (p
< pend
&& p
[0] == ':') {
2500 if (p
+ 2 >= pend
|| p
[1] != ':') goto wrong_name
;
2506 part
= rb_str_subseq(name
, beglen
, len
);
2508 if (!rb_is_const_name(part
)) {
2516 if (!rb_is_const_id(id
)) {
2522 mod
= rb_const_search(mod
, id
, beglen
> 0 || !RTEST(recur
), RTEST(recur
), FALSE
);
2523 if (mod
== Qundef
) return Qfalse
;
2525 if (!RTEST(recur
)) {
2526 if (!rb_const_defined_at(mod
, id
))
2528 if (p
== pend
) return Qtrue
;
2529 mod
= rb_const_get_at(mod
, id
);
2531 else if (beglen
== 0) {
2532 if (!rb_const_defined(mod
, id
))
2534 if (p
== pend
) return Qtrue
;
2535 mod
= rb_const_get(mod
, id
);
2538 if (!rb_const_defined_from(mod
, id
))
2540 if (p
== pend
) return Qtrue
;
2541 mod
= rb_const_get_from(mod
, id
);
2545 if (p
< pend
&& !RB_TYPE_P(mod
, T_MODULE
) && !RB_TYPE_P(mod
, T_CLASS
)) {
2546 rb_raise(rb_eTypeError
, "%"PRIsVALUE
" does not refer to class/module",
2554 rb_name_err_raise(wrong_constant_name
, mod
, name
);
2555 UNREACHABLE_RETURN(Qundef
);
2560 * mod.const_source_location(sym, inherit=true) -> [String, Integer]
2561 * mod.const_source_location(str, inherit=true) -> [String, Integer]
2563 * Returns the Ruby source filename and line number containing the definition
2564 * of the constant specified. If the named constant is not found, +nil+ is returned.
2565 * If the constant is found, but its source location can not be extracted
2566 * (constant is defined in C code), empty array is returned.
2568 * _inherit_ specifies whether to lookup in <code>mod.ancestors</code> (+true+
2581 * class B < A # line 10
2586 * class A # continuation of A definition
2587 * C2 = 8 # constant redefinition; warned yet allowed
2590 * p B.const_source_location('C4') # => ["test.rb", 12]
2591 * p B.const_source_location('C3') # => ["test.rb", 7]
2592 * p B.const_source_location('C1') # => ["test.rb", 2]
2594 * p B.const_source_location('C3', false) # => nil -- don't lookup in ancestors
2596 * p A.const_source_location('C2') # => ["test.rb", 16] -- actual (last) definition place
2598 * p Object.const_source_location('B') # => ["test.rb", 10] -- top-level constant could be looked through Object
2599 * p Object.const_source_location('A') # => ["test.rb", 1] -- class reopening is NOT considered new definition
2601 * p B.const_source_location('A') # => ["test.rb", 1] -- because Object is in ancestors
2602 * p M.const_source_location('A') # => ["test.rb", 1] -- Object is not ancestor, but additionally checked for modules
2604 * p Object.const_source_location('A::C1') # => ["test.rb", 2] -- nesting is supported
2605 * p Object.const_source_location('String') # => [] -- constant is defined in C code
2610 rb_mod_const_source_location(int argc
, VALUE
*argv
, VALUE mod
)
2612 VALUE name
, recur
, loc
= Qnil
;
2614 const char *pbeg
, *p
, *path
, *pend
;
2617 rb_check_arity(argc
, 1, 2);
2619 recur
= (argc
== 1) ? Qtrue
: argv
[1];
2621 if (SYMBOL_P(name
)) {
2622 if (!rb_is_const_sym(name
)) goto wrong_name
;
2623 id
= rb_check_id(&name
);
2624 if (!id
) return Qnil
;
2625 return RTEST(recur
) ? rb_const_source_location(mod
, id
) : rb_const_source_location_at(mod
, id
);
2628 path
= StringValuePtr(name
);
2629 enc
= rb_enc_get(name
);
2631 if (!rb_enc_asciicompat(enc
)) {
2632 rb_raise(rb_eArgError
, "invalid class path encoding (non ASCII)");
2636 pend
= path
+ RSTRING_LEN(name
);
2638 if (p
>= pend
|| !*p
) {
2642 if (p
+ 2 < pend
&& p
[0] == ':' && p
[1] == ':') {
2652 while (p
< pend
&& *p
!= ':') p
++;
2654 if (pbeg
== p
) goto wrong_name
;
2656 id
= rb_check_id_cstr(pbeg
, len
= p
-pbeg
, enc
);
2659 if (p
< pend
&& p
[0] == ':') {
2660 if (p
+ 2 >= pend
|| p
[1] != ':') goto wrong_name
;
2666 part
= rb_str_subseq(name
, beglen
, len
);
2668 if (!rb_is_const_name(part
)) {
2676 if (!rb_is_const_id(id
)) {
2682 mod
= rb_const_get(mod
, id
);
2685 mod
= rb_const_get_at(mod
, id
);
2687 if (!RB_TYPE_P(mod
, T_MODULE
) && !RB_TYPE_P(mod
, T_CLASS
)) {
2688 rb_raise(rb_eTypeError
, "%"PRIsVALUE
" does not refer to class/module",
2694 loc
= rb_const_source_location(mod
, id
);
2697 loc
= rb_const_source_location_at(mod
, id
);
2707 rb_name_err_raise(wrong_constant_name
, mod
, name
);
2708 UNREACHABLE_RETURN(Qundef
);
2713 * obj.instance_variable_get(symbol) -> obj
2714 * obj.instance_variable_get(string) -> obj
2716 * Returns the value of the given instance variable, or nil if the
2717 * instance variable is not set. The <code>@</code> part of the
2718 * variable name should be included for regular instance
2719 * variables. Throws a NameError exception if the
2720 * supplied symbol is not valid as an instance variable name.
2721 * String arguments are converted to symbols.
2724 * def initialize(p1, p2)
2728 * fred = Fred.new('cat', 99)
2729 * fred.instance_variable_get(:@a) #=> "cat"
2730 * fred.instance_variable_get("@b") #=> 99
2734 rb_obj_ivar_get(VALUE obj
, VALUE iv
)
2736 ID id
= id_for_var(obj
, iv
, instance
);
2741 return rb_ivar_get(obj
, id
);
2746 * obj.instance_variable_set(symbol, obj) -> obj
2747 * obj.instance_variable_set(string, obj) -> obj
2749 * Sets the instance variable named by <i>symbol</i> to the given
2750 * object. This may circumvent the encapsulation intended by
2751 * the author of the class, so it should be used with care.
2752 * The variable does not have to exist prior to this call.
2753 * If the instance variable name is passed as a string, that string
2754 * is converted to a symbol.
2757 * def initialize(p1, p2)
2761 * fred = Fred.new('cat', 99)
2762 * fred.instance_variable_set(:@a, 'dog') #=> "dog"
2763 * fred.instance_variable_set(:@c, 'cat') #=> "cat"
2764 * fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
2768 rb_obj_ivar_set(VALUE obj
, VALUE iv
, VALUE val
)
2770 ID id
= id_for_var(obj
, iv
, instance
);
2771 if (!id
) id
= rb_intern_str(iv
);
2772 return rb_ivar_set(obj
, id
, val
);
2777 * obj.instance_variable_defined?(symbol) -> true or false
2778 * obj.instance_variable_defined?(string) -> true or false
2780 * Returns <code>true</code> if the given instance variable is
2781 * defined in <i>obj</i>.
2782 * String arguments are converted to symbols.
2785 * def initialize(p1, p2)
2789 * fred = Fred.new('cat', 99)
2790 * fred.instance_variable_defined?(:@a) #=> true
2791 * fred.instance_variable_defined?("@b") #=> true
2792 * fred.instance_variable_defined?("@c") #=> false
2796 rb_obj_ivar_defined(VALUE obj
, VALUE iv
)
2798 ID id
= id_for_var(obj
, iv
, instance
);
2803 return rb_ivar_defined(obj
, id
);
2808 * mod.class_variable_get(symbol) -> obj
2809 * mod.class_variable_get(string) -> obj
2811 * Returns the value of the given class variable (or throws a
2812 * NameError exception). The <code>@@</code> part of the
2813 * variable name should be included for regular class variables.
2814 * String arguments are converted to symbols.
2819 * Fred.class_variable_get(:@@foo) #=> 99
2823 rb_mod_cvar_get(VALUE obj
, VALUE iv
)
2825 ID id
= id_for_var(obj
, iv
, class);
2828 rb_name_err_raise("uninitialized class variable %1$s in %2$s",
2831 return rb_cvar_get(obj
, id
);
2836 * obj.class_variable_set(symbol, obj) -> obj
2837 * obj.class_variable_set(string, obj) -> obj
2839 * Sets the class variable named by <i>symbol</i> to the given
2841 * If the class variable name is passed as a string, that string
2842 * is converted to a symbol.
2850 * Fred.class_variable_set(:@@foo, 101) #=> 101
2851 * Fred.new.foo #=> 101
2855 rb_mod_cvar_set(VALUE obj
, VALUE iv
, VALUE val
)
2857 ID id
= id_for_var(obj
, iv
, class);
2858 if (!id
) id
= rb_intern_str(iv
);
2859 rb_cvar_set(obj
, id
, val
);
2865 * obj.class_variable_defined?(symbol) -> true or false
2866 * obj.class_variable_defined?(string) -> true or false
2868 * Returns <code>true</code> if the given class variable is defined
2870 * String arguments are converted to symbols.
2875 * Fred.class_variable_defined?(:@@foo) #=> true
2876 * Fred.class_variable_defined?(:@@bar) #=> false
2880 rb_mod_cvar_defined(VALUE obj
, VALUE iv
)
2882 ID id
= id_for_var(obj
, iv
, class);
2887 return rb_cvar_defined(obj
, id
);
2892 * mod.singleton_class? -> true or false
2894 * Returns <code>true</code> if <i>mod</i> is a singleton class or
2895 * <code>false</code> if it is an ordinary class or module.
2899 * C.singleton_class? #=> false
2900 * C.singleton_class.singleton_class? #=> true
2904 rb_mod_singleton_p(VALUE klass
)
2906 return RBOOL(RB_TYPE_P(klass
, T_CLASS
) && FL_TEST(klass
, FL_SINGLETON
));
2910 static const struct conv_method_tbl
{
2911 const char method
[6];
2913 } conv_method_names
[] = {
2914 #define M(n) {#n, (unsigned short)idTo_##n}
2929 #define IMPLICIT_CONVERSIONS 7
2932 conv_method_index(const char *method
)
2934 static const char prefix
[] = "to_";
2936 if (strncmp(prefix
, method
, sizeof(prefix
)-1) == 0) {
2937 const char *const meth
= &method
[sizeof(prefix
)-1];
2939 for (i
=0; i
< numberof(conv_method_names
); i
++) {
2940 if (conv_method_names
[i
].method
[0] == meth
[0] &&
2941 strcmp(conv_method_names
[i
].method
, meth
) == 0) {
2946 return numberof(conv_method_names
);
2950 convert_type_with_id(VALUE val
, const char *tname
, ID method
, int raise
, int index
)
2952 VALUE r
= rb_check_funcall(val
, method
, 0, 0);
2956 ((index
< 0 ? conv_method_index(rb_id2name(method
)) : index
)
2957 < IMPLICIT_CONVERSIONS
) ?
2958 "no implicit conversion of" : "can't convert";
2959 const char *cname
= NIL_P(val
) ? "nil" :
2960 val
== Qtrue
? "true" :
2961 val
== Qfalse
? "false" :
2964 rb_raise(rb_eTypeError
, "%s %s into %s", msg
, cname
, tname
);
2965 rb_raise(rb_eTypeError
, "%s %"PRIsVALUE
" into %s", msg
,
2975 convert_type(VALUE val
, const char *tname
, const char *method
, int raise
)
2977 int i
= conv_method_index(method
);
2978 ID m
= i
< numberof(conv_method_names
) ?
2979 conv_method_names
[i
].id
: rb_intern(method
);
2980 return convert_type_with_id(val
, tname
, m
, raise
, i
);
2984 NORETURN(static void conversion_mismatch(VALUE
, const char *, const char *, VALUE
));
2986 conversion_mismatch(VALUE val
, const char *tname
, const char *method
, VALUE result
)
2988 VALUE cname
= rb_obj_class(val
);
2989 rb_raise(rb_eTypeError
,
2990 "can't convert %"PRIsVALUE
" to %s (%"PRIsVALUE
"#%s gives %"PRIsVALUE
")",
2991 cname
, tname
, cname
, method
, rb_obj_class(result
));
2995 rb_convert_type(VALUE val
, int type
, const char *tname
, const char *method
)
2999 if (TYPE(val
) == type
) return val
;
3000 v
= convert_type(val
, tname
, method
, TRUE
);
3001 if (TYPE(v
) != type
) {
3002 conversion_mismatch(val
, tname
, method
, v
);
3009 rb_convert_type_with_id(VALUE val
, int type
, const char *tname
, ID method
)
3013 if (TYPE(val
) == type
) return val
;
3014 v
= convert_type_with_id(val
, tname
, method
, TRUE
, -1);
3015 if (TYPE(v
) != type
) {
3016 conversion_mismatch(val
, tname
, RSTRING_PTR(rb_id2str(method
)), v
);
3022 rb_check_convert_type(VALUE val
, int type
, const char *tname
, const char *method
)
3026 /* always convert T_DATA */
3027 if (TYPE(val
) == type
&& type
!= T_DATA
) return val
;
3028 v
= convert_type(val
, tname
, method
, FALSE
);
3029 if (NIL_P(v
)) return Qnil
;
3030 if (TYPE(v
) != type
) {
3031 conversion_mismatch(val
, tname
, method
, v
);
3037 MJIT_FUNC_EXPORTED VALUE
3038 rb_check_convert_type_with_id(VALUE val
, int type
, const char *tname
, ID method
)
3042 /* always convert T_DATA */
3043 if (TYPE(val
) == type
&& type
!= T_DATA
) return val
;
3044 v
= convert_type_with_id(val
, tname
, method
, FALSE
, -1);
3045 if (NIL_P(v
)) return Qnil
;
3046 if (TYPE(v
) != type
) {
3047 conversion_mismatch(val
, tname
, RSTRING_PTR(rb_id2str(method
)), v
);
3052 #define try_to_int(val, mid, raise) \
3053 convert_type_with_id(val, "Integer", mid, raise, -1)
3055 ALWAYS_INLINE(static VALUE
rb_to_integer_with_id_exception(VALUE val
, const char *method
, ID mid
, int raise
));
3056 /* Integer specific rb_check_convert_type_with_id */
3058 rb_to_integer_with_id_exception(VALUE val
, const char *method
, ID mid
, int raise
)
3062 if (RB_INTEGER_TYPE_P(val
)) return val
;
3063 v
= try_to_int(val
, mid
, raise
);
3064 if (!raise
&& NIL_P(v
)) return Qnil
;
3065 if (!RB_INTEGER_TYPE_P(v
)) {
3066 conversion_mismatch(val
, "Integer", method
, v
);
3070 #define rb_to_integer(val, method, mid) \
3071 rb_to_integer_with_id_exception(val, method, mid, TRUE)
3074 rb_check_to_integer(VALUE val
, const char *method
)
3078 if (RB_INTEGER_TYPE_P(val
)) return val
;
3079 v
= convert_type(val
, "Integer", method
, FALSE
);
3080 if (!RB_INTEGER_TYPE_P(v
)) {
3087 rb_to_int(VALUE val
)
3089 return rb_to_integer(val
, "to_int", idTo_int
);
3093 rb_check_to_int(VALUE val
)
3095 if (RB_INTEGER_TYPE_P(val
)) return val
;
3096 val
= try_to_int(val
, idTo_int
, FALSE
);
3097 if (RB_INTEGER_TYPE_P(val
)) return val
;
3102 rb_check_to_i(VALUE val
)
3104 if (RB_INTEGER_TYPE_P(val
)) return val
;
3105 val
= try_to_int(val
, idTo_i
, FALSE
);
3106 if (RB_INTEGER_TYPE_P(val
)) return val
;
3111 rb_convert_to_integer(VALUE val
, int base
, int raise_exception
)
3116 tmp
= rb_check_string_type(val
);
3121 else if (! raise_exception
) {
3125 rb_raise(rb_eArgError
, "base specified for non string value");
3128 if (RB_FLOAT_TYPE_P(val
)) {
3129 double f
= RFLOAT_VALUE(val
);
3130 if (!raise_exception
&& !isfinite(f
)) return Qnil
;
3131 if (FIXABLE(f
)) return LONG2FIX((long)f
);
3132 return rb_dbl2big(f
);
3134 else if (RB_INTEGER_TYPE_P(val
)) {
3137 else if (RB_TYPE_P(val
, T_STRING
)) {
3138 return rb_str_convert_to_inum(val
, base
, TRUE
, raise_exception
);
3140 else if (NIL_P(val
)) {
3141 if (!raise_exception
) return Qnil
;
3142 rb_raise(rb_eTypeError
, "can't convert nil into Integer");
3145 tmp
= rb_protect(rb_check_to_int
, val
, NULL
);
3146 if (RB_INTEGER_TYPE_P(tmp
)) return tmp
;
3147 rb_set_errinfo(Qnil
);
3149 if (!raise_exception
) {
3150 VALUE result
= rb_protect(rb_check_to_i
, val
, NULL
);
3151 rb_set_errinfo(Qnil
);
3155 return rb_to_integer(val
, "to_i", idTo_i
);
3159 rb_Integer(VALUE val
)
3161 return rb_convert_to_integer(val
, 0, TRUE
);
3165 rb_check_integer_type(VALUE val
)
3167 return rb_to_integer_with_id_exception(val
, "to_int", idTo_int
, FALSE
);
3171 rb_bool_expected(VALUE obj
, const char *flagname
)
3174 case Qtrue
: case Qfalse
:
3177 rb_raise(rb_eArgError
, "expected true or false as %s: %+"PRIsVALUE
,
3180 return obj
!= Qfalse
;
3184 rb_opts_exception_p(VALUE opts
, int default_value
)
3186 static const ID kwds
[1] = {idException
};
3188 if (rb_get_kwargs(opts
, kwds
, 0, 1, &exception
))
3189 return rb_bool_expected(exception
, "exception");
3190 return default_value
;
3193 #define opts_exception_p(opts) rb_opts_exception_p((opts), TRUE)
3197 * Integer(arg, base=0, exception: true) -> integer or nil
3199 * Converts <i>arg</i> to an Integer.
3200 * Numeric types are converted directly (with floating point numbers
3201 * being truncated). <i>base</i> (0, or between 2 and 36) is a base for
3202 * integer string representation. If <i>arg</i> is a String,
3203 * when <i>base</i> is omitted or equals zero, radix indicators
3204 * (<code>0</code>, <code>0b</code>, and <code>0x</code>) are honored.
3205 * In any case, strings should consist only of one or more digits, except
3206 * for that a sign, one underscore between two digits, and leading/trailing
3207 * spaces are optional. This behavior is different from that of
3208 * String#to_i. Non string values will be converted by first
3209 * trying <code>to_int</code>, then <code>to_i</code>.
3211 * Passing <code>nil</code> raises a TypeError, while passing a String that
3212 * does not conform with numeric representation raises an ArgumentError.
3213 * This behavior can be altered by passing <code>exception: false</code>,
3214 * in this case a not convertible value will return <code>nil</code>.
3216 * Integer(123.999) #=> 123
3217 * Integer("0x1a") #=> 26
3218 * Integer(Time.new) #=> 1204973019
3219 * Integer("0930", 10) #=> 930
3220 * Integer("111", 2) #=> 7
3221 * Integer(" +1_0 ") #=> 10
3222 * Integer(nil) #=> TypeError: can't convert nil into Integer
3223 * Integer("x") #=> ArgumentError: invalid value for Integer(): "x"
3225 * Integer("x", exception: false) #=> nil
3230 rb_f_integer(int argc
, VALUE
*argv
, VALUE obj
)
3232 VALUE arg
= Qnil
, opts
= Qnil
;
3237 VALUE vbase
= rb_check_to_int(argv
[1]);
3238 if (!NIL_P(vbase
)) {
3239 base
= NUM2INT(vbase
);
3243 VALUE hash
= rb_check_hash_type(argv
[argc
-1]);
3245 opts
= rb_extract_keywords(&hash
);
3250 rb_check_arity(argc
, 1, 2);
3253 return rb_convert_to_integer(arg
, base
, opts_exception_p(opts
));
3257 rb_cstr_to_dbl_raise(const char *p
, int badcheck
, int raise
, int *error
)
3262 const char *ellipsis
= "";
3264 enum {max_width
= 20};
3265 #define OutOfRange() ((end - p > max_width) ? \
3266 (w = max_width, ellipsis = "...") : \
3267 (w = (int)(end - p), ellipsis = ""))
3271 while (ISSPACE(*p
)) p
++;
3273 if (!badcheck
&& p
[0] == '0' && (p
[1] == 'x' || p
[1] == 'X')) {
3277 d
= strtod(p
, &end
);
3278 if (errno
== ERANGE
) {
3280 rb_warning("Float %.*s%s out of range", w
, p
, ellipsis
);
3290 char buf
[DBL_DIG
* 4 + 10];
3292 char *const init_e
= buf
+ DBL_DIG
* 4;
3295 int dot_seen
= FALSE
;
3297 switch (*p
) {case '+': case '-': prev
= *n
++ = *p
++;}
3300 while (*++p
== '0');
3302 while (p
< end
&& n
< e
) prev
= *n
++ = *p
++;
3305 /* remove an underscore between digits */
3306 if (n
== buf
|| !ISDIGIT(prev
) || (++p
, !ISDIGIT(*p
))) {
3307 if (badcheck
) goto bad
;
3312 if (e
== init_e
&& (prev
== 'e' || prev
== 'E' || prev
== 'p' || prev
== 'P')) {
3313 e
= buf
+ sizeof(buf
) - 1;
3315 switch (*p
) {case '+': case '-': prev
= *n
++ = *p
++;}
3318 while (*++p
== '0');
3322 else if (ISSPACE(prev
)) {
3323 while (ISSPACE(*p
)) ++p
;
3325 if (badcheck
) goto bad
;
3329 else if (prev
== '.' ? dot_seen
++ : !ISDIGIT(prev
)) {
3330 if (badcheck
) goto bad
;
3333 if (n
< e
) *n
++ = prev
;
3338 if (!badcheck
&& p
[0] == '0' && (p
[1] == 'x' || p
[1] == 'X')) {
3342 d
= strtod(p
, &end
);
3343 if (errno
== ERANGE
) {
3345 rb_warning("Float %.*s%s out of range", w
, p
, ellipsis
);
3349 if (!end
|| p
== end
) goto bad
;
3350 while (*end
&& ISSPACE(*end
)) end
++;
3354 if (errno
== ERANGE
) {
3357 rb_raise(rb_eArgError
, "Float %.*s%s out of range", w
, q
, ellipsis
);
3363 rb_invalid_str(q
, "Float()");
3364 UNREACHABLE_RETURN(nan(""));
3367 if (error
) *error
= 1;
3373 rb_cstr_to_dbl(const char *p
, int badcheck
)
3375 return rb_cstr_to_dbl_raise(p
, badcheck
, TRUE
, NULL
);
3379 rb_str_to_dbl_raise(VALUE str
, int badcheck
, int raise
, int *error
)
3387 s
= RSTRING_PTR(str
);
3388 len
= RSTRING_LEN(str
);
3390 if (badcheck
&& memchr(s
, '\0', len
)) {
3392 rb_raise(rb_eArgError
, "string for Float contains null byte");
3394 if (error
) *error
= 1;
3398 if (s
[len
]) { /* no sentinel somehow */
3399 char *p
= ALLOCV(v
, (size_t)len
+ 1);
3400 MEMCPY(p
, s
, char, len
);
3405 ret
= rb_cstr_to_dbl_raise(s
, badcheck
, raise
, error
);
3411 FUNC_MINIMIZED(double rb_str_to_dbl(VALUE str
, int badcheck
));
3414 rb_str_to_dbl(VALUE str
, int badcheck
)
3416 return rb_str_to_dbl_raise(str
, badcheck
, TRUE
, NULL
);
3419 /*! \cond INTERNAL_MACRO */
3420 #define fix2dbl_without_to_f(x) (double)FIX2LONG(x)
3421 #define big2dbl_without_to_f(x) rb_big2dbl(x)
3422 #define int2dbl_without_to_f(x) \
3423 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : big2dbl_without_to_f(x))
3424 #define num2dbl_without_to_f(x) \
3425 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : \
3426 RB_BIGNUM_TYPE_P(x) ? big2dbl_without_to_f(x) : \
3427 (Check_Type(x, T_FLOAT), RFLOAT_VALUE(x)))
3428 static inline double
3429 rat2dbl_without_to_f(VALUE x
)
3431 VALUE num
= rb_rational_num(x
);
3432 VALUE den
= rb_rational_den(x
);
3433 return num2dbl_without_to_f(num
) / num2dbl_without_to_f(den
);
3436 #define special_const_to_float(val, pre, post) \
3439 rb_raise_static(rb_eTypeError, pre "nil" post); \
3441 rb_raise_static(rb_eTypeError, pre "true" post); \
3443 rb_raise_static(rb_eTypeError, pre "false" post); \
3448 conversion_to_float(VALUE val
)
3450 special_const_to_float(val
, "can't convert ", " into Float");
3454 implicit_conversion_to_float(VALUE val
)
3456 special_const_to_float(val
, "no implicit conversion to float from ", "");
3460 to_float(VALUE
*valp
, int raise_exception
)
3463 if (SPECIAL_CONST_P(val
)) {
3464 if (FIXNUM_P(val
)) {
3465 *valp
= DBL2NUM(fix2dbl_without_to_f(val
));
3468 else if (FLONUM_P(val
)) {
3471 else if (raise_exception
) {
3472 conversion_to_float(val
);
3476 int type
= BUILTIN_TYPE(val
);
3481 *valp
= DBL2NUM(big2dbl_without_to_f(val
));
3484 *valp
= DBL2NUM(rat2dbl_without_to_f(val
));
3494 convert_type_to_float_protected(VALUE val
)
3496 return rb_convert_type_with_id(val
, T_FLOAT
, "Float", id_to_f
);
3500 rb_convert_to_float(VALUE val
, int raise_exception
)
3502 switch (to_float(&val
, raise_exception
)) {
3506 if (!raise_exception
) {
3508 double x
= rb_str_to_dbl_raise(val
, TRUE
, raise_exception
, &e
);
3509 return e
? Qnil
: DBL2NUM(x
);
3511 return DBL2NUM(rb_str_to_dbl(val
, TRUE
));
3513 if (SPECIAL_CONST_P(val
) && !raise_exception
)
3517 if (!raise_exception
) {
3519 VALUE result
= rb_protect(convert_type_to_float_protected
, val
, &state
);
3520 if (state
) rb_set_errinfo(Qnil
);
3524 return rb_convert_type_with_id(val
, T_FLOAT
, "Float", id_to_f
);
3527 FUNC_MINIMIZED(VALUE
rb_Float(VALUE val
));
3532 return rb_convert_to_float(val
, TRUE
);
3536 rb_f_float1(rb_execution_context_t
*ec
, VALUE obj
, VALUE arg
)
3538 return rb_convert_to_float(arg
, TRUE
);
3542 rb_f_float(rb_execution_context_t
*ec
, VALUE obj
, VALUE arg
, VALUE opts
)
3544 int exception
= rb_bool_expected(opts
, "exception");
3545 return rb_convert_to_float(arg
, exception
);
3549 numeric_to_float(VALUE val
)
3551 if (!rb_obj_is_kind_of(val
, rb_cNumeric
)) {
3552 rb_raise(rb_eTypeError
, "can't convert %"PRIsVALUE
" into Float",
3555 return rb_convert_type_with_id(val
, T_FLOAT
, "Float", id_to_f
);
3559 rb_to_float(VALUE val
)
3561 switch (to_float(&val
, TRUE
)) {
3565 return numeric_to_float(val
);
3569 rb_check_to_float(VALUE val
)
3571 if (RB_FLOAT_TYPE_P(val
)) return val
;
3572 if (!rb_obj_is_kind_of(val
, rb_cNumeric
)) {
3575 return rb_check_convert_type_with_id(val
, T_FLOAT
, "Float", id_to_f
);
3579 basic_to_f_p(VALUE klass
)
3581 return rb_method_basic_definition_p(klass
, id_to_f
);
3586 rb_num_to_dbl(VALUE val
)
3588 if (SPECIAL_CONST_P(val
)) {
3589 if (FIXNUM_P(val
)) {
3590 if (basic_to_f_p(rb_cInteger
))
3591 return fix2dbl_without_to_f(val
);
3593 else if (FLONUM_P(val
)) {
3594 return rb_float_flonum_value(val
);
3597 conversion_to_float(val
);
3601 switch (BUILTIN_TYPE(val
)) {
3603 return rb_float_noflonum_value(val
);
3605 if (basic_to_f_p(rb_cInteger
))
3606 return big2dbl_without_to_f(val
);
3609 if (basic_to_f_p(rb_cRational
))
3610 return rat2dbl_without_to_f(val
);
3616 val
= numeric_to_float(val
);
3617 return RFLOAT_VALUE(val
);
3621 rb_num2dbl(VALUE val
)
3623 if (SPECIAL_CONST_P(val
)) {
3624 if (FIXNUM_P(val
)) {
3625 return fix2dbl_without_to_f(val
);
3627 else if (FLONUM_P(val
)) {
3628 return rb_float_flonum_value(val
);
3631 implicit_conversion_to_float(val
);
3635 switch (BUILTIN_TYPE(val
)) {
3637 return rb_float_noflonum_value(val
);
3639 return big2dbl_without_to_f(val
);
3641 return rat2dbl_without_to_f(val
);
3643 rb_raise(rb_eTypeError
, "no implicit conversion to float from string");
3648 val
= rb_convert_type_with_id(val
, T_FLOAT
, "Float", id_to_f
);
3649 return RFLOAT_VALUE(val
);
3653 rb_String(VALUE val
)
3655 VALUE tmp
= rb_check_string_type(val
);
3657 tmp
= rb_convert_type_with_id(val
, T_STRING
, "String", idTo_s
);
3664 * String(arg) -> string
3666 * Returns <i>arg</i> as a String.
3668 * First tries to call its <code>to_str</code> method, then its <code>to_s</code> method.
3670 * String(self) #=> "main"
3671 * String(self.class) #=> "Object"
3672 * String(123456) #=> "123456"
3676 rb_f_string(VALUE obj
, VALUE arg
)
3678 return rb_String(arg
);
3684 VALUE tmp
= rb_check_array_type(val
);
3687 tmp
= rb_check_to_array(val
);
3689 return rb_ary_new3(1, val
);
3697 * Array(arg) -> array
3699 * Returns +arg+ as an Array.
3701 * First tries to call <code>to_ary</code> on +arg+, then <code>to_a</code>.
3702 * If +arg+ does not respond to <code>to_ary</code> or <code>to_a</code>,
3703 * returns an Array of length 1 containing +arg+.
3705 * If <code>to_ary</code> or <code>to_a</code> returns something other than
3706 * an Array, raises a TypeError.
3708 * Array(["a", "b"]) #=> ["a", "b"]
3709 * Array(1..5) #=> [1, 2, 3, 4, 5]
3710 * Array(key: :value) #=> [[:key, :value]]
3716 rb_f_array(VALUE obj
, VALUE arg
)
3718 return rb_Array(arg
);
3722 * Equivalent to \c Kernel\#Hash in Ruby
3729 if (NIL_P(val
)) return rb_hash_new();
3730 tmp
= rb_check_hash_type(val
);
3732 if (RB_TYPE_P(val
, T_ARRAY
) && RARRAY_LEN(val
) == 0)
3733 return rb_hash_new();
3734 rb_raise(rb_eTypeError
, "can't convert %s into Hash", rb_obj_classname(val
));
3743 * Converts <i>arg</i> to a Hash by calling
3744 * <i>arg</i><code>.to_hash</code>. Returns an empty Hash when
3745 * <i>arg</i> is <tt>nil</tt> or <tt>[]</tt>.
3749 * Hash(key: :value) #=> {:key => :value}
3750 * Hash([1, 2, 3]) #=> TypeError
3754 rb_f_hash(VALUE obj
, VALUE arg
)
3756 return rb_Hash(arg
);
3768 dig_basic_p(VALUE obj
, struct dig_method
*cache
)
3770 VALUE klass
= RBASIC_CLASS(obj
);
3771 if (klass
!= cache
->klass
) {
3772 cache
->klass
= klass
;
3773 cache
->basic
= rb_method_basic_definition_p(klass
, id_dig
);
3775 return cache
->basic
;
3779 no_dig_method(int found
, VALUE recv
, ID mid
, int argc
, const VALUE
*argv
, VALUE data
)
3782 rb_raise(rb_eTypeError
, "%"PRIsVALUE
" does not have #dig method",
3789 rb_obj_dig(int argc
, VALUE
*argv
, VALUE obj
, VALUE notfound
)
3791 struct dig_method hash
= {Qnil
}, ary
= {Qnil
}, strt
= {Qnil
};
3793 for (; argc
> 0; ++argv
, --argc
) {
3794 if (NIL_P(obj
)) return notfound
;
3795 if (!SPECIAL_CONST_P(obj
)) {
3796 switch (BUILTIN_TYPE(obj
)) {
3798 if (dig_basic_p(obj
, &hash
)) {
3799 obj
= rb_hash_aref(obj
, *argv
);
3804 if (dig_basic_p(obj
, &ary
)) {
3805 obj
= rb_ary_at(obj
, *argv
);
3810 if (dig_basic_p(obj
, &strt
)) {
3811 obj
= rb_struct_lookup(obj
, *argv
);
3819 return rb_check_funcall_with_hook_kw(obj
, id_dig
, argc
, argv
,
3828 * format(format_string [, arguments...] ) -> string
3829 * sprintf(format_string [, arguments...] ) -> string
3831 * Returns the string resulting from applying <i>format_string</i> to
3832 * any additional arguments. Within the format string, any characters
3833 * other than format sequences are copied to the result.
3835 * The syntax of a format sequence is as follows.
3837 * %[flags][width][.precision]type
3840 * sequence consists of a percent sign, followed by optional flags,
3841 * width, and precision indicators, then terminated with a field type
3842 * character. The field type controls how the corresponding
3843 * <code>sprintf</code> argument is to be interpreted, while the flags
3844 * modify that interpretation.
3846 * The field type characters are:
3848 * Field | Integer Format
3849 * ------+--------------------------------------------------------------
3850 * b | Convert argument as a binary number.
3851 * | Negative numbers will be displayed as a two's complement
3852 * | prefixed with `..1'.
3853 * B | Equivalent to `b', but uses an uppercase 0B for prefix
3854 * | in the alternative format by #.
3855 * d | Convert argument as a decimal number.
3856 * i | Identical to `d'.
3857 * o | Convert argument as an octal number.
3858 * | Negative numbers will be displayed as a two's complement
3859 * | prefixed with `..7'.
3860 * u | Identical to `d'.
3861 * x | Convert argument as a hexadecimal number.
3862 * | Negative numbers will be displayed as a two's complement
3863 * | prefixed with `..f' (representing an infinite string of
3865 * X | Equivalent to `x', but uses uppercase letters.
3867 * Field | Float Format
3868 * ------+--------------------------------------------------------------
3869 * e | Convert floating point argument into exponential notation
3870 * | with one digit before the decimal point as [-]d.dddddde[+-]dd.
3871 * | The precision specifies the number of digits after the decimal
3872 * | point (defaulting to six).
3873 * E | Equivalent to `e', but uses an uppercase E to indicate
3875 * f | Convert floating point argument as [-]ddd.dddddd,
3876 * | where the precision specifies the number of digits after
3877 * | the decimal point.
3878 * g | Convert a floating point number using exponential form
3879 * | if the exponent is less than -4 or greater than or
3880 * | equal to the precision, or in dd.dddd form otherwise.
3881 * | The precision specifies the number of significant digits.
3882 * G | Equivalent to `g', but use an uppercase `E' in exponent form.
3883 * a | Convert floating point argument as [-]0xh.hhhhp[+-]dd,
3884 * | which is consisted from optional sign, "0x", fraction part
3885 * | as hexadecimal, "p", and exponential part as decimal.
3886 * A | Equivalent to `a', but use uppercase `X' and `P'.
3888 * Field | Other Format
3889 * ------+--------------------------------------------------------------
3890 * c | Argument is the numeric code for a single character or
3891 * | a single character string itself.
3892 * p | The valuing of argument.inspect.
3893 * s | Argument is a string to be substituted. If the format
3894 * | sequence contains a precision, at most that many characters
3896 * % | A percent sign itself will be displayed. No argument taken.
3898 * The flags modifies the behavior of the formats.
3899 * The flag characters are:
3901 * Flag | Applies to | Meaning
3902 * ---------+---------------+-----------------------------------------
3903 * space | bBdiouxX | Leave a space at the start of
3904 * | aAeEfgG | non-negative numbers.
3905 * | (numeric fmt) | For `o', `x', `X', `b' and `B', use
3906 * | | a minus sign with absolute value for
3907 * | | negative values.
3908 * ---------+---------------+-----------------------------------------
3909 * (digit)$ | all | Specifies the absolute argument number
3910 * | | for this field. Absolute and relative
3911 * | | argument numbers cannot be mixed in a
3912 * | | sprintf string.
3913 * ---------+---------------+-----------------------------------------
3914 * # | bBoxX | Use an alternative format.
3915 * | aAeEfgG | For the conversions `o', increase the precision
3916 * | | until the first digit will be `0' if
3917 * | | it is not formatted as complements.
3918 * | | For the conversions `x', `X', `b' and `B'
3919 * | | on non-zero, prefix the result with ``0x'',
3920 * | | ``0X'', ``0b'' and ``0B'', respectively.
3921 * | | For `a', `A', `e', `E', `f', `g', and 'G',
3922 * | | force a decimal point to be added,
3923 * | | even if no digits follow.
3924 * | | For `g' and 'G', do not remove trailing zeros.
3925 * ---------+---------------+-----------------------------------------
3926 * + | bBdiouxX | Add a leading plus sign to non-negative
3927 * | aAeEfgG | numbers.
3928 * | (numeric fmt) | For `o', `x', `X', `b' and `B', use
3929 * | | a minus sign with absolute value for
3930 * | | negative values.
3931 * ---------+---------------+-----------------------------------------
3932 * - | all | Left-justify the result of this conversion.
3933 * ---------+---------------+-----------------------------------------
3934 * 0 (zero) | bBdiouxX | Pad with zeros, not spaces.
3935 * | aAeEfgG | For `o', `x', `X', `b' and `B', radix-1
3936 * | (numeric fmt) | is used for negative numbers formatted as
3938 * ---------+---------------+-----------------------------------------
3939 * * | all | Use the next argument as the field width.
3940 * | | If negative, left-justify the result. If the
3941 * | | asterisk is followed by a number and a dollar
3942 * | | sign, use the indicated argument as the width.
3944 * Examples of flags:
3946 * # `+' and space flag specifies the sign of non-negative numbers.
3947 * sprintf("%d", 123) #=> "123"
3948 * sprintf("%+d", 123) #=> "+123"
3949 * sprintf("% d", 123) #=> " 123"
3951 * # `#' flag for `o' increases number of digits to show `0'.
3952 * # `+' and space flag changes format of negative numbers.
3953 * sprintf("%o", 123) #=> "173"
3954 * sprintf("%#o", 123) #=> "0173"
3955 * sprintf("%+o", -123) #=> "-173"
3956 * sprintf("%o", -123) #=> "..7605"
3957 * sprintf("%#o", -123) #=> "..7605"
3959 * # `#' flag for `x' add a prefix `0x' for non-zero numbers.
3960 * # `+' and space flag disables complements for negative numbers.
3961 * sprintf("%x", 123) #=> "7b"
3962 * sprintf("%#x", 123) #=> "0x7b"
3963 * sprintf("%+x", -123) #=> "-7b"
3964 * sprintf("%x", -123) #=> "..f85"
3965 * sprintf("%#x", -123) #=> "0x..f85"
3966 * sprintf("%#x", 0) #=> "0"
3968 * # `#' for `X' uses the prefix `0X'.
3969 * sprintf("%X", 123) #=> "7B"
3970 * sprintf("%#X", 123) #=> "0X7B"
3972 * # `#' flag for `b' add a prefix `0b' for non-zero numbers.
3973 * # `+' and space flag disables complements for negative numbers.
3974 * sprintf("%b", 123) #=> "1111011"
3975 * sprintf("%#b", 123) #=> "0b1111011"
3976 * sprintf("%+b", -123) #=> "-1111011"
3977 * sprintf("%b", -123) #=> "..10000101"
3978 * sprintf("%#b", -123) #=> "0b..10000101"
3979 * sprintf("%#b", 0) #=> "0"
3981 * # `#' for `B' uses the prefix `0B'.
3982 * sprintf("%B", 123) #=> "1111011"
3983 * sprintf("%#B", 123) #=> "0B1111011"
3985 * # `#' for `e' forces to show the decimal point.
3986 * sprintf("%.0e", 1) #=> "1e+00"
3987 * sprintf("%#.0e", 1) #=> "1.e+00"
3989 * # `#' for `f' forces to show the decimal point.
3990 * sprintf("%.0f", 1234) #=> "1234"
3991 * sprintf("%#.0f", 1234) #=> "1234."
3993 * # `#' for `g' forces to show the decimal point.
3994 * # It also disables stripping lowest zeros.
3995 * sprintf("%g", 123.4) #=> "123.4"
3996 * sprintf("%#g", 123.4) #=> "123.400"
3997 * sprintf("%g", 123456) #=> "123456"
3998 * sprintf("%#g", 123456) #=> "123456."
4000 * The field width is an optional integer, followed optionally by a
4001 * period and a precision. The width specifies the minimum number of
4002 * characters that will be written to the result for this field.
4004 * Examples of width:
4006 * # padding is done by spaces, width=20
4007 * # 0 or radix-1. <------------------>
4008 * sprintf("%20d", 123) #=> " 123"
4009 * sprintf("%+20d", 123) #=> " +123"
4010 * sprintf("%020d", 123) #=> "00000000000000000123"
4011 * sprintf("%+020d", 123) #=> "+0000000000000000123"
4012 * sprintf("% 020d", 123) #=> " 0000000000000000123"
4013 * sprintf("%-20d", 123) #=> "123 "
4014 * sprintf("%-+20d", 123) #=> "+123 "
4015 * sprintf("%- 20d", 123) #=> " 123 "
4016 * sprintf("%020x", -123) #=> "..ffffffffffffffff85"
4019 * numeric fields, the precision controls the number of decimal places
4020 * displayed. For string fields, the precision determines the maximum
4021 * number of characters to be copied from the string. (Thus, the format
4022 * sequence <code>%10.10s</code> will always contribute exactly ten
4023 * characters to the result.)
4025 * Examples of precisions:
4027 * # precision for `d', 'o', 'x' and 'b' is
4028 * # minimum number of digits <------>
4029 * sprintf("%20.8d", 123) #=> " 00000123"
4030 * sprintf("%20.8o", 123) #=> " 00000173"
4031 * sprintf("%20.8x", 123) #=> " 0000007b"
4032 * sprintf("%20.8b", 123) #=> " 01111011"
4033 * sprintf("%20.8d", -123) #=> " -00000123"
4034 * sprintf("%20.8o", -123) #=> " ..777605"
4035 * sprintf("%20.8x", -123) #=> " ..ffff85"
4036 * sprintf("%20.8b", -11) #=> " ..110101"
4038 * # "0x" and "0b" for `#x' and `#b' is not counted for
4039 * # precision but "0" for `#o' is counted. <------>
4040 * sprintf("%#20.8d", 123) #=> " 00000123"
4041 * sprintf("%#20.8o", 123) #=> " 00000173"
4042 * sprintf("%#20.8x", 123) #=> " 0x0000007b"
4043 * sprintf("%#20.8b", 123) #=> " 0b01111011"
4044 * sprintf("%#20.8d", -123) #=> " -00000123"
4045 * sprintf("%#20.8o", -123) #=> " ..777605"
4046 * sprintf("%#20.8x", -123) #=> " 0x..ffff85"
4047 * sprintf("%#20.8b", -11) #=> " 0b..110101"
4049 * # precision for `e' is number of
4050 * # digits after the decimal point <------>
4051 * sprintf("%20.8e", 1234.56789) #=> " 1.23456789e+03"
4053 * # precision for `f' is number of
4054 * # digits after the decimal point <------>
4055 * sprintf("%20.8f", 1234.56789) #=> " 1234.56789000"
4057 * # precision for `g' is number of
4058 * # significant digits <------->
4059 * sprintf("%20.8g", 1234.56789) #=> " 1234.5679"
4062 * sprintf("%20.8g", 123456789) #=> " 1.2345679e+08"
4064 * # precision for `s' is
4065 * # maximum number of characters <------>
4066 * sprintf("%20.8s", "string test") #=> " string t"
4070 * sprintf("%d %04x", 123, 123) #=> "123 007b"
4071 * sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'"
4072 * sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello"
4073 * sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8"
4074 * sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23"
4075 * sprintf("%u", -123) #=> "-123"
4077 * For more complex formatting, Ruby supports a reference by name.
4078 * %<name>s style uses format style, but %{name} style doesn't.
4081 * sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 })
4083 * sprintf("%{foo}f", { :foo => 1 })
4088 f_sprintf(int c
, const VALUE
*v
, VALUE _
)
4090 return rb_f_sprintf(c
, v
);
4094 * Document-class: Class
4096 * Classes in Ruby are first-class objects---each is an instance of
4099 * Typically, you create a new class by using:
4102 * # some code describing the class behavior
4105 * When a new class is created, an object of type Class is initialized and
4106 * assigned to a global constant (Name in this case).
4108 * When <code>Name.new</code> is called to create a new object, the
4109 * #new method in Class is run by default.
4110 * This can be demonstrated by overriding #new in Class:
4115 * print "Creating a new ", self.name, "\n"
4125 * <em>produces:</em>
4127 * Creating a new Name
4129 * Classes, modules, and objects are interrelated. In the diagram
4130 * that follows, the vertical arrows represent inheritance, and the
4131 * parentheses metaclasses. All metaclasses are instances
4132 * of the class `Class'.
4135 * BasicObject-----|-->(BasicObject)-------|-...
4138 * Object---------|----->(Object)---------|-...
4141 * +-------+ | +--------+ |
4143 * | Module-|---------|--->(Module)-|-...
4146 * | Class-|---------|---->(Class)-|-...
4150 * obj--->OtherClass---------->(OtherClass)-----------...
4155 /* Document-class: BasicObject
4157 * BasicObject is the parent class of all classes in Ruby. It's an explicit
4160 * BasicObject can be used for creating object hierarchies independent of
4161 * Ruby's object hierarchy, proxy objects like the Delegator class, or other
4162 * uses where namespace pollution from Ruby's methods and classes must be
4165 * To avoid polluting BasicObject for other users an appropriately named
4166 * subclass of BasicObject should be created instead of directly modifying
4169 * class MyObjectSystem < BasicObject
4172 * BasicObject does not include Kernel (for methods like +puts+) and
4173 * BasicObject is outside of the namespace of the standard library so common
4174 * classes will not be found without using a full class path.
4176 * A variety of strategies can be used to provide useful portions of the
4177 * standard library to subclasses of BasicObject. A subclass could
4178 * <code>include Kernel</code> to obtain +puts+, +exit+, etc. A custom
4179 * Kernel-like module could be created and included or delegation can be used
4180 * via #method_missing:
4182 * class MyObjectSystem < BasicObject
4183 * DELEGATE = [:puts, :p]
4185 * def method_missing(name, *args, &block)
4186 * return super unless DELEGATE.include? name
4187 * ::Kernel.send(name, *args, &block)
4190 * def respond_to_missing?(name, include_private = false)
4191 * DELEGATE.include?(name) or super
4195 * Access to classes and modules from the Ruby standard library can be
4196 * obtained in a BasicObject subclass by referencing the desired constant
4197 * from the root like <code>::File</code> or <code>::Enumerator</code>.
4198 * Like #method_missing, #const_missing can be used to delegate constant
4199 * lookup to +Object+:
4201 * class MyObjectSystem < BasicObject
4202 * def self.const_missing(name)
4203 * ::Object.const_get(name)
4209 * These are the methods defined for \BasicObject:
4211 * - ::new:: Returns a new \BasicObject instance.
4212 * - {!}[#method-i-21]:: Returns the boolean negation of +self+: +true+ or +false+.
4213 * - {!=}[#method-i-21-3D]:: Returns whether +self+ and the given object
4215 * - {==}[#method-i-3D-3D]:: Returns whether +self+ and the given object
4217 * - {__id__}[#method-i-__id__]:: Returns the integer object identifier for +self+.
4218 * - {__send__}[#method-i-__send__]:: Calls the method identified by the given symbol.
4219 * - #equal?:: Returns whether +self+ and the given object are the same object.
4220 * - #instance_eval:: Evaluates the given string or block in the context of +self+.
4221 * - #instance_exec:: Executes the given block in the context of +self+,
4222 * passing the given arguments.
4223 * - #method_missing:: Method called when an undefined method is called on +self+.
4224 * - #singleton_method_added:: Method called when a singleton method
4225 * is added to +self+.
4226 * - #singleton_method_removed:: Method called when a singleton method
4227 * is added removed from +self+.
4228 * - #singleton_method_undefined:: Method called when a singleton method
4229 * is undefined in +self+.
4233 /* Document-class: Object
4235 * Object is the default root of all Ruby objects. Object inherits from
4236 * BasicObject which allows creating alternate object hierarchies. Methods
4237 * on Object are available to all classes unless explicitly overridden.
4239 * Object mixes in the Kernel module, making the built-in kernel functions
4240 * globally accessible. Although the instance methods of Object are defined
4241 * by the Kernel module, we have chosen to document them here for clarity.
4243 * When referencing constants in classes inheriting from Object you do not
4244 * need to use the full namespace. For example, referencing +File+ inside
4245 * +YourClass+ will find the top-level File class.
4247 * In the descriptions of Object's methods, the parameter <i>symbol</i> refers
4248 * to a symbol, which is either a quoted string or a Symbol (such as
4249 * <code>:name</code>).
4253 * First, what's elsewhere. \Class \Object:
4255 * - Inherits from {class BasicObject}[BasicObject.html#class-BasicObject-label-What-27s+Here].
4256 * - Includes {module Kernel}[Kernel.html#module-Kernel-label-What-27s+Here].
4258 * Here, class \Object provides methods for:
4260 * - {Querying}[#class-Object-label-Querying]
4261 * - {Instance Variables}[#class-Object-label-Instance+Variables]
4262 * - {Other}[#class-Object-label-Other]
4266 * - {!~}[#method-i-21~]:: Returns +true+ if +self+ does not match the given object,
4267 * otherwise +false+.
4268 * - {<=>}[#method-i-3C-3D-3E]:: Returns 0 if +self+ and the given object +object+
4269 * are the same object, or if
4270 * <tt>self == object</tt>; otherwise returns +nil+.
4271 * - #===:: Implements case equality, effectively the same as calling #==.
4272 * - #eql?:: Implements hash equality, effectively the same as calling #==.
4273 * - #kind_of? (aliased as #is_a?):: Returns whether given argument is an ancestor
4274 * of the singleton class of +self+.
4275 * - #instance_of?:: Returns whether +self+ is an instance of the given class.
4276 * - #instance_variable_defined?:: Returns whether the given instance variable
4277 * is defined in +self+.
4278 * - #method:: Returns the Method object for the given method in +self+.
4279 * - #methods:: Returns an array of symbol names of public and protected methods
4281 * - #nil?:: Returns +false+. (Only +nil+ responds +true+ to method <tt>nil?</tt>.)
4282 * - #object_id:: Returns an integer corresponding to +self+ that is unique
4283 * for the current process
4284 * - #private_methods:: Returns an array of the symbol names
4285 * of the private methods in +self+.
4286 * - #protected_methods:: Returns an array of the symbol names
4287 * of the protected methods in +self+.
4288 * - #public_method:: Returns the Method object for the given public method in +self+.
4289 * - #public_methods:: Returns an array of the symbol names
4290 * of the public methods in +self+.
4291 * - #respond_to?:: Returns whether +self+ responds to the given method.
4292 * - #singleton_class:: Returns the singleton class of +self+.
4293 * - #singleton_method:: Returns the Method object for the given singleton method
4295 * - #singleton_methods:: Returns an array of the symbol names
4296 * of the singleton methods in +self+.
4298 * - #define_singleton_method:: Defines a singleton method in +self+
4299 * for the given symbol method-name and block or proc.
4300 * - #extend:: Includes the given modules in the singleton class of +self+.
4301 * - #public_send:: Calls the given public method in +self+ with the given argument.
4302 * - #send:: Calls the given method in +self+ with the given argument.
4304 * === Instance Variables
4306 * - #instance_variable_get:: Returns the value of the given instance variable
4307 * in +self+, or +nil+ if the instance variable is not set.
4308 * - #instance_variable_set:: Sets the value of the given instance variable in +self+
4309 * to the given object.
4310 * - #instance_variables:: Returns an array of the symbol names
4311 * of the instance variables in +self+.
4312 * - #remove_instance_variable:: Removes the named instance variable from +self+.
4316 * - #clone:: Returns a shallow copy of +self+, including singleton class
4318 * - #define_singleton_method:: Defines a singleton method in +self+
4319 * for the given symbol method-name and block or proc.
4320 * - #display:: Prints +self+ to the given \IO stream or <tt>$stdout</tt>.
4321 * - #dup:: Returns a shallow unfrozen copy of +self+.
4322 * - #enum_for (aliased as #to_enum):: Returns an Enumerator for +self+
4323 * using the using the given method,
4324 * arguments, and block.
4325 * - #extend:: Includes the given modules in the singleton class of +self+.
4326 * - #freeze:: Prevents further modifications to +self+.
4327 * - #hash:: Returns the integer hash value for +self+.
4328 * - #inspect:: Returns a human-readable string representation of +self+.
4329 * - #itself:: Returns +self+.
4330 * - #public_send:: Calls the given public method in +self+ with the given argument.
4331 * - #send:: Calls the given method in +self+ with the given argument.
4332 * - #to_s:: Returns a string representation of +self+.
4339 * Initializes the world of objects and classes.
4341 * At first, the function bootstraps the class hierarchy.
4342 * It initializes the most fundamental classes and their metaclasses.
4347 * After the bootstrap step, the class hierarchy becomes as the following
4350 * \image html boottime-classes.png
4352 * Then, the function defines classes, modules and methods as usual.
4360 Init_class_hierarchy();
4363 // teach RDoc about these classes
4364 rb_cBasicObject
= rb_define_class("BasicObject", Qnil
);
4365 rb_cObject
= rb_define_class("Object", rb_cBasicObject
);
4366 rb_cModule
= rb_define_class("Module", rb_cObject
);
4367 rb_cClass
= rb_define_class("Class", rb_cModule
);
4368 rb_cRefinement
= rb_define_class("Refinement", rb_cModule
);
4371 rb_define_private_method(rb_cBasicObject
, "initialize", rb_obj_initialize
, 0);
4372 rb_define_alloc_func(rb_cBasicObject
, rb_class_allocate_instance
);
4373 rb_define_method(rb_cBasicObject
, "==", rb_obj_equal
, 1);
4374 rb_define_method(rb_cBasicObject
, "equal?", rb_obj_equal
, 1);
4375 rb_define_method(rb_cBasicObject
, "!", rb_obj_not
, 0);
4376 rb_define_method(rb_cBasicObject
, "!=", rb_obj_not_equal
, 1);
4378 rb_define_private_method(rb_cBasicObject
, "singleton_method_added", rb_obj_singleton_method_added
, 1);
4379 rb_define_private_method(rb_cBasicObject
, "singleton_method_removed", rb_obj_singleton_method_removed
, 1);
4380 rb_define_private_method(rb_cBasicObject
, "singleton_method_undefined", rb_obj_singleton_method_undefined
, 1);
4382 /* Document-module: Kernel
4384 * The Kernel module is included by class Object, so its methods are
4385 * available in every Ruby object.
4387 * The Kernel instance methods are documented in class Object while the
4388 * module methods are documented here. These methods are called without a
4389 * receiver and thus can be called in functional form:
4391 * sprintf "%.1f", 1.234 #=> "1.2"
4395 * \Module \Kernel provides methods that are useful for:
4397 * - {Converting}[#module-Kernel-label-Converting]
4398 * - {Querying}[#module-Kernel-label-Querying]
4399 * - {Exiting}[#module-Kernel-label-Exiting]
4400 * - {Exceptions}[#module-Kernel-label-Exceptions]
4401 * - {IO}[#module-Kernel-label-IO]
4402 * - {Procs}[#module-Kernel-label-Procs]
4403 * - {Tracing}[#module-Kernel-label-Tracing]
4404 * - {Subprocesses}[#module-Kernel-label-Subprocesses]
4405 * - {Loading}[#module-Kernel-label-Loading]
4406 * - {Yielding}[#module-Kernel-label-Yielding]
4407 * - {Random Values}[#module-Kernel-label-Random+Values]
4408 * - {Other}[#module-Kernel-label-Other]
4412 * - {#Array}[#method-i-Array]:: Returns an Array based on the given argument.
4413 * - {#Complex}[#method-i-Complex]:: Returns a Complex based on the given arguments.
4414 * - {#Float}[#method-i-Float]:: Returns a Float based on the given arguments.
4415 * - {#Hash}[#method-i-Hash]:: Returns a Hash based on the given argument.
4416 * - {#Integer}[#method-i-Integer]:: Returns an Integer based on the given arguments.
4417 * - {#Rational}[#method-i-Rational]:: Returns a Rational
4418 * based on the given arguments.
4419 * - {#String}[#method-i-String]:: Returns a String based on the given argument.
4423 * - {#__callee__}[#method-i-__callee__]:: Returns the called name
4424 * of the current method as a symbol.
4425 * - {#__dir__}[#method-i-__dir__]:: Returns the path to the directory
4426 * from which the current method is called.
4427 * - {#__method__}[#method-i-__method__]:: Returns the name
4428 * of the current method as a symbol.
4429 * - #autoload?:: Returns the file to be loaded when the given module is referenced.
4430 * - #binding:: Returns a Binding for the context at the point of call.
4431 * - #block_given?:: Returns +true+ if a block was passed to the calling method.
4432 * - #caller:: Returns the current execution stack as an array of strings.
4433 * - #caller_locations:: Returns the current execution stack as an array
4434 * of Thread::Backtrace::Location objects.
4435 * - #class:: Returns the class of +self+.
4436 * - #frozen?:: Returns whether +self+ is frozen.
4437 * - #global_variables:: Returns an array of global variables as symbols.
4438 * - #local_variables:: Returns an array of local variables as symbols.
4439 * - #test:: Performs specified tests on the given single file or pair of files.
4443 * - #abort:: Exits the current process after printing the given arguments.
4444 * - #at_exit:: Executes the given block when the process exits.
4445 * - #exit:: Exits the current process after calling any registered
4446 * +at_exit+ handlers.
4447 * - #exit!:: Exits the current process without calling any registered
4448 * +at_exit+ handlers.
4452 * - #catch:: Executes the given block, possibly catching a thrown object.
4453 * - #raise (aliased as #fail):: Raises an exception based on the given arguments.
4454 * - #throw:: Returns from the active catch block waiting for the given tag.
4459 * - #gets:: Returns and assigns to <tt>$_</tt> the next line from the current input.
4460 * - #open:: Creates an IO object connected to the given stream, file, or subprocess.
4461 * - #p:: Prints the given objects' inspect output to the standard output.
4462 * - #pp:: Prints the given objects in pretty form.
4463 * - #print:: Prints the given objects to standard output without a newline.
4464 * - #printf:: Prints the string resulting from applying the given format string
4465 * to any additional arguments.
4466 * - #putc:: Equivalent to <tt.$stdout.putc(object)</tt> for the given object.
4467 * - #puts:: Equivalent to <tt>$stdout.puts(*objects)</tt> for the given objects.
4468 * - #readline:: Similar to #gets, but raises an exception at the end of file.
4469 * - #readlines:: Returns an array of the remaining lines from the current input.
4470 * - #select:: Same as IO.select.
4474 * - #lambda:: Returns a lambda proc for the given block.
4475 * - #proc:: Returns a new Proc; equivalent to Proc.new.
4479 * - #set_trace_func:: Sets the given proc as the handler for tracing,
4480 * or disables tracing if given +nil+.
4481 * - #trace_var:: Starts tracing assignments to the given global variable.
4482 * - #untrace_var:: Disables tracing of assignments to the given global variable.
4486 * - #`cmd`:: Returns the standard output of running +cmd+ in a subshell.
4487 * - #exec:: Replaces current process with a new process.
4488 * - #fork:: Forks the current process into two processes.
4489 * - #spawn:: Executes the given command and returns its pid without waiting
4491 * - #system:: Executes the given command in a subshell.
4495 * - #autoload:: Registers the given file to be loaded when the given constant
4496 * is first referenced.
4497 * - #load:: Loads the given Ruby file.
4498 * - #require:: Loads the given Ruby file unless it has already been loaded.
4499 * - #require_relative:: Loads the Ruby file path relative to the calling file,
4500 * unless it has already been loaded.
4504 * - #tap:: Yields +self+ to the given block; returns +self+.
4505 * - #then (aliased as #yield_self):: Yields +self+ to the block
4506 * and returns the result of the block.
4508 * === \Random Values
4510 * - #rand:: Returns a pseudo-random floating point number
4511 * strictly between 0.0 and 1.0.
4512 * - #srand:: Seeds the pseudo-random number generator with the given number.
4516 * - #eval:: Evaluates the given string as Ruby code.
4517 * - #loop:: Repeatedly executes the given block.
4518 * - #sleep:: Suspends the current thread for the given number of seconds.
4519 * - #sprintf (aliased as #format):: Returns the string resulting from applying
4520 * the given format string
4521 * to any additional arguments.
4522 * - #syscall:: Runs an operating system call.
4523 * - #trap:: Specifies the handling of system signals.
4524 * - #warn:: Issue a warning based on the given messages and options.
4527 rb_mKernel
= rb_define_module("Kernel");
4528 rb_include_module(rb_cObject
, rb_mKernel
);
4529 rb_define_private_method(rb_cClass
, "inherited", rb_obj_class_inherited
, 1);
4530 rb_define_private_method(rb_cModule
, "included", rb_obj_mod_included
, 1);
4531 rb_define_private_method(rb_cModule
, "extended", rb_obj_mod_extended
, 1);
4532 rb_define_private_method(rb_cModule
, "prepended", rb_obj_mod_prepended
, 1);
4533 rb_define_private_method(rb_cModule
, "method_added", rb_obj_mod_method_added
, 1);
4534 rb_define_private_method(rb_cModule
, "method_removed", rb_obj_mod_method_removed
, 1);
4535 rb_define_private_method(rb_cModule
, "method_undefined", rb_obj_mod_method_undefined
, 1);
4537 rb_define_method(rb_mKernel
, "nil?", rb_false
, 0);
4538 rb_define_method(rb_mKernel
, "===", case_equal
, 1);
4539 rb_define_method(rb_mKernel
, "=~", rb_obj_match
, 1);
4540 rb_define_method(rb_mKernel
, "!~", rb_obj_not_match
, 1);
4541 rb_define_method(rb_mKernel
, "eql?", rb_obj_equal
, 1);
4542 rb_define_method(rb_mKernel
, "hash", rb_obj_hash
, 0); /* in hash.c */
4543 rb_define_method(rb_mKernel
, "<=>", rb_obj_cmp
, 1);
4545 rb_define_method(rb_mKernel
, "singleton_class", rb_obj_singleton_class
, 0);
4546 rb_define_method(rb_mKernel
, "dup", rb_obj_dup
, 0);
4547 rb_define_method(rb_mKernel
, "itself", rb_obj_itself
, 0);
4548 rb_define_method(rb_mKernel
, "initialize_copy", rb_obj_init_copy
, 1);
4549 rb_define_method(rb_mKernel
, "initialize_dup", rb_obj_init_dup_clone
, 1);
4550 rb_define_method(rb_mKernel
, "initialize_clone", rb_obj_init_clone
, -1);
4552 rb_define_method(rb_mKernel
, "taint", rb_obj_taint
, 0);
4553 rb_define_method(rb_mKernel
, "tainted?", rb_obj_tainted
, 0);
4554 rb_define_method(rb_mKernel
, "untaint", rb_obj_untaint
, 0);
4555 rb_define_method(rb_mKernel
, "untrust", rb_obj_untrust
, 0);
4556 rb_define_method(rb_mKernel
, "untrusted?", rb_obj_untrusted
, 0);
4557 rb_define_method(rb_mKernel
, "trust", rb_obj_trust
, 0);
4558 rb_define_method(rb_mKernel
, "freeze", rb_obj_freeze
, 0);
4560 rb_define_method(rb_mKernel
, "to_s", rb_any_to_s
, 0);
4561 rb_define_method(rb_mKernel
, "inspect", rb_obj_inspect
, 0);
4562 rb_define_method(rb_mKernel
, "methods", rb_obj_methods
, -1); /* in class.c */
4563 rb_define_method(rb_mKernel
, "singleton_methods", rb_obj_singleton_methods
, -1); /* in class.c */
4564 rb_define_method(rb_mKernel
, "protected_methods", rb_obj_protected_methods
, -1); /* in class.c */
4565 rb_define_method(rb_mKernel
, "private_methods", rb_obj_private_methods
, -1); /* in class.c */
4566 rb_define_method(rb_mKernel
, "public_methods", rb_obj_public_methods
, -1); /* in class.c */
4567 rb_define_method(rb_mKernel
, "instance_variables", rb_obj_instance_variables
, 0); /* in variable.c */
4568 rb_define_method(rb_mKernel
, "instance_variable_get", rb_obj_ivar_get
, 1);
4569 rb_define_method(rb_mKernel
, "instance_variable_set", rb_obj_ivar_set
, 2);
4570 rb_define_method(rb_mKernel
, "instance_variable_defined?", rb_obj_ivar_defined
, 1);
4571 rb_define_method(rb_mKernel
, "remove_instance_variable",
4572 rb_obj_remove_instance_variable
, 1); /* in variable.c */
4574 rb_define_method(rb_mKernel
, "instance_of?", rb_obj_is_instance_of
, 1);
4575 rb_define_method(rb_mKernel
, "kind_of?", rb_obj_is_kind_of
, 1);
4576 rb_define_method(rb_mKernel
, "is_a?", rb_obj_is_kind_of
, 1);
4578 rb_define_global_function("sprintf", f_sprintf
, -1);
4579 rb_define_global_function("format", f_sprintf
, -1);
4581 rb_define_global_function("Integer", rb_f_integer
, -1);
4583 rb_define_global_function("String", rb_f_string
, 1);
4584 rb_define_global_function("Array", rb_f_array
, 1);
4585 rb_define_global_function("Hash", rb_f_hash
, 1);
4587 rb_cNilClass
= rb_define_class("NilClass", rb_cObject
);
4588 rb_cNilClass_to_s
= rb_fstring_enc_lit("", rb_usascii_encoding());
4589 rb_gc_register_mark_object(rb_cNilClass_to_s
);
4590 rb_define_method(rb_cNilClass
, "to_s", rb_nil_to_s
, 0);
4591 rb_define_method(rb_cNilClass
, "to_a", nil_to_a
, 0);
4592 rb_define_method(rb_cNilClass
, "to_h", nil_to_h
, 0);
4593 rb_define_method(rb_cNilClass
, "inspect", nil_inspect
, 0);
4594 rb_define_method(rb_cNilClass
, "=~", nil_match
, 1);
4595 rb_define_method(rb_cNilClass
, "&", false_and
, 1);
4596 rb_define_method(rb_cNilClass
, "|", false_or
, 1);
4597 rb_define_method(rb_cNilClass
, "^", false_xor
, 1);
4598 rb_define_method(rb_cNilClass
, "===", case_equal
, 1);
4600 rb_define_method(rb_cNilClass
, "nil?", rb_true
, 0);
4601 rb_undef_alloc_func(rb_cNilClass
);
4602 rb_undef_method(CLASS_OF(rb_cNilClass
), "new");
4604 rb_define_method(rb_cModule
, "freeze", rb_mod_freeze
, 0);
4605 rb_define_method(rb_cModule
, "===", rb_mod_eqq
, 1);
4606 rb_define_method(rb_cModule
, "==", rb_obj_equal
, 1);
4607 rb_define_method(rb_cModule
, "<=>", rb_mod_cmp
, 1);
4608 rb_define_method(rb_cModule
, "<", rb_mod_lt
, 1);
4609 rb_define_method(rb_cModule
, "<=", rb_class_inherited_p
, 1);
4610 rb_define_method(rb_cModule
, ">", rb_mod_gt
, 1);
4611 rb_define_method(rb_cModule
, ">=", rb_mod_ge
, 1);
4612 rb_define_method(rb_cModule
, "initialize_copy", rb_mod_init_copy
, 1); /* in class.c */
4613 rb_define_method(rb_cModule
, "to_s", rb_mod_to_s
, 0);
4614 rb_define_alias(rb_cModule
, "inspect", "to_s");
4615 rb_define_method(rb_cModule
, "included_modules", rb_mod_included_modules
, 0); /* in class.c */
4616 rb_define_method(rb_cModule
, "include?", rb_mod_include_p
, 1); /* in class.c */
4617 rb_define_method(rb_cModule
, "name", rb_mod_name
, 0); /* in variable.c */
4618 rb_define_method(rb_cModule
, "ancestors", rb_mod_ancestors
, 0); /* in class.c */
4620 rb_define_method(rb_cModule
, "attr", rb_mod_attr
, -1);
4621 rb_define_method(rb_cModule
, "attr_reader", rb_mod_attr_reader
, -1);
4622 rb_define_method(rb_cModule
, "attr_writer", rb_mod_attr_writer
, -1);
4623 rb_define_method(rb_cModule
, "attr_accessor", rb_mod_attr_accessor
, -1);
4625 rb_define_alloc_func(rb_cModule
, rb_module_s_alloc
);
4626 rb_undef_method(rb_singleton_class(rb_cModule
), "allocate");
4627 rb_define_method(rb_cModule
, "initialize", rb_mod_initialize
, 0);
4628 rb_define_method(rb_cModule
, "initialize_clone", rb_mod_initialize_clone
, -1);
4629 rb_define_method(rb_cModule
, "instance_methods", rb_class_instance_methods
, -1); /* in class.c */
4630 rb_define_method(rb_cModule
, "public_instance_methods",
4631 rb_class_public_instance_methods
, -1); /* in class.c */
4632 rb_define_method(rb_cModule
, "protected_instance_methods",
4633 rb_class_protected_instance_methods
, -1); /* in class.c */
4634 rb_define_method(rb_cModule
, "private_instance_methods",
4635 rb_class_private_instance_methods
, -1); /* in class.c */
4637 rb_define_method(rb_cModule
, "constants", rb_mod_constants
, -1); /* in variable.c */
4638 rb_define_method(rb_cModule
, "const_get", rb_mod_const_get
, -1);
4639 rb_define_method(rb_cModule
, "const_set", rb_mod_const_set
, 2);
4640 rb_define_method(rb_cModule
, "const_defined?", rb_mod_const_defined
, -1);
4641 rb_define_method(rb_cModule
, "const_source_location", rb_mod_const_source_location
, -1);
4642 rb_define_private_method(rb_cModule
, "remove_const",
4643 rb_mod_remove_const
, 1); /* in variable.c */
4644 rb_define_method(rb_cModule
, "const_missing",
4645 rb_mod_const_missing
, 1); /* in variable.c */
4646 rb_define_method(rb_cModule
, "class_variables",
4647 rb_mod_class_variables
, -1); /* in variable.c */
4648 rb_define_method(rb_cModule
, "remove_class_variable",
4649 rb_mod_remove_cvar
, 1); /* in variable.c */
4650 rb_define_method(rb_cModule
, "class_variable_get", rb_mod_cvar_get
, 1);
4651 rb_define_method(rb_cModule
, "class_variable_set", rb_mod_cvar_set
, 2);
4652 rb_define_method(rb_cModule
, "class_variable_defined?", rb_mod_cvar_defined
, 1);
4653 rb_define_method(rb_cModule
, "public_constant", rb_mod_public_constant
, -1); /* in variable.c */
4654 rb_define_method(rb_cModule
, "private_constant", rb_mod_private_constant
, -1); /* in variable.c */
4655 rb_define_method(rb_cModule
, "deprecate_constant", rb_mod_deprecate_constant
, -1); /* in variable.c */
4656 rb_define_method(rb_cModule
, "singleton_class?", rb_mod_singleton_p
, 0);
4658 rb_define_method(rb_singleton_class(rb_cClass
), "allocate", rb_class_alloc_m
, 0);
4659 rb_define_method(rb_cClass
, "allocate", rb_class_alloc_m
, 0);
4660 rb_define_method(rb_cClass
, "new", rb_class_new_instance_pass_kw
, -1);
4661 rb_define_method(rb_cClass
, "initialize", rb_class_initialize
, -1);
4662 rb_define_method(rb_cClass
, "superclass", rb_class_superclass
, 0);
4663 rb_define_method(rb_cClass
, "subclasses", rb_class_subclasses
, 0); /* in class.c */
4664 rb_define_alloc_func(rb_cClass
, rb_class_s_alloc
);
4665 rb_undef_method(rb_cClass
, "extend_object");
4666 rb_undef_method(rb_cClass
, "append_features");
4667 rb_undef_method(rb_cClass
, "prepend_features");
4669 rb_cTrueClass
= rb_define_class("TrueClass", rb_cObject
);
4670 rb_cTrueClass_to_s
= rb_fstring_enc_lit("true", rb_usascii_encoding());
4671 rb_gc_register_mark_object(rb_cTrueClass_to_s
);
4672 rb_define_method(rb_cTrueClass
, "to_s", rb_true_to_s
, 0);
4673 rb_define_alias(rb_cTrueClass
, "inspect", "to_s");
4674 rb_define_method(rb_cTrueClass
, "&", true_and
, 1);
4675 rb_define_method(rb_cTrueClass
, "|", true_or
, 1);
4676 rb_define_method(rb_cTrueClass
, "^", true_xor
, 1);
4677 rb_define_method(rb_cTrueClass
, "===", case_equal
, 1);
4678 rb_undef_alloc_func(rb_cTrueClass
);
4679 rb_undef_method(CLASS_OF(rb_cTrueClass
), "new");
4681 rb_cFalseClass
= rb_define_class("FalseClass", rb_cObject
);
4682 rb_cFalseClass_to_s
= rb_fstring_enc_lit("false", rb_usascii_encoding());
4683 rb_gc_register_mark_object(rb_cFalseClass_to_s
);
4684 rb_define_method(rb_cFalseClass
, "to_s", rb_false_to_s
, 0);
4685 rb_define_alias(rb_cFalseClass
, "inspect", "to_s");
4686 rb_define_method(rb_cFalseClass
, "&", false_and
, 1);
4687 rb_define_method(rb_cFalseClass
, "|", false_or
, 1);
4688 rb_define_method(rb_cFalseClass
, "^", false_xor
, 1);
4689 rb_define_method(rb_cFalseClass
, "===", case_equal
, 1);
4690 rb_undef_alloc_func(rb_cFalseClass
);
4691 rb_undef_method(CLASS_OF(rb_cFalseClass
), "new");
4694 #include "kernel.rbinc"
4695 #include "nilclass.rbinc"
4700 id_dig
= rb_intern_const("dig");