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