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