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