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