Ruby 4.1.0dev (2026-09-27 revision f6ff9e7d02e46360f8930b280a3dd921cccbda29)
object.c (f6ff9e7d02e46360f8930b280a3dd921cccbda29)
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 (long 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 (UNDEF_P(ivars) || NIL_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
2140static VALUE
2141rb_class_initialize(int argc, VALUE *argv, VALUE klass)
2142{
2143 VALUE super;
2144
2145 // an uninitialized class is still somebody's, and this writes its superclass
2146 rb_class_modify_check(klass);
2147 if (RCLASS_SUPER(klass) != 0 || klass == rb_cBasicObject) {
2148 rb_raise(rb_eTypeError, "already initialized class");
2149 }
2150 if (rb_check_arity(argc, 0, 1) == 0) {
2151 super = rb_cObject;
2152 }
2153 else {
2154 super = argv[0];
2155 rb_check_inheritable(super);
2156 if (!RCLASS_INITIALIZED_P(super)) {
2157 rb_raise(rb_eTypeError, "can't inherit uninitialized class");
2158 }
2159 }
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_make_metaclass(klass, RBASIC(super)->klass);
2164 rb_class_inherited(super, klass);
2165 rb_mod_initialize_exec(klass);
2166
2167 return klass;
2168}
2169
2171void
2172rb_undefined_alloc(VALUE klass)
2173{
2174 rb_raise(rb_eTypeError, "allocator undefined for %"PRIsVALUE,
2175 klass);
2176}
2177
2178static rb_alloc_func_t class_get_alloc_func(VALUE klass);
2179static VALUE class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass);
2180
2181/*
2182 * call-seq:
2183 * class.allocate() -> obj
2184 *
2185 * Allocates space for a new object of <i>class</i>'s class and does not
2186 * call initialize on the new instance. The returned object must be an
2187 * instance of <i>class</i>.
2188 *
2189 * klass = Class.new do
2190 * def initialize(*args)
2191 * @initialized = true
2192 * end
2193 *
2194 * def initialized?
2195 * @initialized || false
2196 * end
2197 * end
2198 *
2199 * klass.allocate.initialized? #=> false
2200 *
2201 */
2202
2203static VALUE
2204rb_class_alloc(VALUE klass)
2205{
2206 RBIMPL_ASSERT_TYPE(klass, T_CLASS);
2207 rb_alloc_func_t allocator = class_get_alloc_func(klass);
2208 return class_call_alloc_func(allocator, klass);
2209}
2210
2211static rb_alloc_func_t
2212class_get_alloc_func(VALUE klass)
2213{
2214 rb_alloc_func_t allocator;
2215
2216 if (!RCLASS_INITIALIZED_P(klass)) {
2217 rb_raise(rb_eTypeError, "can't instantiate uninitialized class");
2218 }
2219 if (RCLASS_SINGLETON_P(klass)) {
2220 rb_raise(rb_eTypeError, "can't create instance of singleton class");
2221 }
2222 allocator = rb_get_alloc_func(klass);
2223 if (!allocator) {
2224 rb_undefined_alloc(klass);
2225 }
2226 return allocator;
2227}
2228
2229// Might return NULL.
2231rb_zjit_class_get_alloc_func(VALUE klass)
2232{
2233 assert(RCLASS_INITIALIZED_P(klass));
2234 assert(!RCLASS_SINGLETON_P(klass));
2235 return rb_get_alloc_func(klass);
2236}
2237
2238static VALUE
2239class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass)
2240{
2241 VALUE obj;
2242
2243 RUBY_DTRACE_CREATE_HOOK(OBJECT, rb_class2name(klass));
2244
2245 obj = (*allocator)(klass);
2246
2247 RUBY_ASSERT(rb_obj_class(obj) == rb_class_real(klass));
2248 return obj;
2249}
2250
2251VALUE
2253{
2254 Check_Type(klass, T_CLASS);
2255 return rb_class_alloc(klass);
2256}
2257
2258/*
2259 * call-seq:
2260 * class.new(args, ...) -> obj
2261 *
2262 * Calls #allocate to create a new object of <i>class</i>'s class,
2263 * then invokes that object's #initialize method, passing it
2264 * <i>args</i>. This is the method that ends up getting called
2265 * whenever an object is constructed using <code>.new</code>.
2266 *
2267 */
2268
2269VALUE
2270rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass)
2271{
2272 VALUE obj;
2273
2274 obj = rb_class_alloc(klass);
2275 rb_obj_call_init_kw(obj, argc, argv, RB_PASS_CALLED_KEYWORDS);
2276
2277 return obj;
2278}
2279
2280VALUE
2281rb_class_new_instance_kw(int argc, const VALUE *argv, VALUE klass, int kw_splat)
2282{
2283 VALUE obj;
2284 Check_Type(klass, T_CLASS);
2285
2286 obj = rb_class_alloc(klass);
2287 rb_obj_call_init_kw(obj, argc, argv, kw_splat);
2288
2289 return obj;
2290}
2291
2292VALUE
2293rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
2294{
2295 return rb_class_new_instance_kw(argc, argv, klass, RB_NO_KEYWORDS);
2296}
2297
2307VALUE
2309{
2310 RUBY_ASSERT(RB_TYPE_P(klass, T_CLASS));
2311
2312 VALUE *superclasses = RCLASS_SUPERCLASSES(klass);
2313 size_t superclasses_depth = RCLASS_SUPERCLASS_DEPTH(klass);
2314
2315 if (klass == rb_cBasicObject) return Qnil;
2316
2317 if (!superclasses) {
2318 RUBY_ASSERT(!RCLASS_SUPER(klass));
2319 rb_raise(rb_eTypeError, "uninitialized class");
2320 }
2321
2322 if (!superclasses_depth) {
2323 return Qnil;
2324 }
2325 else {
2326 VALUE super = superclasses[superclasses_depth - 1];
2327 RUBY_ASSERT(RB_TYPE_P(super, T_CLASS));
2328 return super;
2329 }
2330}
2331
2332VALUE
2334{
2335 return RCLASS_SUPER(klass);
2336}
2337
2338static const char bad_instance_name[] = "'%1$s' is not allowed as an instance variable name";
2339static const char bad_class_name[] = "'%1$s' is not allowed as a class variable name";
2340static const char bad_const_name[] = "wrong constant name %1$s";
2341static const char bad_attr_name[] = "invalid attribute name '%1$s'";
2342#define wrong_constant_name bad_const_name
2343
2345#define id_for_var(obj, name, type) id_for_setter(obj, name, type, bad_##type##_name)
2347#define id_for_setter(obj, name, type, message) \
2348 check_setter_id(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message))
2349static ID
2350check_setter_id(VALUE obj, VALUE *pname,
2351 int (*valid_id_p)(ID), int (*valid_name_p)(VALUE),
2352 const char *message, size_t message_len)
2353{
2354 ID id = rb_check_id(pname);
2355 VALUE name = *pname;
2356
2357 if (id ? !valid_id_p(id) : !valid_name_p(name)) {
2358 rb_name_err_raise_str(rb_fstring_new(message, message_len),
2359 obj, name);
2360 }
2361 return id;
2362}
2363
2364static int
2365rb_is_attr_name(VALUE name)
2366{
2367 return rb_is_local_name(name) || rb_is_const_name(name);
2368}
2369
2370static int
2371rb_is_attr_id(ID id)
2372{
2373 return rb_is_local_id(id) || rb_is_const_id(id);
2374}
2375
2376static ID
2377id_for_attr(VALUE obj, VALUE name)
2378{
2379 ID id = id_for_var(obj, name, attr);
2380 if (!id) id = rb_intern_str(name);
2381 return id;
2382}
2383
2384/*
2385 * call-seq:
2386 * attr_reader(symbol, ...) -> array
2387 * attr(symbol, ...) -> array
2388 * attr_reader(string, ...) -> array
2389 * attr(string, ...) -> array
2390 *
2391 * Creates instance variables and corresponding methods that return the
2392 * value of each instance variable. Equivalent to calling
2393 * ``<code>attr</code><i>:name</i>'' on each name in turn.
2394 * String arguments are converted to symbols.
2395 * Returns an array of defined method names as symbols.
2396 */
2397
2398static VALUE
2399rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass)
2400{
2401 int i;
2402 VALUE names = rb_ary_new2(argc);
2403
2404 for (i=0; i<argc; i++) {
2405 ID id = id_for_attr(klass, argv[i]);
2406 rb_attr(klass, id, TRUE, FALSE, TRUE);
2407 rb_ary_push(names, ID2SYM(id));
2408 }
2409 return names;
2410}
2411
2416VALUE
2417rb_mod_attr(int argc, VALUE *argv, VALUE klass)
2418{
2419 if (argc == 2 && (argv[1] == Qtrue || argv[1] == Qfalse)) {
2420 ID id = id_for_attr(klass, argv[0]);
2421 VALUE names = rb_ary_new();
2422
2423 rb_category_warning(RB_WARN_CATEGORY_DEPRECATED, "optional boolean argument is obsoleted");
2424 rb_attr(klass, id, 1, RTEST(argv[1]), TRUE);
2425 rb_ary_push(names, ID2SYM(id));
2426 if (argv[1] == Qtrue) rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2427 return names;
2428 }
2429 return rb_mod_attr_reader(argc, argv, klass);
2430}
2431
2432/*
2433 * call-seq:
2434 * attr_writer(symbol, ...) -> array
2435 * attr_writer(string, ...) -> array
2436 *
2437 * Creates an accessor method to allow assignment to the attribute
2438 * <i>symbol</i><code>.id2name</code>.
2439 * String arguments are converted to symbols.
2440 * Returns an array of defined method names as symbols.
2441 */
2442
2443static VALUE
2444rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass)
2445{
2446 int i;
2447 VALUE names = rb_ary_new2(argc);
2448
2449 for (i=0; i<argc; i++) {
2450 ID id = id_for_attr(klass, argv[i]);
2451 rb_attr(klass, id, FALSE, TRUE, TRUE);
2452 rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2453 }
2454 return names;
2455}
2456
2457/*
2458 * call-seq:
2459 * attr_accessor(symbol, ...) -> array
2460 * attr_accessor(string, ...) -> array
2461 *
2462 * Defines a named attribute for this module, where the name is
2463 * <i>symbol.</i><code>id2name</code>, creating an instance variable
2464 * (<code>@name</code>) and a corresponding access method to read it.
2465 * Also creates a method called <code>name=</code> to set the attribute.
2466 * String arguments are converted to symbols.
2467 * Returns an array of defined method names as symbols.
2468 *
2469 * module Mod
2470 * attr_accessor(:one, :two) #=> [:one, :one=, :two, :two=]
2471 * end
2472 * Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
2473 */
2474
2475static VALUE
2476rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass)
2477{
2478 int i;
2479 VALUE names = rb_ary_new2(argc * 2);
2480
2481 for (i=0; i<argc; i++) {
2482 ID id = id_for_attr(klass, argv[i]);
2483
2484 rb_attr(klass, id, TRUE, TRUE, TRUE);
2485 rb_ary_push(names, ID2SYM(id));
2486 rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2487 }
2488 return names;
2489}
2490
2491/*
2492 * call-seq:
2493 * mod.const_get(sym, inherit=true) -> obj
2494 * mod.const_get(str, inherit=true) -> obj
2495 *
2496 * Checks for a constant with the given name in <i>mod</i>.
2497 * If +inherit+ is set, the lookup will also search
2498 * the ancestors (and +Object+ if <i>mod</i> is a +Module+).
2499 *
2500 * The value of the constant is returned if a definition is found,
2501 * otherwise a +NameError+ is raised.
2502 *
2503 * Math.const_get(:PI) #=> 3.14159265358979
2504 *
2505 * This method will recursively look up constant names if a namespaced
2506 * class name is provided. For example:
2507 *
2508 * module Foo; class Bar; end end
2509 * Object.const_get 'Foo::Bar'
2510 *
2511 * The +inherit+ flag is respected on each lookup. For example:
2512 *
2513 * module Foo
2514 * class Bar
2515 * VAL = 10
2516 * end
2517 *
2518 * class Baz < Bar; end
2519 * end
2520 *
2521 * Object.const_get 'Foo::Baz::VAL' # => 10
2522 * Object.const_get 'Foo::Baz::VAL', false # => NameError
2523 *
2524 * If the argument is not a valid constant name a +NameError+ will be
2525 * raised with a warning "wrong constant name".
2526 *
2527 * Object.const_get 'foobar' #=> NameError: wrong constant name foobar
2528 *
2529 */
2530
2531static VALUE
2532rb_mod_const_get(int argc, VALUE *argv, VALUE mod)
2533{
2534 VALUE name, recur;
2535 rb_encoding *enc;
2536 const char *pbeg, *p, *path, *pend;
2537 ID id;
2538
2539 rb_check_arity(argc, 1, 2);
2540 name = argv[0];
2541 recur = (argc == 1) ? Qtrue : argv[1];
2542
2543 if (SYMBOL_P(name)) {
2544 if (!rb_is_const_sym(name)) goto wrong_name;
2545 id = rb_check_id(&name);
2546 if (!id) return rb_const_missing(mod, name);
2547 return RTEST(recur) ? rb_const_get(mod, id) : rb_const_get_at(mod, id);
2548 }
2549
2550 path = StringValuePtr(name);
2551 enc = rb_enc_get(name);
2552
2553 if (!rb_enc_asciicompat(enc)) {
2554 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2555 }
2556
2557 pbeg = p = path;
2558 pend = path + RSTRING_LEN(name);
2559
2560 if (p >= pend || !*p) {
2561 goto wrong_name;
2562 }
2563
2564 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2565 mod = rb_cObject;
2566 p += 2;
2567 pbeg = p;
2568 }
2569
2570 while (p < pend) {
2571 VALUE part;
2572 long len, beglen;
2573
2574 while (p < pend && *p != ':') p++;
2575
2576 if (pbeg == p) goto wrong_name;
2577
2578 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2579 beglen = pbeg-path;
2580
2581 if (p < pend && p[0] == ':') {
2582 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2583 p += 2;
2584 pbeg = p;
2585 }
2586
2587 if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2588 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2589 QUOTE(name));
2590 }
2591
2592 if (!id) {
2593 part = rb_str_subseq(name, beglen, len);
2594 OBJ_FREEZE(part);
2595 if (!rb_is_const_name(part)) {
2596 name = part;
2597 goto wrong_name;
2598 }
2599 else if (!rb_method_basic_definition_p(CLASS_OF(mod), id_const_missing)) {
2600 part = rb_str_intern(part);
2601 mod = rb_const_missing(mod, part);
2602 continue;
2603 }
2604 else {
2605 rb_mod_const_missing(mod, part);
2606 }
2607 }
2608 if (!rb_is_const_id(id)) {
2609 name = ID2SYM(id);
2610 goto wrong_name;
2611 }
2612#if 0
2613 mod = rb_const_get_0(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2614#else
2615 if (!RTEST(recur)) {
2616 mod = rb_const_get_at(mod, id);
2617 }
2618 else if (beglen == 0) {
2619 mod = rb_const_get(mod, id);
2620 }
2621 else {
2622 mod = rb_const_get_from(mod, id);
2623 }
2624#endif
2625 }
2626
2627 return mod;
2628
2629 wrong_name:
2630 rb_name_err_raise(wrong_constant_name, mod, name);
2632}
2633
2634/*
2635 * call-seq:
2636 * mod.const_set(sym, obj) -> obj
2637 * mod.const_set(str, obj) -> obj
2638 *
2639 * Sets the named constant to the given object, returning that object.
2640 * Creates a new constant if no constant with the given name previously
2641 * existed.
2642 *
2643 * Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714
2644 * Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968
2645 *
2646 * If +sym+ or +str+ is not a valid constant name a +NameError+ will be
2647 * raised with a warning "wrong constant name".
2648 *
2649 * Object.const_set('foobar', 42) #=> NameError: wrong constant name foobar
2650 *
2651 */
2652
2653static VALUE
2654rb_mod_const_set(VALUE mod, VALUE name, VALUE value)
2655{
2656 ID id = id_for_var(mod, name, const);
2657 if (!id) id = rb_intern_str(name);
2658 rb_const_set(mod, id, value);
2659
2660 return value;
2661}
2662
2663/*
2664 * call-seq:
2665 * mod.const_defined?(sym, inherit=true) -> true or false
2666 * mod.const_defined?(str, inherit=true) -> true or false
2667 *
2668 * Says whether _mod_ or its ancestors have a constant with the given name:
2669 *
2670 * Float.const_defined?(:EPSILON) #=> true, found in Float itself
2671 * Float.const_defined?("String") #=> true, found in Object (ancestor)
2672 * BasicObject.const_defined?(:Hash) #=> false
2673 *
2674 * If _mod_ is a +Module+, additionally +Object+ and its ancestors are checked:
2675 *
2676 * Math.const_defined?(:String) #=> true, found in Object
2677 *
2678 * In each of the checked classes or modules, if the constant is not present
2679 * but there is an autoload for it, +true+ is returned directly without
2680 * autoloading:
2681 *
2682 * module Admin
2683 * autoload :User, 'admin/user'
2684 * end
2685 * Admin.const_defined?(:User) #=> true
2686 *
2687 * If the constant is not found the callback +const_missing+ is *not* called
2688 * and the method returns +false+.
2689 *
2690 * If +inherit+ is false, the lookup only checks the constants in the receiver:
2691 *
2692 * IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor)
2693 * IO.const_defined?(:SYNC, false) #=> false, not found in IO itself
2694 *
2695 * In this case, the same logic for autoloading applies.
2696 *
2697 * If the argument is not a valid constant name a +NameError+ is raised with the
2698 * message "wrong constant name _name_":
2699 *
2700 * Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar
2701 *
2702 */
2703
2704static VALUE
2705rb_mod_const_defined(int argc, VALUE *argv, VALUE mod)
2706{
2707 VALUE name, recur;
2708 rb_encoding *enc;
2709 const char *pbeg, *p, *path, *pend;
2710 ID id;
2711
2712 rb_check_arity(argc, 1, 2);
2713 name = argv[0];
2714 recur = (argc == 1) ? Qtrue : argv[1];
2715
2716 if (SYMBOL_P(name)) {
2717 if (!rb_is_const_sym(name)) goto wrong_name;
2718 id = rb_check_id(&name);
2719 if (!id) return Qfalse;
2720 return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id);
2721 }
2722
2723 path = StringValuePtr(name);
2724 enc = rb_enc_get(name);
2725
2726 if (!rb_enc_asciicompat(enc)) {
2727 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2728 }
2729
2730 pbeg = p = path;
2731 pend = path + RSTRING_LEN(name);
2732
2733 if (p >= pend || !*p) {
2734 goto wrong_name;
2735 }
2736
2737 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2738 mod = rb_cObject;
2739 p += 2;
2740 pbeg = p;
2741 }
2742
2743 while (p < pend) {
2744 VALUE part;
2745 long len, beglen;
2746
2747 while (p < pend && *p != ':') p++;
2748
2749 if (pbeg == p) goto wrong_name;
2750
2751 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2752 beglen = pbeg-path;
2753
2754 if (p < pend && p[0] == ':') {
2755 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2756 p += 2;
2757 pbeg = p;
2758 }
2759
2760 if (!id) {
2761 part = rb_str_subseq(name, beglen, len);
2762 OBJ_FREEZE(part);
2763 if (!rb_is_const_name(part)) {
2764 name = part;
2765 goto wrong_name;
2766 }
2767 else {
2768 return Qfalse;
2769 }
2770 }
2771 if (!rb_is_const_id(id)) {
2772 name = ID2SYM(id);
2773 goto wrong_name;
2774 }
2775
2776#if 0
2777 mod = rb_const_search(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2778 if (UNDEF_P(mod)) return Qfalse;
2779#else
2780 if (!RTEST(recur)) {
2781 if (!rb_const_defined_at(mod, id))
2782 return Qfalse;
2783 if (p == pend) return Qtrue;
2784 mod = rb_const_get_at(mod, id);
2785 }
2786 else if (beglen == 0) {
2787 if (!rb_const_defined(mod, id))
2788 return Qfalse;
2789 if (p == pend) return Qtrue;
2790 mod = rb_const_get(mod, id);
2791 }
2792 else {
2793 if (!rb_const_defined_from(mod, id))
2794 return Qfalse;
2795 if (p == pend) return Qtrue;
2796 mod = rb_const_get_from(mod, id);
2797 }
2798#endif
2799
2800 if (p < pend && !RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2801 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2802 QUOTE(name));
2803 }
2804 }
2805
2806 return Qtrue;
2807
2808 wrong_name:
2809 rb_name_err_raise(wrong_constant_name, mod, name);
2811}
2812
2813/*
2814 * call-seq:
2815 * mod.const_source_location(sym, inherit=true) -> [String, Integer]
2816 * mod.const_source_location(str, inherit=true) -> [String, Integer]
2817 *
2818 * Returns the Ruby source filename and line number containing the definition
2819 * of the constant specified. If the named constant is not found, +nil+ is returned.
2820 * If the constant is found, but its source location can not be extracted
2821 * (constant is defined in C code), empty array is returned.
2822 *
2823 * _inherit_ specifies whether to lookup in <code>mod.ancestors</code> (+true+
2824 * by default).
2825 *
2826 * # test.rb:
2827 * class A # line 1
2828 * C1 = 1
2829 * C2 = 2
2830 * end
2831 *
2832 * module M # line 6
2833 * C3 = 3
2834 * end
2835 *
2836 * class B < A # line 10
2837 * include M
2838 * C4 = 4
2839 * end
2840 *
2841 * class A # continuation of A definition
2842 * C2 = 8 # constant redefinition; warned yet allowed
2843 * end
2844 *
2845 * p B.const_source_location('C4') # => ["test.rb", 12]
2846 * p B.const_source_location('C3') # => ["test.rb", 7]
2847 * p B.const_source_location('C1') # => ["test.rb", 2]
2848 *
2849 * p B.const_source_location('C3', false) # => nil -- don't lookup in ancestors
2850 *
2851 * p A.const_source_location('C2') # => ["test.rb", 16] -- actual (last) definition place
2852 *
2853 * p Object.const_source_location('B') # => ["test.rb", 10] -- top-level constant could be looked through Object
2854 * p Object.const_source_location('A') # => ["test.rb", 1] -- class reopening is NOT considered new definition
2855 *
2856 * p B.const_source_location('A') # => ["test.rb", 1] -- because Object is in ancestors
2857 * p M.const_source_location('A') # => ["test.rb", 1] -- Object is not ancestor, but additionally checked for modules
2858 *
2859 * p Object.const_source_location('A::C1') # => ["test.rb", 2] -- nesting is supported
2860 * p Object.const_source_location('String') # => [] -- constant is defined in C code
2861 *
2862 *
2863 */
2864static VALUE
2865rb_mod_const_source_location(int argc, VALUE *argv, VALUE mod)
2866{
2867 VALUE name, recur, loc = Qnil;
2868 rb_encoding *enc;
2869 const char *pbeg, *p, *path, *pend;
2870 ID id;
2871
2872 rb_check_arity(argc, 1, 2);
2873 name = argv[0];
2874 recur = (argc == 1) ? Qtrue : argv[1];
2875
2876 if (SYMBOL_P(name)) {
2877 if (!rb_is_const_sym(name)) goto wrong_name;
2878 id = rb_check_id(&name);
2879 if (!id) return Qnil;
2880 return RTEST(recur) ? rb_const_source_location(mod, id) : rb_const_source_location_at(mod, id);
2881 }
2882
2883 path = StringValuePtr(name);
2884 enc = rb_enc_get(name);
2885
2886 if (!rb_enc_asciicompat(enc)) {
2887 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2888 }
2889
2890 pbeg = p = path;
2891 pend = path + RSTRING_LEN(name);
2892
2893 if (p >= pend || !*p) {
2894 goto wrong_name;
2895 }
2896
2897 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2898 mod = rb_cObject;
2899 p += 2;
2900 pbeg = p;
2901 }
2902
2903 while (p < pend) {
2904 VALUE part;
2905 long len, beglen;
2906
2907 while (p < pend && *p != ':') p++;
2908
2909 if (pbeg == p) goto wrong_name;
2910
2911 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2912 beglen = pbeg-path;
2913
2914 if (p < pend && p[0] == ':') {
2915 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2916 p += 2;
2917 pbeg = p;
2918 }
2919
2920 if (!id) {
2921 part = rb_str_subseq(name, beglen, len);
2922 OBJ_FREEZE(part);
2923 if (!rb_is_const_name(part)) {
2924 name = part;
2925 goto wrong_name;
2926 }
2927 else {
2928 return Qnil;
2929 }
2930 }
2931 if (!rb_is_const_id(id)) {
2932 name = ID2SYM(id);
2933 goto wrong_name;
2934 }
2935 if (p < pend) {
2936 if (RTEST(recur)) {
2937 mod = rb_const_get(mod, id);
2938 }
2939 else {
2940 mod = rb_const_get_at(mod, id);
2941 }
2942 if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2943 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2944 QUOTE(name));
2945 }
2946 }
2947 else {
2948 if (RTEST(recur)) {
2949 loc = rb_const_source_location(mod, id);
2950 }
2951 else {
2952 loc = rb_const_source_location_at(mod, id);
2953 }
2954 break;
2955 }
2956 recur = Qfalse;
2957 }
2958
2959 return loc;
2960
2961 wrong_name:
2962 rb_name_err_raise(wrong_constant_name, mod, name);
2964}
2965
2966/*
2967 * call-seq:
2968 * obj.instance_variable_get(symbol) -> obj
2969 * obj.instance_variable_get(string) -> obj
2970 *
2971 * Returns the value of the given instance variable, or nil if the
2972 * instance variable is not set. The <code>@</code> part of the
2973 * variable name should be included for regular instance
2974 * variables. Throws a NameError exception if the
2975 * supplied symbol is not valid as an instance variable name.
2976 * String arguments are converted to symbols.
2977 *
2978 * class Fred
2979 * def initialize(p1, p2)
2980 * @a, @b = p1, p2
2981 * end
2982 * end
2983 * fred = Fred.new('cat', 99)
2984 * fred.instance_variable_get(:@a) #=> "cat"
2985 * fred.instance_variable_get("@b") #=> 99
2986 */
2987
2988static VALUE
2989rb_obj_ivar_get(VALUE obj, VALUE iv)
2990{
2991 ID id = id_for_var(obj, iv, instance);
2992
2993 if (!id) {
2994 return Qnil;
2995 }
2996 return rb_ivar_get(obj, id);
2997}
2998
2999/*
3000 * call-seq:
3001 * obj.instance_variable_set(symbol, obj) -> obj
3002 * obj.instance_variable_set(string, obj) -> obj
3003 *
3004 * Sets the instance variable named by <i>symbol</i> to the given
3005 * object. This may circumvent the encapsulation intended by
3006 * the author of the class, so it should be used with care.
3007 * The variable does not have to exist prior to this call.
3008 * If the instance variable name is passed as a string, that string
3009 * is converted to a symbol.
3010 *
3011 * class Fred
3012 * def initialize(p1, p2)
3013 * @a, @b = p1, p2
3014 * end
3015 * end
3016 * fred = Fred.new('cat', 99)
3017 * fred.instance_variable_set(:@a, 'dog') #=> "dog"
3018 * fred.instance_variable_set(:@c, 'cat') #=> "cat"
3019 * fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
3020 */
3021
3022static VALUE
3023rb_obj_ivar_set_m(VALUE obj, VALUE iv, VALUE val)
3024{
3025 ID id = id_for_var(obj, iv, instance);
3026 if (!id) id = rb_intern_str(iv);
3027 return rb_ivar_set(obj, id, val);
3028}
3029
3030/*
3031 * call-seq:
3032 * obj.instance_variable_defined?(symbol) -> true or false
3033 * obj.instance_variable_defined?(string) -> true or false
3034 *
3035 * Returns <code>true</code> if the given instance variable is
3036 * defined in <i>obj</i>.
3037 * String arguments are converted to symbols.
3038 *
3039 * class Fred
3040 * def initialize(p1, p2)
3041 * @a, @b = p1, p2
3042 * end
3043 * end
3044 * fred = Fred.new('cat', 99)
3045 * fred.instance_variable_defined?(:@a) #=> true
3046 * fred.instance_variable_defined?("@b") #=> true
3047 * fred.instance_variable_defined?("@c") #=> false
3048 */
3049
3050static VALUE
3051rb_obj_ivar_defined(VALUE obj, VALUE iv)
3052{
3053 ID id = id_for_var(obj, iv, instance);
3054
3055 if (!id) {
3056 return Qfalse;
3057 }
3058 return rb_ivar_defined(obj, id);
3059}
3060
3061/*
3062 * call-seq:
3063 * mod.class_variable_get(symbol) -> obj
3064 * mod.class_variable_get(string) -> obj
3065 *
3066 * Returns the value of the given class variable (or throws a
3067 * NameError exception). The <code>@@</code> part of the
3068 * variable name should be included for regular class variables.
3069 * String arguments are converted to symbols.
3070 *
3071 * class Fred
3072 * @@foo = 99
3073 * end
3074 * Fred.class_variable_get(:@@foo) #=> 99
3075 */
3076
3077static VALUE
3078rb_mod_cvar_get(VALUE obj, VALUE iv)
3079{
3080 ID id = id_for_var(obj, iv, class);
3081
3082 if (!id) {
3083 rb_name_err_raise("uninitialized class variable %1$s in %2$s",
3084 obj, iv);
3085 }
3086 return rb_cvar_get(obj, id);
3087}
3088
3089/*
3090 * call-seq:
3091 * obj.class_variable_set(symbol, obj) -> obj
3092 * obj.class_variable_set(string, obj) -> obj
3093 *
3094 * Sets the class variable named by <i>symbol</i> to the given
3095 * object.
3096 * If the class variable name is passed as a string, that string
3097 * is converted to a symbol.
3098 *
3099 * class Fred
3100 * @@foo = 99
3101 * def foo
3102 * @@foo
3103 * end
3104 * end
3105 * Fred.class_variable_set(:@@foo, 101) #=> 101
3106 * Fred.new.foo #=> 101
3107 */
3108
3109static VALUE
3110rb_mod_cvar_set(VALUE obj, VALUE iv, VALUE val)
3111{
3112 ID id = id_for_var(obj, iv, class);
3113 if (!id) id = rb_intern_str(iv);
3114 rb_cvar_set(obj, id, val);
3115 return val;
3116}
3117
3118/*
3119 * call-seq:
3120 * obj.class_variable_defined?(symbol) -> true or false
3121 * obj.class_variable_defined?(string) -> true or false
3122 *
3123 * Returns <code>true</code> if the given class variable is defined
3124 * in <i>obj</i>.
3125 * String arguments are converted to symbols.
3126 *
3127 * class Fred
3128 * @@foo = 99
3129 * end
3130 * Fred.class_variable_defined?(:@@foo) #=> true
3131 * Fred.class_variable_defined?(:@@bar) #=> false
3132 */
3133
3134static VALUE
3135rb_mod_cvar_defined(VALUE obj, VALUE iv)
3136{
3137 ID id = id_for_var(obj, iv, class);
3138
3139 if (!id) {
3140 return Qfalse;
3141 }
3142 return rb_cvar_defined(obj, id);
3143}
3144
3145/*
3146 * call-seq:
3147 * mod.singleton_class? -> true or false
3148 *
3149 * Returns <code>true</code> if <i>mod</i> is a singleton class or
3150 * <code>false</code> if it is an ordinary class or module.
3151 *
3152 * class C
3153 * end
3154 * C.singleton_class? #=> false
3155 * C.singleton_class.singleton_class? #=> true
3156 */
3157
3158static VALUE
3159rb_mod_singleton_p(VALUE klass)
3160{
3161 return RBOOL(RCLASS_SINGLETON_P(klass));
3162}
3163
3165static const struct conv_method_tbl {
3166 const char method[6];
3167 unsigned short id;
3168} conv_method_names[] = {
3169#define M(n) {#n, (unsigned short)idTo_##n}
3170 M(int),
3171 M(ary),
3172 M(str),
3173 M(sym),
3174 M(hash),
3175 M(proc),
3176 M(io),
3177 M(a),
3178 M(s),
3179 M(i),
3180 M(f),
3181 M(r),
3182#undef M
3183};
3184#define IMPLICIT_CONVERSIONS 7
3185
3186static int
3187conv_method_index(const char *method)
3188{
3189 static const char prefix[] = "to_";
3190
3191 if (strncmp(prefix, method, sizeof(prefix)-1) == 0) {
3192 const char *const meth = &method[sizeof(prefix)-1];
3193 int i;
3194 for (i=0; i < numberof(conv_method_names); i++) {
3195 if (conv_method_names[i].method[0] == meth[0] &&
3196 strcmp(conv_method_names[i].method, meth) == 0) {
3197 return i;
3198 }
3199 }
3200 }
3201 return numberof(conv_method_names);
3202}
3203
3204static VALUE
3205convert_type_with_id(VALUE val, const char *tname, ID method, int raise, int index)
3206{
3207 VALUE r = rb_check_funcall(val, method, 0, 0);
3208 if (UNDEF_P(r)) {
3209 if (raise) {
3210 if ((index < 0 ? conv_method_index(rb_id2name(method)) : index) < IMPLICIT_CONVERSIONS) {
3211 rb_no_implicit_conversion(val, tname);
3212 }
3213 else {
3214 rb_cant_convert(val, tname);
3215 }
3216 }
3217 return Qnil;
3218 }
3219 return r;
3220}
3221
3222static VALUE
3223convert_type(VALUE val, const char *tname, const char *method, int raise)
3224{
3225 int i = conv_method_index(method);
3226 ID m = i < numberof(conv_method_names) ?
3227 conv_method_names[i].id : rb_intern(method);
3228 return convert_type_with_id(val, tname, m, raise, i);
3229}
3230
3231VALUE
3232rb_convert_type(VALUE val, int type, const char *tname, const char *method)
3233{
3234 VALUE v;
3235
3236 if (TYPE(val) == type) return val;
3237 v = convert_type(val, tname, method, TRUE);
3238 if (TYPE(v) != type) {
3239 rb_cant_convert_invalid_return(val, tname, method, v);
3240 }
3241 return v;
3242}
3243
3245VALUE
3246rb_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
3247{
3248 VALUE v;
3249
3250 if (TYPE(val) == type) return val;
3251 v = convert_type_with_id(val, tname, method, TRUE, -1);
3252 if (TYPE(v) != type) {
3253 rb_cant_convert_invalid_return(val, tname, rb_id2name(method), v);
3254 }
3255 return v;
3256}
3257
3258VALUE
3259rb_check_convert_type(VALUE val, int type, const char *tname, const char *method)
3260{
3261 VALUE v;
3262
3263 /* always convert T_DATA */
3264 if (TYPE(val) == type && type != T_DATA) return val;
3265 v = convert_type(val, tname, method, FALSE);
3266 if (NIL_P(v)) return Qnil;
3267 if (TYPE(v) != type) {
3268 rb_cant_convert_invalid_return(val, tname, method, v);
3269 }
3270 return v;
3271}
3272
3274VALUE
3275rb_check_convert_type_with_id_slow(VALUE val, int type, const char *tname, ID method)
3276{
3277 VALUE v = convert_type_with_id(val, tname, method, FALSE, -1);
3278 if (NIL_P(v)) return Qnil;
3279 if (TYPE(v) != type) {
3280 rb_cant_convert_invalid_return(val, tname, rb_id2name(method), v);
3281 }
3282 return v;
3283}
3284
3285#define try_to_int(val, mid, raise) \
3286 convert_type_with_id(val, "Integer", mid, raise, -1)
3287
3288ALWAYS_INLINE(static VALUE rb_to_integer_with_id_exception(VALUE val, const char *method, ID mid, int raise));
3289/* Integer specific rb_check_convert_type_with_id */
3290static inline VALUE
3291rb_to_integer_with_id_exception(VALUE val, const char *method, ID mid, int raise)
3292{
3293 // We need to pop the lazily pushed frame when not raising an exception.
3294 rb_control_frame_t *current_cfp;
3295 VALUE v;
3296
3297 if (RB_INTEGER_TYPE_P(val)) return val;
3298 current_cfp = GET_EC()->cfp;
3299 rb_yjit_lazy_push_frame(GET_EC()->cfp->pc);
3300 v = try_to_int(val, mid, raise);
3301 if (!raise && NIL_P(v)) {
3302 GET_EC()->cfp = current_cfp;
3303 return Qnil;
3304 }
3305 if (!RB_INTEGER_TYPE_P(v)) {
3306 rb_cant_convert_invalid_return(val, "Integer", method, v);
3307 }
3308 GET_EC()->cfp = current_cfp;
3309 return v;
3310}
3311#define rb_to_integer(val, method, mid) \
3312 rb_to_integer_with_id_exception(val, method, mid, TRUE)
3313
3314VALUE
3315rb_check_to_integer(VALUE val, const char *method)
3316{
3317 VALUE v;
3318
3319 if (RB_INTEGER_TYPE_P(val)) return val;
3320 v = convert_type(val, "Integer", method, FALSE);
3321 if (!RB_INTEGER_TYPE_P(v)) {
3322 return Qnil;
3323 }
3324 return v;
3325}
3326
3327VALUE
3329{
3330 return rb_to_integer(val, "to_int", idTo_int);
3331}
3332
3333VALUE
3335{
3336 if (RB_INTEGER_TYPE_P(val)) return val;
3337 val = try_to_int(val, idTo_int, FALSE);
3338 if (RB_INTEGER_TYPE_P(val)) return val;
3339 return Qnil;
3340}
3341
3342static VALUE
3343rb_check_to_i(VALUE val)
3344{
3345 if (RB_INTEGER_TYPE_P(val)) return val;
3346 val = try_to_int(val, idTo_i, FALSE);
3347 if (RB_INTEGER_TYPE_P(val)) return val;
3348 return Qnil;
3349}
3350
3351static VALUE
3352rb_convert_to_integer(VALUE val, int base, int raise_exception)
3353{
3354 VALUE tmp;
3355
3356 if (base) {
3357 tmp = rb_check_string_type(val);
3358
3359 if (! NIL_P(tmp)) {
3360 val = tmp;
3361 }
3362 else if (! raise_exception) {
3363 return Qnil;
3364 }
3365 else {
3366 rb_raise(rb_eArgError, "base specified for non string value");
3367 }
3368 }
3369 if (RB_FLOAT_TYPE_P(val)) {
3370 double f = RFLOAT_VALUE(val);
3371 if (!raise_exception && !isfinite(f)) return Qnil;
3372 if (FIXABLE(f)) return LONG2FIX((long)f);
3373 return rb_dbl2big(f);
3374 }
3375 else if (RB_INTEGER_TYPE_P(val)) {
3376 return val;
3377 }
3378 else if (RB_TYPE_P(val, T_STRING)) {
3379 return rb_str_convert_to_inum(val, base, TRUE, raise_exception);
3380 }
3381 else if (NIL_P(val)) {
3382 if (!raise_exception) return Qnil;
3383 rb_cant_convert(val, "Integer");
3384 }
3385
3386 tmp = rb_protect(rb_check_to_int, val, NULL);
3387 if (RB_INTEGER_TYPE_P(tmp)) return tmp;
3388 rb_set_errinfo(Qnil);
3389 if (!NIL_P(tmp = rb_check_string_type(val))) {
3390 return rb_str_convert_to_inum(tmp, base, TRUE, raise_exception);
3391 }
3392
3393 if (!raise_exception) {
3394 VALUE result = rb_protect(rb_check_to_i, val, NULL);
3395 rb_set_errinfo(Qnil);
3396 return result;
3397 }
3398
3399 return rb_to_integer(val, "to_i", idTo_i);
3400}
3401
3402VALUE
3404{
3405 return rb_convert_to_integer(val, 0, TRUE);
3406}
3407
3408VALUE
3409rb_check_integer_type(VALUE val)
3410{
3411 return rb_to_integer_with_id_exception(val, "to_int", idTo_int, FALSE);
3412}
3413
3414int
3415rb_bool_expected(VALUE obj, const char *flagname, int raise)
3416{
3417 switch (obj) {
3418 case Qtrue:
3419 return TRUE;
3420 case Qfalse:
3421 return FALSE;
3422 default: {
3423 static const char message[] = "expected true or false as %s: %+"PRIsVALUE;
3424 if (raise) {
3425 rb_raise(rb_eArgError, message, flagname, obj);
3426 }
3427 rb_warning(message, flagname, obj);
3428 return !NIL_P(obj);
3429 }
3430 }
3431}
3432
3433int
3434rb_opts_exception_p(VALUE opts, int default_value)
3435{
3436 static const ID kwds[1] = {idException};
3437 VALUE exception;
3438 if (rb_get_kwargs(opts, kwds, 0, 1, &exception))
3439 return rb_bool_expected(exception, "exception", TRUE);
3440 return default_value;
3441}
3442
3443static VALUE
3444rb_f_integer1(rb_execution_context_t *ec, VALUE obj, VALUE arg)
3445{
3446 return rb_convert_to_integer(arg, 0, TRUE);
3447}
3448
3449static VALUE
3450rb_f_integer(rb_execution_context_t *ec, VALUE obj, VALUE arg, VALUE base, VALUE exception)
3451{
3452 int exc = rb_bool_expected(exception, "exception", TRUE);
3453 return rb_convert_to_integer(arg, NUM2INT(base), exc);
3454}
3455
3456static bool
3457is_digit_char(unsigned char c, int base)
3458{
3460 return (i >= 0 && i < base);
3461}
3462
3463static double
3464rb_cstr_to_dbl_raise(const char *p, rb_encoding *enc, int badcheck, int raise, int *error)
3465{
3466 const char *q;
3467 char *end;
3468 double d;
3469 const char *ellipsis = "";
3470 int w;
3471 enum {max_width = 20};
3472#define OutOfRange() ((end - p > max_width) ? \
3473 (w = max_width, ellipsis = "...") : \
3474 (w = (int)(end - p), ellipsis = ""))
3475 /* p...end has been parsed with strtod, should be ASCII-only */
3476
3477 if (!p) return 0.0;
3478 q = p;
3479 while (ISSPACE(*p)) p++;
3480
3481 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3482 return 0.0;
3483 }
3484
3485 d = strtod(p, &end);
3486 if (errno == ERANGE) {
3487 OutOfRange();
3488 errno = 0;
3489 }
3490 if (p == end) {
3491 if (badcheck) {
3492 goto bad;
3493 }
3494 return d;
3495 }
3496 if (*end) {
3497 char buf[DBL_DIG * 4 + 10];
3498 char *n = buf;
3499 char *const init_e = buf + DBL_DIG * 4;
3500 char *e = init_e;
3501 char prev = 0;
3502 int dot_seen = FALSE;
3503 int base = 10;
3504 char exp_letter = 'e';
3505
3506 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3507 if (*p == '0') {
3508 prev = *n++ = '0';
3509 switch (*++p) {
3510 case 'x': case 'X':
3511 prev = *n++ = 'x';
3512 base = 16;
3513 exp_letter = 'p';
3514 if (*++p != '0') break;
3515 /* fallthrough */
3516 case '0': /* squeeze successive zeros */
3517 while (*++p == '0');
3518 break;
3519 }
3520 }
3521 while (p < end && n < e) prev = *n++ = *p++;
3522 while (*p) {
3523 if (*p == '_') {
3524 /* remove an underscore between digits */
3525 if (n == buf ||
3526 !is_digit_char(prev, base) ||
3527 !is_digit_char(*++p, base)) {
3528 if (badcheck) goto bad;
3529 break;
3530 }
3531 }
3532 prev = *p++;
3533 if (e == init_e && (rb_tolower(prev) == exp_letter)) {
3534 e = buf + sizeof(buf) - 1;
3535 *n++ = prev;
3536 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3537 if (*p == '0') {
3538 prev = *n++ = '0';
3539 while (*++p == '0');
3540 }
3541
3542 /* reset base to decimal for underscore check of
3543 * binary exponent part */
3544 base = 10;
3545 continue;
3546 }
3547 else if (ISSPACE(prev)) {
3548 while (ISSPACE(*p)) ++p;
3549 if (*p) {
3550 if (badcheck) goto bad;
3551 break;
3552 }
3553 }
3554 else if (prev == '.' ? dot_seen++ : !is_digit_char(prev, base)) {
3555 if (badcheck) goto bad;
3556 break;
3557 }
3558 if (n < e) *n++ = prev;
3559 }
3560 *n = '\0';
3561 p = buf;
3562
3563 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3564 return 0.0;
3565 }
3566
3567 d = strtod(p, &end);
3568 if (errno == ERANGE) {
3569 OutOfRange();
3570 errno = 0;
3571 }
3572 if (badcheck) {
3573 if (!end || p == end) goto bad;
3574 while (*end && ISSPACE(*end)) end++;
3575 if (*end) goto bad;
3576 }
3577 }
3578 if (errno == ERANGE) {
3579 errno = 0;
3580 OutOfRange();
3581 rb_raise(rb_eArgError, "Float %.*s%s out of range", w, q, ellipsis);
3582 }
3583 return d;
3584
3585 bad:
3586 if (raise) {
3587 VALUE s = rb_enc_str_new_cstr(q, enc);
3588 rb_raise(rb_eArgError, "invalid value for Float(): %+"PRIsVALUE, s);
3589 UNREACHABLE_RETURN(nan(""));
3590 }
3591 else {
3592 if (error) *error = 1;
3593 return 0.0;
3594 }
3595}
3596
3597double
3598rb_cstr_to_dbl(const char *p, int badcheck)
3599{
3600 return rb_cstr_to_dbl_raise(p, NULL, badcheck, TRUE, NULL);
3601}
3602
3603static double
3604rb_str_to_dbl_raise(VALUE str, int badcheck, int raise, int *error)
3605{
3606 char *s;
3607 long len;
3608 double ret;
3609 VALUE v = 0;
3610
3611 StringValue(str);
3613 s = RSTRING_PTR(str);
3614 len = RSTRING_LEN(str);
3615 if (s) {
3616 if (badcheck && memchr(s, '\0', len)) {
3617 if (raise)
3618 rb_raise(rb_eArgError, "string for Float contains null byte");
3619 else {
3620 if (error) *error = 1;
3621 return 0.0;
3622 }
3623 }
3624 if (s[len]) { /* no sentinel somehow */
3625 char *p = ALLOCV(v, (size_t)len + 1);
3626 MEMCPY(p, s, char, len);
3627 p[len] = '\0';
3628 s = p;
3629 }
3630 }
3631 ret = rb_cstr_to_dbl_raise(s, rb_enc_get(str), badcheck, raise, error);
3632 if (v)
3633 ALLOCV_END(v);
3634 else
3635 RB_GC_GUARD(str);
3636 return ret;
3637}
3638
3639FUNC_MINIMIZED(double rb_str_to_dbl(VALUE str, int badcheck));
3640
3641double
3642rb_str_to_dbl(VALUE str, int badcheck)
3643{
3644 return rb_str_to_dbl_raise(str, badcheck, TRUE, NULL);
3645}
3646
3648#define fix2dbl_without_to_f(x) (double)FIX2LONG(x)
3649#define big2dbl_without_to_f(x) rb_big2dbl(x)
3650#define int2dbl_without_to_f(x) \
3651 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : big2dbl_without_to_f(x))
3652#define num2dbl_without_to_f(x) \
3653 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : \
3654 RB_BIGNUM_TYPE_P(x) ? big2dbl_without_to_f(x) : \
3655 (Check_Type(x, T_FLOAT), RFLOAT_VALUE(x)))
3656static inline double
3657rat2dbl_without_to_f(VALUE x)
3658{
3659 VALUE num = rb_rational_num(x);
3660 VALUE den = rb_rational_den(x);
3661 return num2dbl_without_to_f(num) / num2dbl_without_to_f(den);
3662}
3663
3664#define special_const_to_float(val, pre, post) \
3665 switch (val) { \
3666 case Qnil: \
3667 rb_raise_static(rb_eTypeError, pre "nil" post); \
3668 case Qtrue: \
3669 rb_raise_static(rb_eTypeError, pre "true" post); \
3670 case Qfalse: \
3671 rb_raise_static(rb_eTypeError, pre "false" post); \
3672 }
3675static int
3676to_float(VALUE *valp, int raise_exception)
3677{
3678 VALUE val = *valp;
3679 if (SPECIAL_CONST_P(val)) {
3680 if (FIXNUM_P(val)) {
3681 *valp = DBL2NUM(fix2dbl_without_to_f(val));
3682 return T_FLOAT;
3683 }
3684 else if (FLONUM_P(val)) {
3685 return T_FLOAT;
3686 }
3687 else if (raise_exception) {
3688 rb_cant_convert(val, "Float");
3689 }
3690 }
3691 else {
3692 int type = BUILTIN_TYPE(val);
3693 switch (type) {
3694 case T_FLOAT:
3695 return T_FLOAT;
3696 case T_BIGNUM:
3697 *valp = DBL2NUM(big2dbl_without_to_f(val));
3698 return T_FLOAT;
3699 case T_RATIONAL:
3700 *valp = DBL2NUM(rat2dbl_without_to_f(val));
3701 return T_FLOAT;
3702 case T_STRING:
3703 return T_STRING;
3704 }
3705 }
3706 return T_NONE;
3707}
3708
3709static VALUE
3710convert_type_to_float_protected(VALUE val)
3711{
3712 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3713}
3714
3715static VALUE
3716rb_convert_to_float(VALUE val, int raise_exception)
3717{
3718 switch (to_float(&val, raise_exception)) {
3719 case T_FLOAT:
3720 return val;
3721 case T_STRING:
3722 if (!raise_exception) {
3723 int e = 0;
3724 double x = rb_str_to_dbl_raise(val, TRUE, raise_exception, &e);
3725 return e ? Qnil : DBL2NUM(x);
3726 }
3727 return DBL2NUM(rb_str_to_dbl(val, TRUE));
3728 case T_NONE:
3729 if (SPECIAL_CONST_P(val) && !raise_exception)
3730 return Qnil;
3731 }
3732
3733 if (!raise_exception) {
3734 int state;
3735 VALUE result = rb_protect(convert_type_to_float_protected, val, &state);
3736 if (state) rb_set_errinfo(Qnil);
3737 return result;
3738 }
3739
3740 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3741}
3742
3743FUNC_MINIMIZED(VALUE rb_Float(VALUE val));
3744
3745VALUE
3747{
3748 return rb_convert_to_float(val, TRUE);
3749}
3750
3751static VALUE
3752rb_f_float1(rb_execution_context_t *ec, VALUE obj, VALUE arg)
3753{
3754 return rb_convert_to_float(arg, TRUE);
3755}
3756
3757static VALUE
3758rb_f_float(rb_execution_context_t *ec, VALUE obj, VALUE arg, VALUE opts)
3759{
3760 int exception = rb_bool_expected(opts, "exception", TRUE);
3761 return rb_convert_to_float(arg, exception);
3762}
3763
3764static VALUE
3765numeric_to_float(VALUE val)
3766{
3767 if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3768 rb_cant_convert(val, "Float");
3769 }
3770 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3771}
3772
3773VALUE
3775{
3776 switch (to_float(&val, TRUE)) {
3777 case T_FLOAT:
3778 return val;
3779 }
3780 return numeric_to_float(val);
3781}
3782
3783VALUE
3785{
3786 if (RB_FLOAT_TYPE_P(val)) return val;
3787 if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3788 return Qnil;
3789 }
3790 return rb_check_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3791}
3792
3793static inline int
3794basic_to_f_p(VALUE klass)
3795{
3796 return rb_method_basic_definition_p(klass, id_to_f);
3797}
3798
3800double
3801rb_num_to_dbl(VALUE val)
3802{
3803 if (SPECIAL_CONST_P(val)) {
3804 if (FIXNUM_P(val)) {
3805 if (basic_to_f_p(rb_cInteger))
3806 return fix2dbl_without_to_f(val);
3807 }
3808 else if (FLONUM_P(val)) {
3809 return rb_float_flonum_value(val);
3810 }
3811 else {
3812 rb_cant_convert(val, "Float");
3813 }
3814 }
3815 else {
3816 switch (BUILTIN_TYPE(val)) {
3817 case T_FLOAT:
3818 return rb_float_noflonum_value(val);
3819 case T_BIGNUM:
3820 if (basic_to_f_p(rb_cInteger))
3821 return big2dbl_without_to_f(val);
3822 break;
3823 case T_RATIONAL:
3824 if (basic_to_f_p(rb_cRational))
3825 return rat2dbl_without_to_f(val);
3826 break;
3827 default:
3828 break;
3829 }
3830 }
3831 val = numeric_to_float(val);
3832 return RFLOAT_VALUE(val);
3833}
3834
3835double
3837{
3838 if (SPECIAL_CONST_P(val)) {
3839 if (FIXNUM_P(val)) {
3840 return fix2dbl_without_to_f(val);
3841 }
3842 else if (FLONUM_P(val)) {
3843 return rb_float_flonum_value(val);
3844 }
3845 else {
3846 rb_no_implicit_conversion(val, "Float");
3847 }
3848 }
3849 else {
3850 switch (BUILTIN_TYPE(val)) {
3851 case T_FLOAT:
3852 return rb_float_noflonum_value(val);
3853 case T_BIGNUM:
3854 return big2dbl_without_to_f(val);
3855 case T_RATIONAL:
3856 return rat2dbl_without_to_f(val);
3857 case T_STRING:
3858 rb_no_implicit_conversion(val, "Float");
3859 default:
3860 break;
3861 }
3862 }
3863 val = rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3864 return RFLOAT_VALUE(val);
3865}
3866
3867VALUE
3869{
3870 VALUE tmp = rb_check_string_type(val);
3871 if (NIL_P(tmp))
3872 tmp = rb_convert_type_with_id(val, T_STRING, "String", idTo_s);
3873 return tmp;
3874}
3875
3876
3877/*
3878 * call-seq:
3879 * String(object) -> object or new_string
3880 *
3881 * Returns a string converted from +object+.
3882 *
3883 * Tries to convert +object+ to a string
3884 * using +to_str+ first and +to_s+ second:
3885 *
3886 * String([0, 1, 2]) # => "[0, 1, 2]"
3887 * String(0..5) # => "0..5"
3888 * String({foo: 0, bar: 1}) # => "{foo: 0, bar: 1}"
3889 *
3890 * Raises +TypeError+ if +object+ cannot be converted to a string.
3891 */
3892
3893static VALUE
3894rb_f_string(VALUE obj, VALUE arg)
3895{
3896 return rb_String(arg);
3897}
3898
3899VALUE
3901{
3902 VALUE tmp = rb_check_array_type(val);
3903
3904 if (NIL_P(tmp)) {
3905 tmp = rb_check_to_array(val);
3906 if (NIL_P(tmp)) {
3907 return rb_ary_new3(1, val);
3908 }
3909 }
3910 return tmp;
3911}
3912
3913/*
3914 * call-seq:
3915 * Array(object) -> object or new_array
3916 *
3917 * Returns an array converted from +object+.
3918 *
3919 * Tries to convert +object+ to an array
3920 * using +to_ary+ first and +to_a+ second:
3921 *
3922 * Array([0, 1, 2]) # => [0, 1, 2]
3923 * Array({foo: 0, bar: 1}) # => [[:foo, 0], [:bar, 1]]
3924 * Array(0..4) # => [0, 1, 2, 3, 4]
3925 *
3926 * Returns +object+ in an array, <tt>[object]</tt>,
3927 * if +object+ cannot be converted:
3928 *
3929 * Array(:foo) # => [:foo]
3930 *
3931 */
3932
3933static VALUE
3934rb_f_array(VALUE obj, VALUE arg)
3935{
3936 return rb_Array(arg);
3937}
3938
3942VALUE
3944{
3945 VALUE tmp;
3946
3947 if (NIL_P(val)) return rb_hash_new_capa(0);
3948 tmp = rb_check_hash_type(val);
3949 if (NIL_P(tmp)) {
3950 if (RB_TYPE_P(val, T_ARRAY) && RARRAY_LEN(val) == 0)
3951 return rb_hash_new_capa(0);
3952 rb_cant_convert(val, "Hash");
3953 }
3954 return tmp;
3955}
3956
3957/*
3958 * call-seq:
3959 * Hash(object) -> object or new_hash
3960 *
3961 * Returns a hash converted from +object+.
3962 *
3963 * - If +object+ is:
3964 *
3965 * - A hash, returns +object+.
3966 * - An empty array or +nil+, returns an empty hash.
3967 *
3968 * - Otherwise, if <tt>object.to_hash</tt> returns a hash, returns that hash.
3969 * - Otherwise, returns TypeError.
3970 *
3971 * Examples:
3972 *
3973 * Hash({foo: 0, bar: 1}) # => {foo: 0, bar: 1}
3974 * Hash(nil) # => {}
3975 * Hash([]) # => {}
3976 *
3977 */
3978
3979static VALUE
3980rb_f_hash(VALUE obj, VALUE arg)
3981{
3982 return rb_Hash(arg);
3983}
3984
3986struct dig_method {
3987 VALUE klass;
3988 int basic;
3989};
3990
3991static ID id_dig;
3992
3993static int
3994dig_basic_p(VALUE obj, struct dig_method *cache)
3995{
3996 VALUE klass = RBASIC_CLASS(obj);
3997 if (klass != cache->klass) {
3998 cache->klass = klass;
3999 cache->basic = rb_method_basic_definition_p(klass, id_dig);
4000 }
4001 return cache->basic;
4002}
4003
4004static void
4005no_dig_method(int found, VALUE recv, ID mid, int argc, const VALUE *argv, VALUE data)
4006{
4007 if (!found) {
4008 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not have #dig method",
4009 CLASS_OF(data));
4010 }
4011}
4012
4014VALUE
4015rb_obj_dig(int argc, VALUE *argv, VALUE obj, VALUE notfound)
4016{
4017 struct dig_method hash = {Qnil}, ary = {Qnil}, strt = {Qnil};
4018
4019 for (; argc > 0; ++argv, --argc) {
4020 if (NIL_P(obj)) return notfound;
4021 if (!SPECIAL_CONST_P(obj)) {
4022 switch (BUILTIN_TYPE(obj)) {
4023 case T_HASH:
4024 if (dig_basic_p(obj, &hash)) {
4025 obj = rb_hash_aref(obj, *argv);
4026 continue;
4027 }
4028 break;
4029 case T_ARRAY:
4030 if (dig_basic_p(obj, &ary)) {
4031 obj = rb_ary_at(obj, *argv);
4032 continue;
4033 }
4034 break;
4035 case T_STRUCT:
4036 if (dig_basic_p(obj, &strt)) {
4037 obj = rb_struct_lookup(obj, *argv);
4038 continue;
4039 }
4040 break;
4041 default:
4042 break;
4043 }
4044 }
4045 return rb_check_funcall_with_hook_kw(obj, id_dig, argc, argv,
4046 no_dig_method, obj,
4048 }
4049 return obj;
4050}
4051
4052/*
4053 * call-seq:
4054 * sprintf(format_string *objects) -> string
4055 *
4056 * Returns the string resulting from formatting +objects+
4057 * into +format_string+.
4058 *
4059 * For details on +format_string+, see
4060 * {Format Specifications}[rdoc-ref:language/format_specifications.rdoc].
4061 */
4062
4063static VALUE
4064f_sprintf(int c, const VALUE *v, VALUE _)
4065{
4066 return rb_f_sprintf(c, v);
4067}
4068
4069static VALUE
4070rb_f_loop_size(VALUE self, VALUE args, VALUE eobj)
4071{
4072 return DBL2NUM(HUGE_VAL);
4073}
4074
4075/*
4076 * Document-class: Class
4077 *
4078 * Classes in Ruby are first-class objects---each is an instance of
4079 * class Class.
4080 *
4081 * Typically, you create a new class by using:
4082 *
4083 * class Name
4084 * # some code describing the class behavior
4085 * end
4086 *
4087 * When a new class is created, an object of type Class is initialized and
4088 * assigned to a global constant (Name in this case).
4089 *
4090 * When <code>Name.new</code> is called to create a new object, the
4091 * #new method in Class is run by default.
4092 * This can be demonstrated by overriding #new in Class:
4093 *
4094 * class Class
4095 * alias old_new new
4096 * def new(*args)
4097 * print "Creating a new ", self.name, "\n"
4098 * old_new(*args)
4099 * end
4100 * end
4101 *
4102 * class Name
4103 * end
4104 *
4105 * n = Name.new
4106 *
4107 * <em>produces:</em>
4108 *
4109 * Creating a new Name
4110 *
4111 * Classes, modules, and objects are interrelated. In the diagram
4112 * that follows, the vertical arrows represent inheritance, and the
4113 * parentheses metaclasses. All metaclasses are instances
4114 * of the class `Class'.
4115 * +---------+ +-...
4116 * | | |
4117 * BasicObject-----|-->(BasicObject)-------|-...
4118 * ^ | ^ |
4119 * | | | |
4120 * Object---------|----->(Object)---------|-...
4121 * ^ | ^ |
4122 * | | | |
4123 * +-------+ | +--------+ |
4124 * | | | | | |
4125 * | Module-|---------|--->(Module)-|-...
4126 * | ^ | | ^ |
4127 * | | | | | |
4128 * | Class-|---------|---->(Class)-|-...
4129 * | ^ | | ^ |
4130 * | +---+ | +----+
4131 * | |
4132 * obj--->OtherClass---------->(OtherClass)-----------...
4133 *
4134 */
4135
4136
4137/*
4138 * Document-class: BasicObject
4139 *
4140 * +BasicObject+ is the parent class of all classes in Ruby.
4141 * In particular, +BasicObject+ is the parent class of class Object,
4142 * which is itself the default parent class of every Ruby class:
4143 *
4144 * class Foo; end
4145 * Foo.superclass # => Object
4146 * Object.superclass # => BasicObject
4147 *
4148 * +BasicObject+ is the only class that has no parent:
4149 *
4150 * BasicObject.superclass # => nil
4151 *
4152 * Class +BasicObject+ can be used to create an object hierarchy
4153 * (e.g., class Delegator) that is independent of Ruby's object hierarchy.
4154 * Such objects:
4155 *
4156 * - Do not have namespace "pollution" from the many methods
4157 * provided in class Object and its included module Kernel.
4158 * - Do not have definitions of common classes,
4159 * and so references to such common classes must be fully qualified
4160 * (+::String+, not +String+).
4161 *
4162 * A variety of strategies can be used to provide useful portions
4163 * of the Standard Library in subclasses of +BasicObject+:
4164 *
4165 * - The immediate subclass could <tt>include Kernel</tt>,
4166 * which would define methods such as +puts+, +exit+, etc.
4167 * - A custom Kernel-like module could be created and included.
4168 * - Delegation can be used via #method_missing:
4169 *
4170 * class MyObjectSystem < BasicObject
4171 * DELEGATE = [:puts, :p]
4172 *
4173 * def method_missing(name, *args, &block)
4174 * return super unless DELEGATE.include? name
4175 * ::Kernel.send(name, *args, &block)
4176 * end
4177 *
4178 * def respond_to_missing?(name, include_private = false)
4179 * DELEGATE.include?(name)
4180 * end
4181 * end
4182 *
4183 * === What's Here
4184 *
4185 * These are the methods defined for \BasicObject:
4186 *
4187 * - ::new: Returns a new \BasicObject instance.
4188 * - #!: Returns the boolean negation of +self+: +true+ or +false+.
4189 * - #!=: Returns whether +self+ and the given object are _not_ equal.
4190 * - #==: Returns whether +self+ and the given object are equivalent.
4191 * - #__id__: Returns the integer object identifier for +self+.
4192 * - #__send__: Calls the method identified by the given symbol.
4193 * - #equal?: Returns whether +self+ and the given object are the same object.
4194 * - #instance_eval: Evaluates the given string or block in the context of +self+.
4195 * - #instance_exec: Executes the given block in the context of +self+, passing the given arguments.
4196 * - #method_missing: Called when +self+ is called with a method it does not define.
4197 * - #singleton_method_added: Called when a singleton method is added to +self+.
4198 * - #singleton_method_removed: Called when a singleton method is removed from +self+.
4199 * - #singleton_method_undefined: Called when a singleton method is undefined in +self+.
4200 *
4201 */
4202
4203/* Document-class: Object
4204 *
4205 * Object is the default root of all Ruby objects. Object inherits from
4206 * BasicObject which allows creating alternate object hierarchies. Methods
4207 * on Object are available to all classes unless explicitly overridden.
4208 *
4209 * Object mixes in the Kernel module, making the built-in kernel functions
4210 * globally accessible. Although the instance methods of Object are defined
4211 * by the Kernel module, we have chosen to document them here for clarity.
4212 *
4213 * When referencing constants in classes inheriting from Object you do not
4214 * need to use the full namespace. For example, referencing +File+ inside
4215 * +YourClass+ will find the top-level File class.
4216 *
4217 * In the descriptions of Object's methods, the parameter <i>symbol</i> refers
4218 * to a symbol, which is either a quoted string or a Symbol (such as
4219 * <code>:name</code>).
4220 *
4221 * == What's Here
4222 *
4223 * First, what's elsewhere. Class \Object:
4224 *
4225 * - Inherits from {class BasicObject}[rdoc-ref:BasicObject@Whats+Here].
4226 * - Includes {module Kernel}[rdoc-ref:Kernel@Whats+Here].
4227 *
4228 * Here, class \Object provides methods for:
4229 *
4230 * - {Querying}[rdoc-ref:Object@Querying]
4231 * - {Instance Variables}[rdoc-ref:Object@Instance+Variables]
4232 * - {Other}[rdoc-ref:Object@Other]
4233 *
4234 * === Querying
4235 *
4236 * - #!~: Returns +true+ if +self+ does not match the given object,
4237 * otherwise +false+.
4238 * - #<=>: Returns 0 if +self+ and the given object +object+ are the same
4239 * object, or if <tt>self == object</tt>; otherwise returns +nil+.
4240 * - #===: Implements case equality, effectively the same as calling #==.
4241 * - #eql?: Implements hash equality, effectively the same as calling #==.
4242 * - #kind_of? (aliased as #is_a?): Returns whether given argument is an ancestor
4243 * of the singleton class of +self+.
4244 * - #instance_of?: Returns whether +self+ is an instance of the given class.
4245 * - #instance_variable_defined?: Returns whether the given instance variable
4246 * is defined in +self+.
4247 * - #method: Returns the +Method+ object for the given method in +self+.
4248 * - #methods: Returns an array of symbol names of public and protected methods
4249 * in +self+.
4250 * - #nil?: Returns +false+. (Only +nil+ responds +true+ to method <tt>nil?</tt>.)
4251 * - #object_id: Returns an integer corresponding to +self+ that is unique
4252 * for the current process
4253 * - #private_methods: Returns an array of the symbol names
4254 * of the private methods in +self+.
4255 * - #protected_methods: Returns an array of the symbol names
4256 * of the protected methods in +self+.
4257 * - #public_method: Returns the +Method+ object for the given public method in +self+.
4258 * - #public_methods: Returns an array of the symbol names
4259 * of the public methods in +self+.
4260 * - #respond_to?: Returns whether +self+ responds to the given method.
4261 * - #singleton_class: Returns the singleton class of +self+.
4262 * - #singleton_method: Returns the +Method+ object for the given singleton method
4263 * in +self+.
4264 * - #singleton_methods: Returns an array of the symbol names
4265 * of the singleton methods in +self+.
4266 *
4267 * - #define_singleton_method: Defines a singleton method in +self+
4268 * for the given symbol method-name and block or proc.
4269 * - #extend: Includes the given modules in the singleton class of +self+.
4270 * - #public_send: Calls the given public method in +self+ with the given argument.
4271 * - #send: Calls the given method in +self+ with the given argument.
4272 *
4273 * === Instance Variables
4274 *
4275 * - #instance_variable_get: Returns the value of the given instance variable
4276 * in +self+, or +nil+ if the instance variable is not set.
4277 * - #instance_variable_set: Sets the value of the given instance variable in +self+
4278 * to the given object.
4279 * - #instance_variables: Returns an array of the symbol names
4280 * of the instance variables in +self+.
4281 * - #remove_instance_variable: Removes the named instance variable from +self+.
4282 *
4283 * === Other
4284 *
4285 * - #clone: Returns a shallow copy of +self+, including singleton class
4286 * and frozen state.
4287 * - #define_singleton_method: Defines a singleton method in +self+
4288 * for the given symbol method-name and block or proc.
4289 * - #display: Prints +self+ to the given IO stream or <tt>$stdout</tt>.
4290 * - #dup: Returns a shallow unfrozen copy of +self+.
4291 * - #enum_for (aliased as #to_enum): Returns an Enumerator for +self+
4292 * using the using the given method, arguments, and block.
4293 * - #extend: Includes the given modules in the singleton class of +self+.
4294 * - #freeze: Prevents further modifications to +self+.
4295 * - #hash: Returns the integer hash value for +self+.
4296 * - #inspect: Returns a human-readable string representation of +self+.
4297 * - #itself: Returns +self+.
4298 * - #method_missing: Method called when an undefined method is called on +self+.
4299 * - #public_send: Calls the given public method in +self+ with the given argument.
4300 * - #send: Calls the given method in +self+ with the given argument.
4301 * - #to_s: Returns a string representation of +self+.
4302 *
4303 */
4304
4305void
4306InitVM_Object(void)
4307{
4308 Init_class_hierarchy();
4309
4310#if 0
4311 // teach RDoc about these classes
4312 rb_cBasicObject = rb_define_class("BasicObject", Qnil);
4313 rb_cObject = rb_define_class("Object", rb_cBasicObject);
4314 rb_cModule = rb_define_class("Module", rb_cObject);
4315 rb_cClass = rb_define_class("Class", rb_cModule);
4316 rb_cRefinement = rb_define_class("Refinement", rb_cModule);
4317#endif
4318
4319 rb_define_private_method(rb_cBasicObject, "initialize", rb_obj_initialize, 0);
4320 rb_define_method(rb_cBasicObject, "==", rb_obj_equal, 1);
4321 rb_define_method(rb_cBasicObject, "equal?", rb_obj_equal, 1);
4322 rb_define_method(rb_cBasicObject, "!", rb_obj_not, 0);
4323 rb_define_method(rb_cBasicObject, "!=", rb_obj_not_equal, 1);
4324
4325 rb_define_private_method(rb_cBasicObject, "singleton_method_added", rb_obj_singleton_method_added, 1);
4326 rb_define_private_method(rb_cBasicObject, "singleton_method_removed", rb_obj_singleton_method_removed, 1);
4327 rb_define_private_method(rb_cBasicObject, "singleton_method_undefined", rb_obj_singleton_method_undefined, 1);
4328
4329 /* Document-module: Kernel
4330 *
4331 * The Kernel module is included by class Object, so its methods are
4332 * available in every Ruby object.
4333 *
4334 * The Kernel instance methods are documented in class Object while the
4335 * module methods are documented here. These methods are called without a
4336 * receiver and thus can be called in functional form:
4337 *
4338 * sprintf "%.1f", 1.234 #=> "1.2"
4339 *
4340 * == What's Here
4341 *
4342 * Module \Kernel provides methods that are useful for:
4343 *
4344 * - {Converting}[rdoc-ref:Kernel@Converting]
4345 * - {Querying}[rdoc-ref:Kernel@Querying]
4346 * - {Exiting}[rdoc-ref:Kernel@Exiting]
4347 * - {Exceptions}[rdoc-ref:Kernel@Exceptions]
4348 * - {IO}[rdoc-ref:Kernel@IO]
4349 * - {Procs}[rdoc-ref:Kernel@Procs]
4350 * - {Tracing}[rdoc-ref:Kernel@Tracing]
4351 * - {Subprocesses}[rdoc-ref:Kernel@Subprocesses]
4352 * - {Loading}[rdoc-ref:Kernel@Loading]
4353 * - {Yielding}[rdoc-ref:Kernel@Yielding]
4354 * - {Random Values}[rdoc-ref:Kernel@Random+Values]
4355 * - {Other}[rdoc-ref:Kernel@Other]
4356 *
4357 * === Converting
4358 *
4359 * - #Array: Returns an Array based on the given argument.
4360 * - #Complex: Returns a Complex based on the given arguments.
4361 * - #Float: Returns a Float based on the given arguments.
4362 * - #Hash: Returns a Hash based on the given argument.
4363 * - #Integer: Returns an Integer based on the given arguments.
4364 * - #Rational: Returns a Rational based on the given arguments.
4365 * - #String: Returns a String based on the given argument.
4366 *
4367 * === Querying
4368 *
4369 * - #__callee__: Returns the called name of the current method as a symbol.
4370 * - #__dir__: Returns the path to the directory from which the current
4371 * method is called.
4372 * - #__method__: Returns the name of the current method as a symbol.
4373 * - #autoload?: Returns the file to be loaded when the given module is referenced.
4374 * - #binding: Returns a Binding for the context at the point of call.
4375 * - #block_given?: Returns +true+ if a block was passed to the calling method.
4376 * - #caller: Returns the current execution stack as an array of strings.
4377 * - #caller_locations: Returns the current execution stack as an array
4378 * of Thread::Backtrace::Location objects.
4379 * - #class: Returns the class of +self+.
4380 * - #frozen?: Returns whether +self+ is frozen.
4381 * - #global_variables: Returns an array of global variables as symbols.
4382 * - #local_variables: Returns an array of local variables as symbols.
4383 * - #test: Performs specified tests on the given single file or pair of files.
4384 *
4385 * === Exiting
4386 *
4387 * - #abort: Exits the current process after printing the given arguments.
4388 * - #at_exit: Executes the given block when the process exits.
4389 * - #exit: Exits the current process after calling any registered
4390 * +at_exit+ handlers.
4391 * - #exit!: Exits the current process without calling any registered
4392 * +at_exit+ handlers.
4393 *
4394 * === Exceptions
4395 *
4396 * - #catch: Executes the given block, possibly catching a thrown object.
4397 * - #raise (aliased as #fail): Raises an exception based on the given arguments.
4398 * - #throw: Returns from the active catch block waiting for the given tag.
4399 *
4400 *
4401 * === \IO
4402 *
4403 * - ::pp: Prints the given objects in pretty form.
4404 * - #gets: Returns and assigns to <tt>$_</tt> the next line from the current input.
4405 * - #open: Creates an IO object connected to the given stream, file, or subprocess.
4406 * - #p: Prints the given objects' inspect output to the standard output.
4407 * - #print: Prints the given objects to standard output without a newline.
4408 * - #printf: Prints the string resulting from applying the given format string
4409 * to any additional arguments.
4410 * - #putc: Equivalent to <tt>$stdout.putc(object)</tt> for the given object.
4411 * - #puts: Equivalent to <tt>$stdout.puts(*objects)</tt> for the given objects.
4412 * - #readline: Similar to #gets, but raises an exception at the end of file.
4413 * - #readlines: Returns an array of the remaining lines from the current input.
4414 * - #select: Same as IO.select.
4415 *
4416 * === Procs
4417 *
4418 * - #lambda: Returns a lambda proc for the given block.
4419 * - #proc: Returns a new Proc; equivalent to Proc.new.
4420 *
4421 * === Tracing
4422 *
4423 * - #set_trace_func: Sets the given proc as the handler for tracing,
4424 * or disables tracing if given +nil+.
4425 * - #trace_var: Starts tracing assignments to the given global variable.
4426 * - #untrace_var: Disables tracing of assignments to the given global variable.
4427 *
4428 * === Subprocesses
4429 *
4430 * - {\`command`}[rdoc-ref:Kernel#`]: Returns the standard output of running
4431 * +command+ in a subshell.
4432 * - #exec: Replaces current process with a new process.
4433 * - #fork: Forks the current process into two processes.
4434 * - #spawn: Executes the given command and returns its pid without waiting
4435 * for completion.
4436 * - #system: Executes the given command in a subshell.
4437 *
4438 * === Loading
4439 *
4440 * - #autoload: Registers the given file to be loaded when the given constant
4441 * is first referenced.
4442 * - #load: Loads the given Ruby file.
4443 * - #require: Loads the given Ruby file unless it has already been loaded.
4444 * - #require_relative: Loads the Ruby file path relative to the calling file,
4445 * unless it has already been loaded.
4446 *
4447 * === Yielding
4448 *
4449 * - #tap: Yields +self+ to the given block; returns +self+.
4450 * - #then (aliased as #yield_self): Yields +self+ to the block
4451 * and returns the result of the block.
4452 *
4453 * === \Random Values
4454 *
4455 * - #rand: Returns a pseudo-random floating point number
4456 * strictly between 0.0 and 1.0.
4457 * - #srand: Seeds the pseudo-random number generator with the given number.
4458 *
4459 * === Other
4460 *
4461 * - #eval: Evaluates the given string as Ruby code.
4462 * - #loop: Repeatedly executes the given block.
4463 * - #sleep: Suspends the current thread for the given number of seconds.
4464 * - #sprintf (aliased as #format): Returns the string resulting from applying
4465 * the given format string to any additional arguments.
4466 * - #syscall: Runs an operating system call.
4467 * - #trap: Specifies the handling of system signals.
4468 * - #warn: Issue a warning based on the given messages and options.
4469 *
4470 */
4471 rb_mKernel = rb_define_module("Kernel");
4473 rb_define_private_method(rb_cClass, "inherited", rb_obj_class_inherited, 1);
4474 rb_define_private_method(rb_cModule, "included", rb_obj_mod_included, 1);
4475 rb_define_private_method(rb_cModule, "extended", rb_obj_mod_extended, 1);
4476 rb_define_private_method(rb_cModule, "prepended", rb_obj_mod_prepended, 1);
4477 rb_define_private_method(rb_cModule, "method_added", rb_obj_mod_method_added, 1);
4478 rb_define_private_method(rb_cModule, "const_added", rb_obj_mod_const_added, 1);
4479 rb_define_private_method(rb_cModule, "method_removed", rb_obj_mod_method_removed, 1);
4480 rb_define_private_method(rb_cModule, "method_undefined", rb_obj_mod_method_undefined, 1);
4481
4482 rb_define_method(rb_mKernel, "nil?", rb_false, 0);
4483 rb_define_method(rb_mKernel, "===", case_equal, 1);
4484 rb_define_method(rb_mKernel, "!~", rb_obj_not_match, 1);
4485 rb_define_method(rb_mKernel, "eql?", rb_obj_equal, 1);
4486 rb_define_method(rb_mKernel, "hash", rb_obj_hash, 0); /* in hash.c */
4487 rb_define_method(rb_mKernel, "<=>", rb_obj_cmp, 1);
4488
4489 rb_define_method(rb_mKernel, "singleton_class", rb_obj_singleton_class, 0);
4491 rb_define_method(rb_mKernel, "itself", rb_obj_itself, 0);
4492 rb_define_method(rb_mKernel, "initialize_copy", rb_obj_init_copy, 1);
4493 rb_define_method(rb_mKernel, "initialize_dup", rb_obj_init_dup_clone, 1);
4494 rb_define_method(rb_mKernel, "initialize_clone", rb_obj_init_clone, -1);
4495
4497
4499 rb_define_method(rb_mKernel, "inspect", rb_obj_inspect, 0);
4500 rb_define_private_method(rb_mKernel, "instance_variables_to_inspect", rb_obj_instance_variables_to_inspect, 0);
4501 rb_define_method(rb_mKernel, "methods", rb_obj_methods, -1); /* in class.c */
4502 rb_define_method(rb_mKernel, "singleton_methods", rb_obj_singleton_methods, -1); /* in class.c */
4503 rb_define_method(rb_mKernel, "protected_methods", rb_obj_protected_methods, -1); /* in class.c */
4504 rb_define_method(rb_mKernel, "private_methods", rb_obj_private_methods, -1); /* in class.c */
4505 rb_define_method(rb_mKernel, "public_methods", rb_obj_public_methods, -1); /* in class.c */
4506 rb_define_method(rb_mKernel, "instance_variables", rb_obj_instance_variables, 0); /* in variable.c */
4507 rb_define_method(rb_mKernel, "instance_variable_get", rb_obj_ivar_get, 1);
4508 rb_define_method(rb_mKernel, "instance_variable_set", rb_obj_ivar_set_m, 2);
4509 rb_define_method(rb_mKernel, "instance_variable_defined?", rb_obj_ivar_defined, 1);
4510 rb_define_method(rb_mKernel, "remove_instance_variable",
4511 rb_obj_remove_instance_variable, 1); /* in variable.c */
4512
4516
4517 rb_define_global_function("sprintf", f_sprintf, -1);
4518 rb_define_global_function("format", f_sprintf, -1);
4519
4520 rb_define_global_function("String", rb_f_string, 1);
4521 rb_define_global_function("Array", rb_f_array, 1);
4522 rb_define_global_function("Hash", rb_f_hash, 1);
4523
4524 rb_cNilClass = rb_define_class("NilClass", rb_cObject);
4525 rb_cNilClass_to_s = rb_fstring_enc_lit("", rb_usascii_encoding());
4526 rb_vm_register_global_object(rb_cNilClass_to_s);
4527 rb_define_method(rb_cNilClass, "to_s", rb_nil_to_s, 0);
4528 rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0);
4529 rb_define_method(rb_cNilClass, "to_h", nil_to_h, 0);
4530 rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0);
4531 rb_define_method(rb_cNilClass, "=~", nil_match, 1);
4532 rb_define_method(rb_cNilClass, "&", false_and, 1);
4533 rb_define_method(rb_cNilClass, "|", false_or, 1);
4534 rb_define_method(rb_cNilClass, "^", false_xor, 1);
4535 rb_define_method(rb_cNilClass, "===", case_equal, 1);
4536
4537 rb_define_method(rb_cNilClass, "nil?", rb_true, 0);
4540
4541 rb_define_method(rb_cModule, "freeze", rb_mod_freeze, 0);
4542 rb_define_method(rb_cModule, "===", rb_mod_eqq, 1);
4543 rb_define_method(rb_cModule, "==", rb_obj_equal, 1);
4544 rb_define_method(rb_cModule, "<=>", rb_mod_cmp, 1);
4545 rb_define_method(rb_cModule, "<", rb_mod_lt, 1);
4547 rb_define_method(rb_cModule, ">", rb_mod_gt, 1);
4548 rb_define_method(rb_cModule, ">=", rb_mod_ge, 1);
4549 rb_define_method(rb_cModule, "to_s", rb_mod_to_s, 0);
4550 rb_define_alias(rb_cModule, "inspect", "to_s");
4551 rb_define_method(rb_cModule, "included_modules", rb_mod_included_modules, 0); /* in class.c */
4552 rb_define_method(rb_cModule, "include?", rb_mod_include_p, 1); /* in class.c */
4553 rb_define_method(rb_cModule, "name", rb_mod_name, 0); /* in variable.c */
4554 rb_define_method(rb_cModule, "set_temporary_name", rb_mod_set_temporary_name, 1); /* in variable.c */
4555 rb_define_method(rb_cModule, "ancestors", rb_mod_ancestors, 0); /* in class.c */
4556 rb_define_method(rb_cModule, "descendants", rb_mod_descendants, 0); /* in class.c */
4557
4558 rb_define_method(rb_cModule, "attr", rb_mod_attr, -1);
4559 rb_define_method(rb_cModule, "attr_reader", rb_mod_attr_reader, -1);
4560 rb_define_method(rb_cModule, "attr_writer", rb_mod_attr_writer, -1);
4561 rb_define_method(rb_cModule, "attr_accessor", rb_mod_attr_accessor, -1);
4562
4563 rb_define_alloc_func(rb_cModule, rb_module_s_alloc);
4565 rb_define_method(rb_cModule, "initialize", rb_mod_initialize, 0);
4566 rb_define_method(rb_cModule, "initialize_clone", rb_mod_initialize_clone, -1);
4567 rb_define_method(rb_cModule, "instance_methods", rb_class_instance_methods, -1); /* in class.c */
4568 rb_define_method(rb_cModule, "public_instance_methods",
4569 rb_class_public_instance_methods, -1); /* in class.c */
4570 rb_define_method(rb_cModule, "protected_instance_methods",
4571 rb_class_protected_instance_methods, -1); /* in class.c */
4572 rb_define_method(rb_cModule, "private_instance_methods",
4573 rb_class_private_instance_methods, -1); /* in class.c */
4574 rb_define_method(rb_cModule, "undefined_instance_methods",
4575 rb_class_undefined_instance_methods, 0); /* in class.c */
4576
4577 rb_define_method(rb_cModule, "constants", rb_mod_constants, -1); /* in variable.c */
4578 rb_define_method(rb_cModule, "const_get", rb_mod_const_get, -1);
4579 rb_define_method(rb_cModule, "const_set", rb_mod_const_set, 2);
4580 rb_define_method(rb_cModule, "const_defined?", rb_mod_const_defined, -1);
4581 rb_define_method(rb_cModule, "const_source_location", rb_mod_const_source_location, -1);
4582 rb_define_private_method(rb_cModule, "remove_const",
4583 rb_mod_remove_const, 1); /* in variable.c */
4584 rb_define_method(rb_cModule, "const_missing",
4585 rb_mod_const_missing, 1); /* in variable.c */
4586 rb_define_method(rb_cModule, "class_variables",
4587 rb_mod_class_variables, -1); /* in variable.c */
4588 rb_define_method(rb_cModule, "remove_class_variable",
4589 rb_mod_remove_cvar, 1); /* in variable.c */
4590 rb_define_method(rb_cModule, "class_variable_get", rb_mod_cvar_get, 1);
4591 rb_define_method(rb_cModule, "class_variable_set", rb_mod_cvar_set, 2);
4592 rb_define_method(rb_cModule, "class_variable_defined?", rb_mod_cvar_defined, 1);
4593 rb_define_method(rb_cModule, "public_constant", rb_mod_public_constant, -1); /* in variable.c */
4594 rb_define_method(rb_cModule, "private_constant", rb_mod_private_constant, -1); /* in variable.c */
4595 rb_define_method(rb_cModule, "deprecate_constant", rb_mod_deprecate_constant, -1); /* in variable.c */
4596 rb_define_method(rb_cModule, "singleton_class?", rb_mod_singleton_p, 0);
4597
4598 rb_define_method(rb_singleton_class(rb_cClass), "allocate", rb_class_alloc, 0);
4599 rb_define_method(rb_cClass, "allocate", rb_class_alloc, 0);
4601 rb_define_method(rb_cClass, "initialize", rb_class_initialize, -1);
4603 rb_define_method(rb_cClass, "subclasses", rb_class_subclasses, 0); /* in class.c */
4604 rb_define_method(rb_cClass, "attached_object", rb_class_attached_object, 0); /* in class.c */
4605 rb_define_alloc_func(rb_cClass, rb_class_s_alloc);
4606 rb_undef_method(rb_cClass, "extend_object");
4607 rb_undef_method(rb_cClass, "append_features");
4608 rb_undef_method(rb_cClass, "prepend_features");
4609
4610 rb_cTrueClass = rb_define_class("TrueClass", rb_cObject);
4611 rb_cTrueClass_to_s = rb_fstring_enc_lit("true", rb_usascii_encoding());
4612 rb_vm_register_global_object(rb_cTrueClass_to_s);
4613 rb_define_method(rb_cTrueClass, "to_s", rb_true_to_s, 0);
4614 rb_define_alias(rb_cTrueClass, "inspect", "to_s");
4615 rb_define_method(rb_cTrueClass, "&", true_and, 1);
4616 rb_define_method(rb_cTrueClass, "|", true_or, 1);
4617 rb_define_method(rb_cTrueClass, "^", true_xor, 1);
4618 rb_define_method(rb_cTrueClass, "===", case_equal, 1);
4621
4622 rb_cFalseClass = rb_define_class("FalseClass", rb_cObject);
4623 rb_cFalseClass_to_s = rb_fstring_enc_lit("false", rb_usascii_encoding());
4624 rb_vm_register_global_object(rb_cFalseClass_to_s);
4625 rb_define_method(rb_cFalseClass, "to_s", rb_false_to_s, 0);
4626 rb_define_alias(rb_cFalseClass, "inspect", "to_s");
4627 rb_define_method(rb_cFalseClass, "&", false_and, 1);
4628 rb_define_method(rb_cFalseClass, "|", false_or, 1);
4629 rb_define_method(rb_cFalseClass, "^", false_xor, 1);
4630 rb_define_method(rb_cFalseClass, "===", case_equal, 1);
4633}
4634
4635#include "kernel.rbinc"
4636#include "nilclass.rbinc"
4637
4638void
4639Init_Object(void)
4640{
4641 id_dig = rb_intern_const("dig");
4642 id_instance_variables_to_inspect = rb_intern_const("instance_variables_to_inspect");
4643 InitVM(Object);
4644}
4645
#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_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:2090
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:2643
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1769
VALUE rb_class_subclasses(VALUE klass)
Queries the class's direct descendants.
Definition class.c:2288
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3051
VALUE rb_class_attached_object(VALUE klass)
Returns the attached object for a singleton class.
Definition class.c:2435
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:2820
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:2628
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:2681
void rb_class_modify_check(VALUE klass)
Asserts that klass is not a frozen class.
Definition eval.c:445
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:2108
VALUE rb_mod_ancestors(VALUE mod)
Queries the module's ancestors.
Definition class.c:2176
VALUE rb_class_inherited(VALUE super, VALUE klass)
Calls Class::inherited.
Definition class.c:1561
VALUE rb_mod_include_p(VALUE mod, VALUE mod2)
Queries if the passed module is included by the module.
Definition class.c:2144
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:2666
VALUE rb_mod_init_copy(VALUE clone, VALUE orig)
The comment that comes with this function says :nodoc:.
Definition class.c:1093
VALUE rb_mod_descendants(VALUE mod)
Queries the module's descendants.
Definition class.c:2384
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3094
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2897
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:3384
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:3173
#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:1684
#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:1681
#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:510
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1473
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:499
@ 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:2308
VALUE rb_class_get_superclass(VALUE klass)
Returns the superclass of a class.
Definition object.c:2333
VALUE rb_convert_type(VALUE val, int type, const char *tname, const char *method)
Converts an object into another type.
Definition object.c:3232
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition object.c:3746
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:3334
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:3259
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:2252
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2293
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:2281
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:2270
VALUE rb_check_to_float(VALUE val)
This is complicated.
Definition object.c:3784
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:3943
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:3642
VALUE rb_Integer(VALUE val)
This is the logic behind Kernel#Integer.
Definition object.c:3403
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:3900
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:3774
double rb_num2dbl(VALUE val)
Converts an instance of rb_cNumeric into C's double.
Definition object.c:3836
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:3598
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:3315
VALUE rb_String(VALUE val)
This is the logic behind Kernel#String.
Definition object.c:3868
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:3328
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, long len, rb_encoding *enc)
Identical to rb_check_id(), except it takes a pointer to a memory region instead of Ruby's string.
Definition symbol.c:1381
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1123
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:1090
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:1081
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_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3906
VALUE rb_str_subseq(VALUE str, long beg, long len)
Identical to rb_str_substr(), except the numbers are interpreted as byte offsets instead of character...
Definition string.c:3259
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:3872
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2855
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:4143
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:3040
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:1895
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:4538
VALUE rb_obj_instance_variables(VALUE obj)
Resembles Object#instance_variables.
Definition variable.c:2530
VALUE rb_const_get(VALUE space, ID name)
Identical to rb_const_defined(), except it returns the actual defined value.
Definition variable.c:3505
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:2141
VALUE rb_mod_remove_const(VALUE space, VALUE name)
Resembles Module#remove_const.
Definition variable.c:3610
void rb_cvar_set(VALUE klass, ID name, VALUE val)
Assigns a value to a class variable.
Definition variable.c:4294
VALUE rb_cvar_get(VALUE klass, ID name)
Obtains a value from a class variable.
Definition variable.c:4373
VALUE rb_mod_constants(int argc, const VALUE *argv, VALUE recv)
Resembles Module#constants.
Definition variable.c:3782
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:1641
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:3984
VALUE rb_mod_name(VALUE mod)
Queries the name of a module.
Definition variable.c:152
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:518
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:3511
VALUE rb_obj_remove_instance_variable(VALUE obj, VALUE name)
Resembles Object#remove_instance_variable.
Definition variable.c:2582
st_index_t rb_ivar_count(VALUE obj)
Number of instance variables defined on an object.
Definition variable.c:2478
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:3499
VALUE rb_ivar_defined(VALUE obj, ID name)
Queries if the instance variable is defined at the object.
Definition variable.c:2201
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:3844
VALUE rb_mod_class_variables(int argc, const VALUE *argv, VALUE recv)
Resembles Module#class_variables.
Definition variable.c:4503
VALUE rb_cvar_defined(VALUE klass, ID name)
Queries if the given class has the given class variable.
Definition variable.c:4380
int rb_const_defined_from(VALUE space, ID name)
Identical to rb_const_defined(), except it returns false for private constants.
Definition variable.c:3832
int rb_const_defined(VALUE space, ID name)
Queries if the constant is defined at the namespace.
Definition variable.c:3838
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:1843
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:3561
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:2501
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:691
rb_alloc_func_t rb_get_alloc_func(VALUE klass)
Queries the allocator function of a class.
Definition vm_method.c:1852
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:2513
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:2335
#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:524
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:533
#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
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