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