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