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