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