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