Ruby 4.0.0dev (2025-12-17 revision 2117e612cafbd1a5ce4ce1d72cc13f8d9b715aa9)
object.c (2117e612cafbd1a5ce4ce1d72cc13f8d9b715aa9)
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 * obj <=> other -> 0 or nil
1711 *
1712 * Returns 0 if +obj+ and +other+ are the same object
1713 * or <code>obj == other</code>, otherwise nil.
1714 *
1715 * The #<=> is used by various methods to compare objects, for example
1716 * Enumerable#sort, Enumerable#max etc.
1717 *
1718 * Your implementation of #<=> should return one of the following values: -1, 0,
1719 * 1 or nil. -1 means self is smaller than other. 0 means self is equal to other.
1720 * 1 means self is bigger than other. Nil means the two values could not be
1721 * compared.
1722 *
1723 * When you define #<=>, you can include Comparable to gain the
1724 * methods #<=, #<, #==, #>=, #> and #between?.
1725 */
1726static VALUE
1727rb_obj_cmp(VALUE obj1, VALUE obj2)
1728{
1729 if (rb_equal(obj1, obj2))
1730 return INT2FIX(0);
1731 return Qnil;
1732}
1733
1734/***********************************************************************
1735 *
1736 * Document-class: Module
1737 *
1738 * A Module is a collection of methods and constants. The
1739 * methods in a module may be instance methods or module methods.
1740 * Instance methods appear as methods in a class when the module is
1741 * included, module methods do not. Conversely, module methods may be
1742 * called without creating an encapsulating object, while instance
1743 * methods may not. (See Module#module_function.)
1744 *
1745 * In the descriptions that follow, the parameter <i>sym</i> refers
1746 * to a symbol, which is either a quoted string or a
1747 * Symbol (such as <code>:name</code>).
1748 *
1749 * module Mod
1750 * include Math
1751 * CONST = 1
1752 * def meth
1753 * # ...
1754 * end
1755 * end
1756 * Mod.class #=> Module
1757 * Mod.constants #=> [:CONST, :PI, :E]
1758 * Mod.instance_methods #=> [:meth]
1759 *
1760 */
1761
1762/*
1763 * call-seq:
1764 * mod.to_s -> string
1765 *
1766 * Returns a string representing this module or class. For basic
1767 * classes and modules, this is the name. For singletons, we
1768 * show information on the thing we're attached to as well.
1769 */
1770
1771VALUE
1772rb_mod_to_s(VALUE klass)
1773{
1774 ID id_defined_at;
1775 VALUE refined_class, defined_at;
1776
1777 if (RCLASS_SINGLETON_P(klass)) {
1778 VALUE s = rb_usascii_str_new2("#<Class:");
1779 VALUE v = RCLASS_ATTACHED_OBJECT(klass);
1780
1781 if (CLASS_OR_MODULE_P(v)) {
1783 }
1784 else {
1786 }
1787 rb_str_cat2(s, ">");
1788
1789 return s;
1790 }
1791 refined_class = rb_refinement_module_get_refined_class(klass);
1792 if (!NIL_P(refined_class)) {
1793 VALUE s = rb_usascii_str_new2("#<refinement:");
1794
1795 rb_str_concat(s, rb_inspect(refined_class));
1796 rb_str_cat2(s, "@");
1797 CONST_ID(id_defined_at, "__defined_at__");
1798 defined_at = rb_attr_get(klass, id_defined_at);
1799 rb_str_concat(s, rb_inspect(defined_at));
1800 rb_str_cat2(s, ">");
1801 return s;
1802 }
1803 return rb_class_name(klass);
1804}
1805
1806/*
1807 * call-seq:
1808 * mod.freeze -> mod
1809 *
1810 * Prevents further modifications to <i>mod</i>.
1811 *
1812 * This method returns self.
1813 */
1814
1815static VALUE
1816rb_mod_freeze(VALUE mod)
1817{
1818 rb_class_name(mod);
1819 return rb_obj_freeze(mod);
1820}
1821
1822/*
1823 * call-seq:
1824 * mod === obj -> true or false
1825 *
1826 * Case Equality---Returns <code>true</code> if <i>obj</i> is an
1827 * instance of <i>mod</i> or an instance of one of <i>mod</i>'s descendants.
1828 * Of limited use for modules, but can be used in <code>case</code> statements
1829 * to classify objects by class.
1830 */
1831
1832static VALUE
1833rb_mod_eqq(VALUE mod, VALUE arg)
1834{
1835 return rb_obj_is_kind_of(arg, mod);
1836}
1837
1838/*
1839 * call-seq:
1840 * mod <= other -> true, false, or nil
1841 *
1842 * Returns true if <i>mod</i> is a subclass of <i>other</i> or
1843 * is the same as <i>other</i>. Returns
1844 * <code>nil</code> if there's no relationship between the two.
1845 * (Think of the relationship in terms of the class definition:
1846 * "class A < B" implies "A < B".)
1847 */
1848
1849VALUE
1851{
1852 if (mod == arg) return Qtrue;
1853
1854 if (RB_TYPE_P(arg, T_CLASS) && RB_TYPE_P(mod, T_CLASS)) {
1855 // comparison between classes
1856 size_t mod_depth = RCLASS_SUPERCLASS_DEPTH(mod);
1857 size_t arg_depth = RCLASS_SUPERCLASS_DEPTH(arg);
1858 if (arg_depth < mod_depth) {
1859 // check if mod < arg
1860 return RCLASS_SUPERCLASSES(mod)[arg_depth] == arg ?
1861 Qtrue :
1862 Qnil;
1863 }
1864 else if (arg_depth > mod_depth) {
1865 // check if mod > arg
1866 return RCLASS_SUPERCLASSES(arg)[mod_depth] == mod ?
1867 Qfalse :
1868 Qnil;
1869 }
1870 else {
1871 // Depths match, and we know they aren't equal: no relation
1872 return Qnil;
1873 }
1874 }
1875 else {
1876 if (!CLASS_OR_MODULE_P(arg) && !RB_TYPE_P(arg, T_ICLASS)) {
1877 rb_raise(rb_eTypeError, "compared with non class/module");
1878 }
1879 if (class_search_ancestor(mod, RCLASS_ORIGIN(arg))) {
1880 return Qtrue;
1881 }
1882 /* not mod < arg; check if mod > arg */
1883 if (class_search_ancestor(arg, mod)) {
1884 return Qfalse;
1885 }
1886 return Qnil;
1887 }
1888}
1889
1890/*
1891 * call-seq:
1892 * mod < other -> true, false, or nil
1893 *
1894 * Returns true if <i>mod</i> is a subclass of <i>other</i>. Returns
1895 * <code>false</code> if <i>mod</i> is the same as <i>other</i>
1896 * or <i>mod</i> is an ancestor of <i>other</i>.
1897 * Returns <code>nil</code> if there's no relationship between the two.
1898 * (Think of the relationship in terms of the class definition:
1899 * "class A < B" implies "A < B".)
1900 *
1901 */
1902
1903static VALUE
1904rb_mod_lt(VALUE mod, VALUE arg)
1905{
1906 if (mod == arg) return Qfalse;
1907 return rb_class_inherited_p(mod, arg);
1908}
1909
1910
1911/*
1912 * call-seq:
1913 * mod >= other -> true, false, or nil
1914 *
1915 * Returns true if <i>mod</i> is an ancestor of <i>other</i>, or the
1916 * two modules are the same. Returns
1917 * <code>nil</code> if there's no relationship between the two.
1918 * (Think of the relationship in terms of the class definition:
1919 * "class A < B" implies "B > A".)
1920 *
1921 */
1922
1923static VALUE
1924rb_mod_ge(VALUE mod, VALUE arg)
1925{
1926 if (!CLASS_OR_MODULE_P(arg)) {
1927 rb_raise(rb_eTypeError, "compared with non class/module");
1928 }
1929
1930 return rb_class_inherited_p(arg, mod);
1931}
1932
1933/*
1934 * call-seq:
1935 * mod > other -> true, false, or nil
1936 *
1937 * Returns true if <i>mod</i> is an ancestor of <i>other</i>. Returns
1938 * <code>false</code> if <i>mod</i> is the same as <i>other</i>
1939 * or <i>mod</i> is a descendant of <i>other</i>.
1940 * Returns <code>nil</code> if there's no relationship between the two.
1941 * (Think of the relationship in terms of the class definition:
1942 * "class A < B" implies "B > A".)
1943 *
1944 */
1945
1946static VALUE
1947rb_mod_gt(VALUE mod, VALUE arg)
1948{
1949 if (mod == arg) return Qfalse;
1950 return rb_mod_ge(mod, arg);
1951}
1952
1953/*
1954 * call-seq:
1955 * self <=> object -> -1, 0, +1, or nil
1956 *
1957 * Returns:
1958 *
1959 * - +-1+, if +self+ includes +object+, if or +self+ is a subclass of +object+.
1960 * - +0+, if +self+ and +object+ are the same.
1961 * - +1+, if +object+ includes +self+, or if +object+ is a subclass of +self+.
1962 * - +nil+, if none of the above is true.
1963 *
1964 * Examples:
1965 *
1966 * # Class Array includes module Enumerable.
1967 * Array <=> Enumerable # => -1
1968 * Enumerable <=> Enumerable # => 0
1969 * Enumerable <=> Array # => 1
1970 * # Class File is a subclass of class IO.
1971 * File <=> IO # => -1
1972 * IO <=> File # => 1
1973 * File <=> File # => 0
1974 *
1975 */
1976
1977static VALUE
1978rb_mod_cmp(VALUE mod, VALUE arg)
1979{
1980 VALUE cmp;
1981
1982 if (mod == arg) return INT2FIX(0);
1983 if (!CLASS_OR_MODULE_P(arg)) {
1984 return Qnil;
1985 }
1986
1987 cmp = rb_class_inherited_p(mod, arg);
1988 if (NIL_P(cmp)) return Qnil;
1989 if (cmp) {
1990 return INT2FIX(-1);
1991 }
1992 return INT2FIX(1);
1993}
1994
1995static VALUE rb_mod_initialize_exec(VALUE module);
1996
1997/*
1998 * call-seq:
1999 * Module.new -> mod
2000 * Module.new {|mod| block } -> mod
2001 *
2002 * Creates a new anonymous module. If a block is given, it is passed
2003 * the module object, and the block is evaluated in the context of this
2004 * module like #module_eval.
2005 *
2006 * fred = Module.new do
2007 * def meth1
2008 * "hello"
2009 * end
2010 * def meth2
2011 * "bye"
2012 * end
2013 * end
2014 * a = "my string"
2015 * a.extend(fred) #=> "my string"
2016 * a.meth1 #=> "hello"
2017 * a.meth2 #=> "bye"
2018 *
2019 * Assign the module to a constant (name starting uppercase) if you
2020 * want to treat it like a regular module.
2021 */
2022
2023static VALUE
2024rb_mod_initialize(VALUE module)
2025{
2026 return rb_mod_initialize_exec(module);
2027}
2028
2029static VALUE
2030rb_mod_initialize_exec(VALUE module)
2031{
2032 if (rb_block_given_p()) {
2033 rb_mod_module_exec(1, &module, module);
2034 }
2035 return Qnil;
2036}
2037
2038/* :nodoc: */
2039static VALUE
2040rb_mod_initialize_clone(int argc, VALUE* argv, VALUE clone)
2041{
2042 VALUE ret, orig, opts;
2043 rb_scan_args(argc, argv, "1:", &orig, &opts);
2044 ret = rb_obj_init_clone(argc, argv, clone);
2045 if (OBJ_FROZEN(orig))
2046 rb_class_name(clone);
2047 return ret;
2048}
2049
2050/*
2051 * call-seq:
2052 * Class.new(super_class=Object) -> a_class
2053 * Class.new(super_class=Object) { |mod| ... } -> a_class
2054 *
2055 * Creates a new anonymous (unnamed) class with the given superclass
2056 * (or Object if no parameter is given). You can give a
2057 * class a name by assigning the class object to a constant.
2058 *
2059 * If a block is given, it is passed the class object, and the block
2060 * is evaluated in the context of this class like
2061 * #class_eval.
2062 *
2063 * fred = Class.new do
2064 * def meth1
2065 * "hello"
2066 * end
2067 * def meth2
2068 * "bye"
2069 * end
2070 * end
2071 *
2072 * a = fred.new #=> #<#<Class:0x100381890>:0x100376b98>
2073 * a.meth1 #=> "hello"
2074 * a.meth2 #=> "bye"
2075 *
2076 * Assign the class to a constant (name starting uppercase) if you
2077 * want to treat it like a regular class.
2078 */
2079
2080static VALUE
2081rb_class_initialize(int argc, VALUE *argv, VALUE klass)
2082{
2083 VALUE super;
2084
2085 if (RCLASS_SUPER(klass) != 0 || klass == rb_cBasicObject) {
2086 rb_raise(rb_eTypeError, "already initialized class");
2087 }
2088 if (rb_check_arity(argc, 0, 1) == 0) {
2089 super = rb_cObject;
2090 }
2091 else {
2092 super = argv[0];
2093 rb_check_inheritable(super);
2094 if (!RCLASS_INITIALIZED_P(super)) {
2095 rb_raise(rb_eTypeError, "can't inherit uninitialized class");
2096 }
2097 }
2098 rb_class_set_super(klass, super);
2099 rb_make_metaclass(klass, RBASIC(super)->klass);
2100 rb_class_inherited(super, klass);
2101 rb_mod_initialize_exec(klass);
2102
2103 return klass;
2104}
2105
2107void
2108rb_undefined_alloc(VALUE klass)
2109{
2110 rb_raise(rb_eTypeError, "allocator undefined for %"PRIsVALUE,
2111 klass);
2112}
2113
2114static rb_alloc_func_t class_get_alloc_func(VALUE klass);
2115static VALUE class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass);
2116
2117/*
2118 * call-seq:
2119 * class.allocate() -> obj
2120 *
2121 * Allocates space for a new object of <i>class</i>'s class and does not
2122 * call initialize on the new instance. The returned object must be an
2123 * instance of <i>class</i>.
2124 *
2125 * klass = Class.new do
2126 * def initialize(*args)
2127 * @initialized = true
2128 * end
2129 *
2130 * def initialized?
2131 * @initialized || false
2132 * end
2133 * end
2134 *
2135 * klass.allocate.initialized? #=> false
2136 *
2137 */
2138
2139static VALUE
2140rb_class_alloc(VALUE klass)
2141{
2142 rb_alloc_func_t allocator = class_get_alloc_func(klass);
2143 return class_call_alloc_func(allocator, klass);
2144}
2145
2146static rb_alloc_func_t
2147class_get_alloc_func(VALUE klass)
2148{
2149 rb_alloc_func_t allocator;
2150
2151 if (!RCLASS_INITIALIZED_P(klass)) {
2152 rb_raise(rb_eTypeError, "can't instantiate uninitialized class");
2153 }
2154 if (RCLASS_SINGLETON_P(klass)) {
2155 rb_raise(rb_eTypeError, "can't create instance of singleton class");
2156 }
2157 allocator = rb_get_alloc_func(klass);
2158 if (!allocator) {
2159 rb_undefined_alloc(klass);
2160 }
2161 return allocator;
2162}
2163
2164// Might return NULL.
2166rb_zjit_class_get_alloc_func(VALUE klass)
2167{
2168 assert(RCLASS_INITIALIZED_P(klass));
2169 assert(!RCLASS_SINGLETON_P(klass));
2170 return rb_get_alloc_func(klass);
2171}
2172
2173static VALUE
2174class_call_alloc_func(rb_alloc_func_t allocator, VALUE klass)
2175{
2176 VALUE obj;
2177
2178 RUBY_DTRACE_CREATE_HOOK(OBJECT, rb_class2name(klass));
2179
2180 obj = (*allocator)(klass);
2181
2182 if (UNLIKELY(RBASIC_CLASS(obj) != klass)) {
2183 if (rb_obj_class(obj) != rb_class_real(klass)) {
2184 rb_raise(rb_eTypeError, "wrong instance allocation");
2185 }
2186 }
2187 return obj;
2188}
2189
2190VALUE
2192{
2193 Check_Type(klass, T_CLASS);
2194 return rb_class_alloc(klass);
2195}
2196
2197/*
2198 * call-seq:
2199 * class.new(args, ...) -> obj
2200 *
2201 * Calls #allocate to create a new object of <i>class</i>'s class,
2202 * then invokes that object's #initialize method, passing it
2203 * <i>args</i>. This is the method that ends up getting called
2204 * whenever an object is constructed using <code>.new</code>.
2205 *
2206 */
2207
2208VALUE
2209rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass)
2210{
2211 VALUE obj;
2212
2213 obj = rb_class_alloc(klass);
2214 rb_obj_call_init_kw(obj, argc, argv, RB_PASS_CALLED_KEYWORDS);
2215
2216 return obj;
2217}
2218
2219VALUE
2220rb_class_new_instance_kw(int argc, const VALUE *argv, VALUE klass, int kw_splat)
2221{
2222 VALUE obj;
2223 Check_Type(klass, T_CLASS);
2224
2225 obj = rb_class_alloc(klass);
2226 rb_obj_call_init_kw(obj, argc, argv, kw_splat);
2227
2228 return obj;
2229}
2230
2231VALUE
2232rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
2233{
2234 return rb_class_new_instance_kw(argc, argv, klass, RB_NO_KEYWORDS);
2235}
2236
2246VALUE
2248{
2249 RUBY_ASSERT(RB_TYPE_P(klass, T_CLASS));
2250
2251 VALUE *superclasses = RCLASS_SUPERCLASSES(klass);
2252 size_t superclasses_depth = RCLASS_SUPERCLASS_DEPTH(klass);
2253
2254 if (klass == rb_cBasicObject) return Qnil;
2255
2256 if (!superclasses) {
2257 RUBY_ASSERT(!RCLASS_SUPER(klass));
2258 rb_raise(rb_eTypeError, "uninitialized class");
2259 }
2260
2261 if (!superclasses_depth) {
2262 return Qnil;
2263 }
2264 else {
2265 VALUE super = superclasses[superclasses_depth - 1];
2266 RUBY_ASSERT(RB_TYPE_P(super, T_CLASS));
2267 return super;
2268 }
2269}
2270
2271VALUE
2273{
2274 return RCLASS_SUPER(klass);
2275}
2276
2277static const char bad_instance_name[] = "'%1$s' is not allowed as an instance variable name";
2278static const char bad_class_name[] = "'%1$s' is not allowed as a class variable name";
2279static const char bad_const_name[] = "wrong constant name %1$s";
2280static const char bad_attr_name[] = "invalid attribute name '%1$s'";
2281#define wrong_constant_name bad_const_name
2282
2284#define id_for_var(obj, name, type) id_for_setter(obj, name, type, bad_##type##_name)
2286#define id_for_setter(obj, name, type, message) \
2287 check_setter_id(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message))
2288static ID
2289check_setter_id(VALUE obj, VALUE *pname,
2290 int (*valid_id_p)(ID), int (*valid_name_p)(VALUE),
2291 const char *message, size_t message_len)
2292{
2293 ID id = rb_check_id(pname);
2294 VALUE name = *pname;
2295
2296 if (id ? !valid_id_p(id) : !valid_name_p(name)) {
2297 rb_name_err_raise_str(rb_fstring_new(message, message_len),
2298 obj, name);
2299 }
2300 return id;
2301}
2302
2303static int
2304rb_is_attr_name(VALUE name)
2305{
2306 return rb_is_local_name(name) || rb_is_const_name(name);
2307}
2308
2309static int
2310rb_is_attr_id(ID id)
2311{
2312 return rb_is_local_id(id) || rb_is_const_id(id);
2313}
2314
2315static ID
2316id_for_attr(VALUE obj, VALUE name)
2317{
2318 ID id = id_for_var(obj, name, attr);
2319 if (!id) id = rb_intern_str(name);
2320 return id;
2321}
2322
2323/*
2324 * call-seq:
2325 * attr_reader(symbol, ...) -> array
2326 * attr(symbol, ...) -> array
2327 * attr_reader(string, ...) -> array
2328 * attr(string, ...) -> array
2329 *
2330 * Creates instance variables and corresponding methods that return the
2331 * value of each instance variable. Equivalent to calling
2332 * ``<code>attr</code><i>:name</i>'' on each name in turn.
2333 * String arguments are converted to symbols.
2334 * Returns an array of defined method names as symbols.
2335 */
2336
2337static VALUE
2338rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass)
2339{
2340 int i;
2341 VALUE names = rb_ary_new2(argc);
2342
2343 for (i=0; i<argc; i++) {
2344 ID id = id_for_attr(klass, argv[i]);
2345 rb_attr(klass, id, TRUE, FALSE, TRUE);
2346 rb_ary_push(names, ID2SYM(id));
2347 }
2348 return names;
2349}
2350
2355VALUE
2356rb_mod_attr(int argc, VALUE *argv, VALUE klass)
2357{
2358 if (argc == 2 && (argv[1] == Qtrue || argv[1] == Qfalse)) {
2359 ID id = id_for_attr(klass, argv[0]);
2360 VALUE names = rb_ary_new();
2361
2362 rb_category_warning(RB_WARN_CATEGORY_DEPRECATED, "optional boolean argument is obsoleted");
2363 rb_attr(klass, id, 1, RTEST(argv[1]), TRUE);
2364 rb_ary_push(names, ID2SYM(id));
2365 if (argv[1] == Qtrue) rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2366 return names;
2367 }
2368 return rb_mod_attr_reader(argc, argv, klass);
2369}
2370
2371/*
2372 * call-seq:
2373 * attr_writer(symbol, ...) -> array
2374 * attr_writer(string, ...) -> array
2375 *
2376 * Creates an accessor method to allow assignment to the attribute
2377 * <i>symbol</i><code>.id2name</code>.
2378 * String arguments are converted to symbols.
2379 * Returns an array of defined method names as symbols.
2380 */
2381
2382static VALUE
2383rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass)
2384{
2385 int i;
2386 VALUE names = rb_ary_new2(argc);
2387
2388 for (i=0; i<argc; i++) {
2389 ID id = id_for_attr(klass, argv[i]);
2390 rb_attr(klass, id, FALSE, TRUE, TRUE);
2391 rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2392 }
2393 return names;
2394}
2395
2396/*
2397 * call-seq:
2398 * attr_accessor(symbol, ...) -> array
2399 * attr_accessor(string, ...) -> array
2400 *
2401 * Defines a named attribute for this module, where the name is
2402 * <i>symbol.</i><code>id2name</code>, creating an instance variable
2403 * (<code>@name</code>) and a corresponding access method to read it.
2404 * Also creates a method called <code>name=</code> to set the attribute.
2405 * String arguments are converted to symbols.
2406 * Returns an array of defined method names as symbols.
2407 *
2408 * module Mod
2409 * attr_accessor(:one, :two) #=> [:one, :one=, :two, :two=]
2410 * end
2411 * Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
2412 */
2413
2414static VALUE
2415rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass)
2416{
2417 int i;
2418 VALUE names = rb_ary_new2(argc * 2);
2419
2420 for (i=0; i<argc; i++) {
2421 ID id = id_for_attr(klass, argv[i]);
2422
2423 rb_attr(klass, id, TRUE, TRUE, TRUE);
2424 rb_ary_push(names, ID2SYM(id));
2425 rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
2426 }
2427 return names;
2428}
2429
2430/*
2431 * call-seq:
2432 * mod.const_get(sym, inherit=true) -> obj
2433 * mod.const_get(str, inherit=true) -> obj
2434 *
2435 * Checks for a constant with the given name in <i>mod</i>.
2436 * If +inherit+ is set, the lookup will also search
2437 * the ancestors (and +Object+ if <i>mod</i> is a +Module+).
2438 *
2439 * The value of the constant is returned if a definition is found,
2440 * otherwise a +NameError+ is raised.
2441 *
2442 * Math.const_get(:PI) #=> 3.14159265358979
2443 *
2444 * This method will recursively look up constant names if a namespaced
2445 * class name is provided. For example:
2446 *
2447 * module Foo; class Bar; end end
2448 * Object.const_get 'Foo::Bar'
2449 *
2450 * The +inherit+ flag is respected on each lookup. For example:
2451 *
2452 * module Foo
2453 * class Bar
2454 * VAL = 10
2455 * end
2456 *
2457 * class Baz < Bar; end
2458 * end
2459 *
2460 * Object.const_get 'Foo::Baz::VAL' # => 10
2461 * Object.const_get 'Foo::Baz::VAL', false # => NameError
2462 *
2463 * If the argument is not a valid constant name a +NameError+ will be
2464 * raised with a warning "wrong constant name".
2465 *
2466 * Object.const_get 'foobar' #=> NameError: wrong constant name foobar
2467 *
2468 */
2469
2470static VALUE
2471rb_mod_const_get(int argc, VALUE *argv, VALUE mod)
2472{
2473 VALUE name, recur;
2474 rb_encoding *enc;
2475 const char *pbeg, *p, *path, *pend;
2476 ID id;
2477
2478 rb_check_arity(argc, 1, 2);
2479 name = argv[0];
2480 recur = (argc == 1) ? Qtrue : argv[1];
2481
2482 if (SYMBOL_P(name)) {
2483 if (!rb_is_const_sym(name)) goto wrong_name;
2484 id = rb_check_id(&name);
2485 if (!id) return rb_const_missing(mod, name);
2486 return RTEST(recur) ? rb_const_get(mod, id) : rb_const_get_at(mod, id);
2487 }
2488
2489 path = StringValuePtr(name);
2490 enc = rb_enc_get(name);
2491
2492 if (!rb_enc_asciicompat(enc)) {
2493 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2494 }
2495
2496 pbeg = p = path;
2497 pend = path + RSTRING_LEN(name);
2498
2499 if (p >= pend || !*p) {
2500 goto wrong_name;
2501 }
2502
2503 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2504 mod = rb_cObject;
2505 p += 2;
2506 pbeg = p;
2507 }
2508
2509 while (p < pend) {
2510 VALUE part;
2511 long len, beglen;
2512
2513 while (p < pend && *p != ':') p++;
2514
2515 if (pbeg == p) goto wrong_name;
2516
2517 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2518 beglen = pbeg-path;
2519
2520 if (p < pend && p[0] == ':') {
2521 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2522 p += 2;
2523 pbeg = p;
2524 }
2525
2526 if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2527 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2528 QUOTE(name));
2529 }
2530
2531 if (!id) {
2532 part = rb_str_subseq(name, beglen, len);
2533 OBJ_FREEZE(part);
2534 if (!rb_is_const_name(part)) {
2535 name = part;
2536 goto wrong_name;
2537 }
2538 else if (!rb_method_basic_definition_p(CLASS_OF(mod), id_const_missing)) {
2539 part = rb_str_intern(part);
2540 mod = rb_const_missing(mod, part);
2541 continue;
2542 }
2543 else {
2544 rb_mod_const_missing(mod, part);
2545 }
2546 }
2547 if (!rb_is_const_id(id)) {
2548 name = ID2SYM(id);
2549 goto wrong_name;
2550 }
2551#if 0
2552 mod = rb_const_get_0(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2553#else
2554 if (!RTEST(recur)) {
2555 mod = rb_const_get_at(mod, id);
2556 }
2557 else if (beglen == 0) {
2558 mod = rb_const_get(mod, id);
2559 }
2560 else {
2561 mod = rb_const_get_from(mod, id);
2562 }
2563#endif
2564 }
2565
2566 return mod;
2567
2568 wrong_name:
2569 rb_name_err_raise(wrong_constant_name, mod, name);
2571}
2572
2573/*
2574 * call-seq:
2575 * mod.const_set(sym, obj) -> obj
2576 * mod.const_set(str, obj) -> obj
2577 *
2578 * Sets the named constant to the given object, returning that object.
2579 * Creates a new constant if no constant with the given name previously
2580 * existed.
2581 *
2582 * Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714
2583 * Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968
2584 *
2585 * If +sym+ or +str+ is not a valid constant name a +NameError+ will be
2586 * raised with a warning "wrong constant name".
2587 *
2588 * Object.const_set('foobar', 42) #=> NameError: wrong constant name foobar
2589 *
2590 */
2591
2592static VALUE
2593rb_mod_const_set(VALUE mod, VALUE name, VALUE value)
2594{
2595 ID id = id_for_var(mod, name, const);
2596 if (!id) id = rb_intern_str(name);
2597 rb_const_set(mod, id, value);
2598
2599 return value;
2600}
2601
2602/*
2603 * call-seq:
2604 * mod.const_defined?(sym, inherit=true) -> true or false
2605 * mod.const_defined?(str, inherit=true) -> true or false
2606 *
2607 * Says whether _mod_ or its ancestors have a constant with the given name:
2608 *
2609 * Float.const_defined?(:EPSILON) #=> true, found in Float itself
2610 * Float.const_defined?("String") #=> true, found in Object (ancestor)
2611 * BasicObject.const_defined?(:Hash) #=> false
2612 *
2613 * If _mod_ is a +Module+, additionally +Object+ and its ancestors are checked:
2614 *
2615 * Math.const_defined?(:String) #=> true, found in Object
2616 *
2617 * In each of the checked classes or modules, if the constant is not present
2618 * but there is an autoload for it, +true+ is returned directly without
2619 * autoloading:
2620 *
2621 * module Admin
2622 * autoload :User, 'admin/user'
2623 * end
2624 * Admin.const_defined?(:User) #=> true
2625 *
2626 * If the constant is not found the callback +const_missing+ is *not* called
2627 * and the method returns +false+.
2628 *
2629 * If +inherit+ is false, the lookup only checks the constants in the receiver:
2630 *
2631 * IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor)
2632 * IO.const_defined?(:SYNC, false) #=> false, not found in IO itself
2633 *
2634 * In this case, the same logic for autoloading applies.
2635 *
2636 * If the argument is not a valid constant name a +NameError+ is raised with the
2637 * message "wrong constant name _name_":
2638 *
2639 * Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar
2640 *
2641 */
2642
2643static VALUE
2644rb_mod_const_defined(int argc, VALUE *argv, VALUE mod)
2645{
2646 VALUE name, recur;
2647 rb_encoding *enc;
2648 const char *pbeg, *p, *path, *pend;
2649 ID id;
2650
2651 rb_check_arity(argc, 1, 2);
2652 name = argv[0];
2653 recur = (argc == 1) ? Qtrue : argv[1];
2654
2655 if (SYMBOL_P(name)) {
2656 if (!rb_is_const_sym(name)) goto wrong_name;
2657 id = rb_check_id(&name);
2658 if (!id) return Qfalse;
2659 return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id);
2660 }
2661
2662 path = StringValuePtr(name);
2663 enc = rb_enc_get(name);
2664
2665 if (!rb_enc_asciicompat(enc)) {
2666 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2667 }
2668
2669 pbeg = p = path;
2670 pend = path + RSTRING_LEN(name);
2671
2672 if (p >= pend || !*p) {
2673 goto wrong_name;
2674 }
2675
2676 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2677 mod = rb_cObject;
2678 p += 2;
2679 pbeg = p;
2680 }
2681
2682 while (p < pend) {
2683 VALUE part;
2684 long len, beglen;
2685
2686 while (p < pend && *p != ':') p++;
2687
2688 if (pbeg == p) goto wrong_name;
2689
2690 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2691 beglen = pbeg-path;
2692
2693 if (p < pend && p[0] == ':') {
2694 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2695 p += 2;
2696 pbeg = p;
2697 }
2698
2699 if (!id) {
2700 part = rb_str_subseq(name, beglen, len);
2701 OBJ_FREEZE(part);
2702 if (!rb_is_const_name(part)) {
2703 name = part;
2704 goto wrong_name;
2705 }
2706 else {
2707 return Qfalse;
2708 }
2709 }
2710 if (!rb_is_const_id(id)) {
2711 name = ID2SYM(id);
2712 goto wrong_name;
2713 }
2714
2715#if 0
2716 mod = rb_const_search(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
2717 if (UNDEF_P(mod)) return Qfalse;
2718#else
2719 if (!RTEST(recur)) {
2720 if (!rb_const_defined_at(mod, id))
2721 return Qfalse;
2722 if (p == pend) return Qtrue;
2723 mod = rb_const_get_at(mod, id);
2724 }
2725 else if (beglen == 0) {
2726 if (!rb_const_defined(mod, id))
2727 return Qfalse;
2728 if (p == pend) return Qtrue;
2729 mod = rb_const_get(mod, id);
2730 }
2731 else {
2732 if (!rb_const_defined_from(mod, id))
2733 return Qfalse;
2734 if (p == pend) return Qtrue;
2735 mod = rb_const_get_from(mod, id);
2736 }
2737#endif
2738
2739 if (p < pend && !RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2740 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2741 QUOTE(name));
2742 }
2743 }
2744
2745 return Qtrue;
2746
2747 wrong_name:
2748 rb_name_err_raise(wrong_constant_name, mod, name);
2750}
2751
2752/*
2753 * call-seq:
2754 * mod.const_source_location(sym, inherit=true) -> [String, Integer]
2755 * mod.const_source_location(str, inherit=true) -> [String, Integer]
2756 *
2757 * Returns the Ruby source filename and line number containing the definition
2758 * of the constant specified. If the named constant is not found, +nil+ is returned.
2759 * If the constant is found, but its source location can not be extracted
2760 * (constant is defined in C code), empty array is returned.
2761 *
2762 * _inherit_ specifies whether to lookup in <code>mod.ancestors</code> (+true+
2763 * by default).
2764 *
2765 * # test.rb:
2766 * class A # line 1
2767 * C1 = 1
2768 * C2 = 2
2769 * end
2770 *
2771 * module M # line 6
2772 * C3 = 3
2773 * end
2774 *
2775 * class B < A # line 10
2776 * include M
2777 * C4 = 4
2778 * end
2779 *
2780 * class A # continuation of A definition
2781 * C2 = 8 # constant redefinition; warned yet allowed
2782 * end
2783 *
2784 * p B.const_source_location('C4') # => ["test.rb", 12]
2785 * p B.const_source_location('C3') # => ["test.rb", 7]
2786 * p B.const_source_location('C1') # => ["test.rb", 2]
2787 *
2788 * p B.const_source_location('C3', false) # => nil -- don't lookup in ancestors
2789 *
2790 * p A.const_source_location('C2') # => ["test.rb", 16] -- actual (last) definition place
2791 *
2792 * p Object.const_source_location('B') # => ["test.rb", 10] -- top-level constant could be looked through Object
2793 * p Object.const_source_location('A') # => ["test.rb", 1] -- class reopening is NOT considered new definition
2794 *
2795 * p B.const_source_location('A') # => ["test.rb", 1] -- because Object is in ancestors
2796 * p M.const_source_location('A') # => ["test.rb", 1] -- Object is not ancestor, but additionally checked for modules
2797 *
2798 * p Object.const_source_location('A::C1') # => ["test.rb", 2] -- nesting is supported
2799 * p Object.const_source_location('String') # => [] -- constant is defined in C code
2800 *
2801 *
2802 */
2803static VALUE
2804rb_mod_const_source_location(int argc, VALUE *argv, VALUE mod)
2805{
2806 VALUE name, recur, loc = Qnil;
2807 rb_encoding *enc;
2808 const char *pbeg, *p, *path, *pend;
2809 ID id;
2810
2811 rb_check_arity(argc, 1, 2);
2812 name = argv[0];
2813 recur = (argc == 1) ? Qtrue : argv[1];
2814
2815 if (SYMBOL_P(name)) {
2816 if (!rb_is_const_sym(name)) goto wrong_name;
2817 id = rb_check_id(&name);
2818 if (!id) return Qnil;
2819 return RTEST(recur) ? rb_const_source_location(mod, id) : rb_const_source_location_at(mod, id);
2820 }
2821
2822 path = StringValuePtr(name);
2823 enc = rb_enc_get(name);
2824
2825 if (!rb_enc_asciicompat(enc)) {
2826 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
2827 }
2828
2829 pbeg = p = path;
2830 pend = path + RSTRING_LEN(name);
2831
2832 if (p >= pend || !*p) {
2833 goto wrong_name;
2834 }
2835
2836 if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
2837 mod = rb_cObject;
2838 p += 2;
2839 pbeg = p;
2840 }
2841
2842 while (p < pend) {
2843 VALUE part;
2844 long len, beglen;
2845
2846 while (p < pend && *p != ':') p++;
2847
2848 if (pbeg == p) goto wrong_name;
2849
2850 id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
2851 beglen = pbeg-path;
2852
2853 if (p < pend && p[0] == ':') {
2854 if (p + 2 >= pend || p[1] != ':') goto wrong_name;
2855 p += 2;
2856 pbeg = p;
2857 }
2858
2859 if (!id) {
2860 part = rb_str_subseq(name, beglen, len);
2861 OBJ_FREEZE(part);
2862 if (!rb_is_const_name(part)) {
2863 name = part;
2864 goto wrong_name;
2865 }
2866 else {
2867 return Qnil;
2868 }
2869 }
2870 if (!rb_is_const_id(id)) {
2871 name = ID2SYM(id);
2872 goto wrong_name;
2873 }
2874 if (p < pend) {
2875 if (RTEST(recur)) {
2876 mod = rb_const_get(mod, id);
2877 }
2878 else {
2879 mod = rb_const_get_at(mod, id);
2880 }
2881 if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
2882 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
2883 QUOTE(name));
2884 }
2885 }
2886 else {
2887 if (RTEST(recur)) {
2888 loc = rb_const_source_location(mod, id);
2889 }
2890 else {
2891 loc = rb_const_source_location_at(mod, id);
2892 }
2893 break;
2894 }
2895 recur = Qfalse;
2896 }
2897
2898 return loc;
2899
2900 wrong_name:
2901 rb_name_err_raise(wrong_constant_name, mod, name);
2903}
2904
2905/*
2906 * call-seq:
2907 * obj.instance_variable_get(symbol) -> obj
2908 * obj.instance_variable_get(string) -> obj
2909 *
2910 * Returns the value of the given instance variable, or nil if the
2911 * instance variable is not set. The <code>@</code> part of the
2912 * variable name should be included for regular instance
2913 * variables. Throws a NameError exception if the
2914 * supplied symbol is not valid as an instance variable name.
2915 * String arguments are converted to symbols.
2916 *
2917 * class Fred
2918 * def initialize(p1, p2)
2919 * @a, @b = p1, p2
2920 * end
2921 * end
2922 * fred = Fred.new('cat', 99)
2923 * fred.instance_variable_get(:@a) #=> "cat"
2924 * fred.instance_variable_get("@b") #=> 99
2925 */
2926
2927static VALUE
2928rb_obj_ivar_get(VALUE obj, VALUE iv)
2929{
2930 ID id = id_for_var(obj, iv, instance);
2931
2932 if (!id) {
2933 return Qnil;
2934 }
2935 return rb_ivar_get(obj, id);
2936}
2937
2938/*
2939 * call-seq:
2940 * obj.instance_variable_set(symbol, obj) -> obj
2941 * obj.instance_variable_set(string, obj) -> obj
2942 *
2943 * Sets the instance variable named by <i>symbol</i> to the given
2944 * object. This may circumvent the encapsulation intended by
2945 * the author of the class, so it should be used with care.
2946 * The variable does not have to exist prior to this call.
2947 * If the instance variable name is passed as a string, that string
2948 * is converted to a symbol.
2949 *
2950 * class Fred
2951 * def initialize(p1, p2)
2952 * @a, @b = p1, p2
2953 * end
2954 * end
2955 * fred = Fred.new('cat', 99)
2956 * fred.instance_variable_set(:@a, 'dog') #=> "dog"
2957 * fred.instance_variable_set(:@c, 'cat') #=> "cat"
2958 * fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
2959 */
2960
2961static VALUE
2962rb_obj_ivar_set_m(VALUE obj, VALUE iv, VALUE val)
2963{
2964 ID id = id_for_var(obj, iv, instance);
2965 if (!id) id = rb_intern_str(iv);
2966 return rb_ivar_set(obj, id, val);
2967}
2968
2969/*
2970 * call-seq:
2971 * obj.instance_variable_defined?(symbol) -> true or false
2972 * obj.instance_variable_defined?(string) -> true or false
2973 *
2974 * Returns <code>true</code> if the given instance variable is
2975 * defined in <i>obj</i>.
2976 * String arguments are converted to symbols.
2977 *
2978 * class Fred
2979 * def initialize(p1, p2)
2980 * @a, @b = p1, p2
2981 * end
2982 * end
2983 * fred = Fred.new('cat', 99)
2984 * fred.instance_variable_defined?(:@a) #=> true
2985 * fred.instance_variable_defined?("@b") #=> true
2986 * fred.instance_variable_defined?("@c") #=> false
2987 */
2988
2989static VALUE
2990rb_obj_ivar_defined(VALUE obj, VALUE iv)
2991{
2992 ID id = id_for_var(obj, iv, instance);
2993
2994 if (!id) {
2995 return Qfalse;
2996 }
2997 return rb_ivar_defined(obj, id);
2998}
2999
3000/*
3001 * call-seq:
3002 * mod.class_variable_get(symbol) -> obj
3003 * mod.class_variable_get(string) -> obj
3004 *
3005 * Returns the value of the given class variable (or throws a
3006 * NameError exception). The <code>@@</code> part of the
3007 * variable name should be included for regular class variables.
3008 * String arguments are converted to symbols.
3009 *
3010 * class Fred
3011 * @@foo = 99
3012 * end
3013 * Fred.class_variable_get(:@@foo) #=> 99
3014 */
3015
3016static VALUE
3017rb_mod_cvar_get(VALUE obj, VALUE iv)
3018{
3019 ID id = id_for_var(obj, iv, class);
3020
3021 if (!id) {
3022 rb_name_err_raise("uninitialized class variable %1$s in %2$s",
3023 obj, iv);
3024 }
3025 return rb_cvar_get(obj, id);
3026}
3027
3028/*
3029 * call-seq:
3030 * obj.class_variable_set(symbol, obj) -> obj
3031 * obj.class_variable_set(string, obj) -> obj
3032 *
3033 * Sets the class variable named by <i>symbol</i> to the given
3034 * object.
3035 * If the class variable name is passed as a string, that string
3036 * is converted to a symbol.
3037 *
3038 * class Fred
3039 * @@foo = 99
3040 * def foo
3041 * @@foo
3042 * end
3043 * end
3044 * Fred.class_variable_set(:@@foo, 101) #=> 101
3045 * Fred.new.foo #=> 101
3046 */
3047
3048static VALUE
3049rb_mod_cvar_set(VALUE obj, VALUE iv, VALUE val)
3050{
3051 ID id = id_for_var(obj, iv, class);
3052 if (!id) id = rb_intern_str(iv);
3053 rb_cvar_set(obj, id, val);
3054 return val;
3055}
3056
3057/*
3058 * call-seq:
3059 * obj.class_variable_defined?(symbol) -> true or false
3060 * obj.class_variable_defined?(string) -> true or false
3061 *
3062 * Returns <code>true</code> if the given class variable is defined
3063 * in <i>obj</i>.
3064 * String arguments are converted to symbols.
3065 *
3066 * class Fred
3067 * @@foo = 99
3068 * end
3069 * Fred.class_variable_defined?(:@@foo) #=> true
3070 * Fred.class_variable_defined?(:@@bar) #=> false
3071 */
3072
3073static VALUE
3074rb_mod_cvar_defined(VALUE obj, VALUE iv)
3075{
3076 ID id = id_for_var(obj, iv, class);
3077
3078 if (!id) {
3079 return Qfalse;
3080 }
3081 return rb_cvar_defined(obj, id);
3082}
3083
3084/*
3085 * call-seq:
3086 * mod.singleton_class? -> true or false
3087 *
3088 * Returns <code>true</code> if <i>mod</i> is a singleton class or
3089 * <code>false</code> if it is an ordinary class or module.
3090 *
3091 * class C
3092 * end
3093 * C.singleton_class? #=> false
3094 * C.singleton_class.singleton_class? #=> true
3095 */
3096
3097static VALUE
3098rb_mod_singleton_p(VALUE klass)
3099{
3100 return RBOOL(RCLASS_SINGLETON_P(klass));
3101}
3102
3104static const struct conv_method_tbl {
3105 const char method[6];
3106 unsigned short id;
3107} conv_method_names[] = {
3108#define M(n) {#n, (unsigned short)idTo_##n}
3109 M(int),
3110 M(ary),
3111 M(str),
3112 M(sym),
3113 M(hash),
3114 M(proc),
3115 M(io),
3116 M(a),
3117 M(s),
3118 M(i),
3119 M(f),
3120 M(r),
3121#undef M
3122};
3123#define IMPLICIT_CONVERSIONS 7
3124
3125static int
3126conv_method_index(const char *method)
3127{
3128 static const char prefix[] = "to_";
3129
3130 if (strncmp(prefix, method, sizeof(prefix)-1) == 0) {
3131 const char *const meth = &method[sizeof(prefix)-1];
3132 int i;
3133 for (i=0; i < numberof(conv_method_names); i++) {
3134 if (conv_method_names[i].method[0] == meth[0] &&
3135 strcmp(conv_method_names[i].method, meth) == 0) {
3136 return i;
3137 }
3138 }
3139 }
3140 return numberof(conv_method_names);
3141}
3142
3143static VALUE
3144convert_type_with_id(VALUE val, const char *tname, ID method, int raise, int index)
3145{
3146 VALUE r = rb_check_funcall(val, method, 0, 0);
3147 if (UNDEF_P(r)) {
3148 if (raise) {
3149 const char *msg =
3150 ((index < 0 ? conv_method_index(rb_id2name(method)) : index)
3151 < IMPLICIT_CONVERSIONS) ?
3152 "no implicit conversion of" : "can't convert";
3153 const char *cname = NIL_P(val) ? "nil" :
3154 val == Qtrue ? "true" :
3155 val == Qfalse ? "false" :
3156 NULL;
3157 if (cname)
3158 rb_raise(rb_eTypeError, "%s %s into %s", msg, cname, tname);
3159 rb_raise(rb_eTypeError, "%s %"PRIsVALUE" into %s", msg,
3160 rb_obj_class(val),
3161 tname);
3162 }
3163 return Qnil;
3164 }
3165 return r;
3166}
3167
3168static VALUE
3169convert_type(VALUE val, const char *tname, const char *method, int raise)
3170{
3171 int i = conv_method_index(method);
3172 ID m = i < numberof(conv_method_names) ?
3173 conv_method_names[i].id : rb_intern(method);
3174 return convert_type_with_id(val, tname, m, raise, i);
3175}
3176
3178NORETURN(static void conversion_mismatch(VALUE, const char *, const char *, VALUE));
3179static void
3180conversion_mismatch(VALUE val, const char *tname, const char *method, VALUE result)
3181{
3182 VALUE cname = rb_obj_class(val);
3183 rb_raise(rb_eTypeError,
3184 "can't convert %"PRIsVALUE" to %s (%"PRIsVALUE"#%s gives %"PRIsVALUE")",
3185 cname, tname, cname, method, rb_obj_class(result));
3186}
3187
3188VALUE
3189rb_convert_type(VALUE val, int type, const char *tname, const char *method)
3190{
3191 VALUE v;
3192
3193 if (TYPE(val) == type) return val;
3194 v = convert_type(val, tname, method, TRUE);
3195 if (TYPE(v) != type) {
3196 conversion_mismatch(val, tname, method, v);
3197 }
3198 return v;
3199}
3200
3202VALUE
3203rb_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
3204{
3205 VALUE v;
3206
3207 if (TYPE(val) == type) return val;
3208 v = convert_type_with_id(val, tname, method, TRUE, -1);
3209 if (TYPE(v) != type) {
3210 conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v);
3211 }
3212 return v;
3213}
3214
3215VALUE
3216rb_check_convert_type(VALUE val, int type, const char *tname, const char *method)
3217{
3218 VALUE v;
3219
3220 /* always convert T_DATA */
3221 if (TYPE(val) == type && type != T_DATA) return val;
3222 v = convert_type(val, tname, method, FALSE);
3223 if (NIL_P(v)) return Qnil;
3224 if (TYPE(v) != type) {
3225 conversion_mismatch(val, tname, method, v);
3226 }
3227 return v;
3228}
3229
3231VALUE
3232rb_check_convert_type_with_id(VALUE val, int type, const char *tname, ID method)
3233{
3234 VALUE v;
3235
3236 /* always convert T_DATA */
3237 if (TYPE(val) == type && type != T_DATA) return val;
3238 v = convert_type_with_id(val, tname, method, FALSE, -1);
3239 if (NIL_P(v)) return Qnil;
3240 if (TYPE(v) != type) {
3241 conversion_mismatch(val, tname, RSTRING_PTR(rb_id2str(method)), v);
3242 }
3243 return v;
3244}
3245
3246#define try_to_int(val, mid, raise) \
3247 convert_type_with_id(val, "Integer", mid, raise, -1)
3248
3249ALWAYS_INLINE(static VALUE rb_to_integer_with_id_exception(VALUE val, const char *method, ID mid, int raise));
3250/* Integer specific rb_check_convert_type_with_id */
3251static inline VALUE
3252rb_to_integer_with_id_exception(VALUE val, const char *method, ID mid, int raise)
3253{
3254 // We need to pop the lazily pushed frame when not raising an exception.
3255 rb_control_frame_t *current_cfp;
3256 VALUE v;
3257
3258 if (RB_INTEGER_TYPE_P(val)) return val;
3259 current_cfp = GET_EC()->cfp;
3260 rb_yjit_lazy_push_frame(GET_EC()->cfp->pc);
3261 v = try_to_int(val, mid, raise);
3262 if (!raise && NIL_P(v)) {
3263 GET_EC()->cfp = current_cfp;
3264 return Qnil;
3265 }
3266 if (!RB_INTEGER_TYPE_P(v)) {
3267 conversion_mismatch(val, "Integer", method, v);
3268 }
3269 GET_EC()->cfp = current_cfp;
3270 return v;
3271}
3272#define rb_to_integer(val, method, mid) \
3273 rb_to_integer_with_id_exception(val, method, mid, TRUE)
3274
3275VALUE
3276rb_check_to_integer(VALUE val, const char *method)
3277{
3278 VALUE v;
3279
3280 if (RB_INTEGER_TYPE_P(val)) return val;
3281 v = convert_type(val, "Integer", method, FALSE);
3282 if (!RB_INTEGER_TYPE_P(v)) {
3283 return Qnil;
3284 }
3285 return v;
3286}
3287
3288VALUE
3290{
3291 return rb_to_integer(val, "to_int", idTo_int);
3292}
3293
3294VALUE
3296{
3297 if (RB_INTEGER_TYPE_P(val)) return val;
3298 val = try_to_int(val, idTo_int, FALSE);
3299 if (RB_INTEGER_TYPE_P(val)) return val;
3300 return Qnil;
3301}
3302
3303static VALUE
3304rb_check_to_i(VALUE val)
3305{
3306 if (RB_INTEGER_TYPE_P(val)) return val;
3307 val = try_to_int(val, idTo_i, FALSE);
3308 if (RB_INTEGER_TYPE_P(val)) return val;
3309 return Qnil;
3310}
3311
3312static VALUE
3313rb_convert_to_integer(VALUE val, int base, int raise_exception)
3314{
3315 VALUE tmp;
3316
3317 if (base) {
3318 tmp = rb_check_string_type(val);
3319
3320 if (! NIL_P(tmp)) {
3321 val = tmp;
3322 }
3323 else if (! raise_exception) {
3324 return Qnil;
3325 }
3326 else {
3327 rb_raise(rb_eArgError, "base specified for non string value");
3328 }
3329 }
3330 if (RB_FLOAT_TYPE_P(val)) {
3331 double f = RFLOAT_VALUE(val);
3332 if (!raise_exception && !isfinite(f)) return Qnil;
3333 if (FIXABLE(f)) return LONG2FIX((long)f);
3334 return rb_dbl2big(f);
3335 }
3336 else if (RB_INTEGER_TYPE_P(val)) {
3337 return val;
3338 }
3339 else if (RB_TYPE_P(val, T_STRING)) {
3340 return rb_str_convert_to_inum(val, base, TRUE, raise_exception);
3341 }
3342 else if (NIL_P(val)) {
3343 if (!raise_exception) return Qnil;
3344 rb_raise(rb_eTypeError, "can't convert nil into Integer");
3345 }
3346
3347 tmp = rb_protect(rb_check_to_int, val, NULL);
3348 if (RB_INTEGER_TYPE_P(tmp)) return tmp;
3349 rb_set_errinfo(Qnil);
3350 if (!NIL_P(tmp = rb_check_string_type(val))) {
3351 return rb_str_convert_to_inum(tmp, base, TRUE, raise_exception);
3352 }
3353
3354 if (!raise_exception) {
3355 VALUE result = rb_protect(rb_check_to_i, val, NULL);
3356 rb_set_errinfo(Qnil);
3357 return result;
3358 }
3359
3360 return rb_to_integer(val, "to_i", idTo_i);
3361}
3362
3363VALUE
3365{
3366 return rb_convert_to_integer(val, 0, TRUE);
3367}
3368
3369VALUE
3370rb_check_integer_type(VALUE val)
3371{
3372 return rb_to_integer_with_id_exception(val, "to_int", idTo_int, FALSE);
3373}
3374
3375int
3376rb_bool_expected(VALUE obj, const char *flagname, int raise)
3377{
3378 switch (obj) {
3379 case Qtrue:
3380 return TRUE;
3381 case Qfalse:
3382 return FALSE;
3383 default: {
3384 static const char message[] = "expected true or false as %s: %+"PRIsVALUE;
3385 if (raise) {
3386 rb_raise(rb_eArgError, message, flagname, obj);
3387 }
3388 rb_warning(message, flagname, obj);
3389 return !NIL_P(obj);
3390 }
3391 }
3392}
3393
3394int
3395rb_opts_exception_p(VALUE opts, int default_value)
3396{
3397 static const ID kwds[1] = {idException};
3398 VALUE exception;
3399 if (rb_get_kwargs(opts, kwds, 0, 1, &exception))
3400 return rb_bool_expected(exception, "exception", TRUE);
3401 return default_value;
3402}
3403
3404static VALUE
3405rb_f_integer1(rb_execution_context_t *ec, VALUE obj, VALUE arg)
3406{
3407 return rb_convert_to_integer(arg, 0, TRUE);
3408}
3409
3410static VALUE
3411rb_f_integer(rb_execution_context_t *ec, VALUE obj, VALUE arg, VALUE base, VALUE exception)
3412{
3413 int exc = rb_bool_expected(exception, "exception", TRUE);
3414 return rb_convert_to_integer(arg, NUM2INT(base), exc);
3415}
3416
3417static bool
3418is_digit_char(unsigned char c, int base)
3419{
3421 return (i >= 0 && i < base);
3422}
3423
3424static double
3425rb_cstr_to_dbl_raise(const char *p, rb_encoding *enc, int badcheck, int raise, int *error)
3426{
3427 const char *q;
3428 char *end;
3429 double d;
3430 const char *ellipsis = "";
3431 int w;
3432 enum {max_width = 20};
3433#define OutOfRange() ((end - p > max_width) ? \
3434 (w = max_width, ellipsis = "...") : \
3435 (w = (int)(end - p), ellipsis = ""))
3436 /* p...end has been parsed with strtod, should be ASCII-only */
3437
3438 if (!p) return 0.0;
3439 q = p;
3440 while (ISSPACE(*p)) p++;
3441
3442 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3443 return 0.0;
3444 }
3445
3446 d = strtod(p, &end);
3447 if (errno == ERANGE) {
3448 OutOfRange();
3449 rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3450 errno = 0;
3451 }
3452 if (p == end) {
3453 if (badcheck) {
3454 goto bad;
3455 }
3456 return d;
3457 }
3458 if (*end) {
3459 char buf[DBL_DIG * 4 + 10];
3460 char *n = buf;
3461 char *const init_e = buf + DBL_DIG * 4;
3462 char *e = init_e;
3463 char prev = 0;
3464 int dot_seen = FALSE;
3465 int base = 10;
3466 char exp_letter = 'e';
3467
3468 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3469 if (*p == '0') {
3470 prev = *n++ = '0';
3471 switch (*++p) {
3472 case 'x': case 'X':
3473 prev = *n++ = 'x';
3474 base = 16;
3475 exp_letter = 'p';
3476 if (*++p != '0') break;
3477 /* fallthrough */
3478 case '0': /* squeeze successive zeros */
3479 while (*++p == '0');
3480 break;
3481 }
3482 }
3483 while (p < end && n < e) prev = *n++ = *p++;
3484 while (*p) {
3485 if (*p == '_') {
3486 /* remove an underscore between digits */
3487 if (n == buf ||
3488 !is_digit_char(prev, base) ||
3489 !is_digit_char(*++p, base)) {
3490 if (badcheck) goto bad;
3491 break;
3492 }
3493 }
3494 prev = *p++;
3495 if (e == init_e && (rb_tolower(prev) == exp_letter)) {
3496 e = buf + sizeof(buf) - 1;
3497 *n++ = prev;
3498 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3499 if (*p == '0') {
3500 prev = *n++ = '0';
3501 while (*++p == '0');
3502 }
3503
3504 /* reset base to decimal for underscore check of
3505 * binary exponent part */
3506 base = 10;
3507 continue;
3508 }
3509 else if (ISSPACE(prev)) {
3510 while (ISSPACE(*p)) ++p;
3511 if (*p) {
3512 if (badcheck) goto bad;
3513 break;
3514 }
3515 }
3516 else if (prev == '.' ? dot_seen++ : !is_digit_char(prev, base)) {
3517 if (badcheck) goto bad;
3518 break;
3519 }
3520 if (n < e) *n++ = prev;
3521 }
3522 *n = '\0';
3523 p = buf;
3524
3525 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3526 return 0.0;
3527 }
3528
3529 d = strtod(p, &end);
3530 if (errno == ERANGE) {
3531 OutOfRange();
3532 rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3533 errno = 0;
3534 }
3535 if (badcheck) {
3536 if (!end || p == end) goto bad;
3537 while (*end && ISSPACE(*end)) end++;
3538 if (*end) goto bad;
3539 }
3540 }
3541 if (errno == ERANGE) {
3542 errno = 0;
3543 OutOfRange();
3544 rb_raise(rb_eArgError, "Float %.*s%s out of range", w, q, ellipsis);
3545 }
3546 return d;
3547
3548 bad:
3549 if (raise) {
3550 VALUE s = rb_enc_str_new_cstr(q, enc);
3551 rb_raise(rb_eArgError, "invalid value for Float(): %+"PRIsVALUE, s);
3552 UNREACHABLE_RETURN(nan(""));
3553 }
3554 else {
3555 if (error) *error = 1;
3556 return 0.0;
3557 }
3558}
3559
3560double
3561rb_cstr_to_dbl(const char *p, int badcheck)
3562{
3563 return rb_cstr_to_dbl_raise(p, NULL, badcheck, TRUE, NULL);
3564}
3565
3566static double
3567rb_str_to_dbl_raise(VALUE str, int badcheck, int raise, int *error)
3568{
3569 char *s;
3570 long len;
3571 double ret;
3572 VALUE v = 0;
3573
3574 StringValue(str);
3576 s = RSTRING_PTR(str);
3577 len = RSTRING_LEN(str);
3578 if (s) {
3579 if (badcheck && memchr(s, '\0', len)) {
3580 if (raise)
3581 rb_raise(rb_eArgError, "string for Float contains null byte");
3582 else {
3583 if (error) *error = 1;
3584 return 0.0;
3585 }
3586 }
3587 if (s[len]) { /* no sentinel somehow */
3588 char *p = ALLOCV(v, (size_t)len + 1);
3589 MEMCPY(p, s, char, len);
3590 p[len] = '\0';
3591 s = p;
3592 }
3593 }
3594 ret = rb_cstr_to_dbl_raise(s, rb_enc_get(str), badcheck, raise, error);
3595 if (v)
3596 ALLOCV_END(v);
3597 else
3598 RB_GC_GUARD(str);
3599 return ret;
3600}
3601
3602FUNC_MINIMIZED(double rb_str_to_dbl(VALUE str, int badcheck));
3603
3604double
3605rb_str_to_dbl(VALUE str, int badcheck)
3606{
3607 return rb_str_to_dbl_raise(str, badcheck, TRUE, NULL);
3608}
3609
3611#define fix2dbl_without_to_f(x) (double)FIX2LONG(x)
3612#define big2dbl_without_to_f(x) rb_big2dbl(x)
3613#define int2dbl_without_to_f(x) \
3614 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : big2dbl_without_to_f(x))
3615#define num2dbl_without_to_f(x) \
3616 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : \
3617 RB_BIGNUM_TYPE_P(x) ? big2dbl_without_to_f(x) : \
3618 (Check_Type(x, T_FLOAT), RFLOAT_VALUE(x)))
3619static inline double
3620rat2dbl_without_to_f(VALUE x)
3621{
3622 VALUE num = rb_rational_num(x);
3623 VALUE den = rb_rational_den(x);
3624 return num2dbl_without_to_f(num) / num2dbl_without_to_f(den);
3625}
3626
3627#define special_const_to_float(val, pre, post) \
3628 switch (val) { \
3629 case Qnil: \
3630 rb_raise_static(rb_eTypeError, pre "nil" post); \
3631 case Qtrue: \
3632 rb_raise_static(rb_eTypeError, pre "true" post); \
3633 case Qfalse: \
3634 rb_raise_static(rb_eTypeError, pre "false" post); \
3635 }
3638static inline void
3639conversion_to_float(VALUE val)
3640{
3641 special_const_to_float(val, "can't convert ", " into Float");
3642}
3643
3644static inline void
3645implicit_conversion_to_float(VALUE val)
3646{
3647 special_const_to_float(val, "no implicit conversion to float from ", "");
3648}
3649
3650static int
3651to_float(VALUE *valp, int raise_exception)
3652{
3653 VALUE val = *valp;
3654 if (SPECIAL_CONST_P(val)) {
3655 if (FIXNUM_P(val)) {
3656 *valp = DBL2NUM(fix2dbl_without_to_f(val));
3657 return T_FLOAT;
3658 }
3659 else if (FLONUM_P(val)) {
3660 return T_FLOAT;
3661 }
3662 else if (raise_exception) {
3663 conversion_to_float(val);
3664 }
3665 }
3666 else {
3667 int type = BUILTIN_TYPE(val);
3668 switch (type) {
3669 case T_FLOAT:
3670 return T_FLOAT;
3671 case T_BIGNUM:
3672 *valp = DBL2NUM(big2dbl_without_to_f(val));
3673 return T_FLOAT;
3674 case T_RATIONAL:
3675 *valp = DBL2NUM(rat2dbl_without_to_f(val));
3676 return T_FLOAT;
3677 case T_STRING:
3678 return T_STRING;
3679 }
3680 }
3681 return T_NONE;
3682}
3683
3684static VALUE
3685convert_type_to_float_protected(VALUE val)
3686{
3687 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3688}
3689
3690static VALUE
3691rb_convert_to_float(VALUE val, int raise_exception)
3692{
3693 switch (to_float(&val, raise_exception)) {
3694 case T_FLOAT:
3695 return val;
3696 case T_STRING:
3697 if (!raise_exception) {
3698 int e = 0;
3699 double x = rb_str_to_dbl_raise(val, TRUE, raise_exception, &e);
3700 return e ? Qnil : DBL2NUM(x);
3701 }
3702 return DBL2NUM(rb_str_to_dbl(val, TRUE));
3703 case T_NONE:
3704 if (SPECIAL_CONST_P(val) && !raise_exception)
3705 return Qnil;
3706 }
3707
3708 if (!raise_exception) {
3709 int state;
3710 VALUE result = rb_protect(convert_type_to_float_protected, val, &state);
3711 if (state) rb_set_errinfo(Qnil);
3712 return result;
3713 }
3714
3715 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3716}
3717
3718FUNC_MINIMIZED(VALUE rb_Float(VALUE val));
3719
3720VALUE
3722{
3723 return rb_convert_to_float(val, TRUE);
3724}
3725
3726static VALUE
3727rb_f_float1(rb_execution_context_t *ec, VALUE obj, VALUE arg)
3728{
3729 return rb_convert_to_float(arg, TRUE);
3730}
3731
3732static VALUE
3733rb_f_float(rb_execution_context_t *ec, VALUE obj, VALUE arg, VALUE opts)
3734{
3735 int exception = rb_bool_expected(opts, "exception", TRUE);
3736 return rb_convert_to_float(arg, exception);
3737}
3738
3739static VALUE
3740numeric_to_float(VALUE val)
3741{
3742 if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3743 rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into Float",
3744 rb_obj_class(val));
3745 }
3746 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3747}
3748
3749VALUE
3751{
3752 switch (to_float(&val, TRUE)) {
3753 case T_FLOAT:
3754 return val;
3755 }
3756 return numeric_to_float(val);
3757}
3758
3759VALUE
3761{
3762 if (RB_FLOAT_TYPE_P(val)) return val;
3763 if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3764 return Qnil;
3765 }
3766 return rb_check_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3767}
3768
3769static inline int
3770basic_to_f_p(VALUE klass)
3771{
3772 return rb_method_basic_definition_p(klass, id_to_f);
3773}
3774
3776double
3777rb_num_to_dbl(VALUE val)
3778{
3779 if (SPECIAL_CONST_P(val)) {
3780 if (FIXNUM_P(val)) {
3781 if (basic_to_f_p(rb_cInteger))
3782 return fix2dbl_without_to_f(val);
3783 }
3784 else if (FLONUM_P(val)) {
3785 return rb_float_flonum_value(val);
3786 }
3787 else {
3788 conversion_to_float(val);
3789 }
3790 }
3791 else {
3792 switch (BUILTIN_TYPE(val)) {
3793 case T_FLOAT:
3794 return rb_float_noflonum_value(val);
3795 case T_BIGNUM:
3796 if (basic_to_f_p(rb_cInteger))
3797 return big2dbl_without_to_f(val);
3798 break;
3799 case T_RATIONAL:
3800 if (basic_to_f_p(rb_cRational))
3801 return rat2dbl_without_to_f(val);
3802 break;
3803 default:
3804 break;
3805 }
3806 }
3807 val = numeric_to_float(val);
3808 return RFLOAT_VALUE(val);
3809}
3810
3811double
3813{
3814 if (SPECIAL_CONST_P(val)) {
3815 if (FIXNUM_P(val)) {
3816 return fix2dbl_without_to_f(val);
3817 }
3818 else if (FLONUM_P(val)) {
3819 return rb_float_flonum_value(val);
3820 }
3821 else {
3822 implicit_conversion_to_float(val);
3823 }
3824 }
3825 else {
3826 switch (BUILTIN_TYPE(val)) {
3827 case T_FLOAT:
3828 return rb_float_noflonum_value(val);
3829 case T_BIGNUM:
3830 return big2dbl_without_to_f(val);
3831 case T_RATIONAL:
3832 return rat2dbl_without_to_f(val);
3833 case T_STRING:
3834 rb_raise(rb_eTypeError, "no implicit conversion to float from string");
3835 default:
3836 break;
3837 }
3838 }
3839 val = rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3840 return RFLOAT_VALUE(val);
3841}
3842
3843VALUE
3845{
3846 VALUE tmp = rb_check_string_type(val);
3847 if (NIL_P(tmp))
3848 tmp = rb_convert_type_with_id(val, T_STRING, "String", idTo_s);
3849 return tmp;
3850}
3851
3852
3853/*
3854 * call-seq:
3855 * String(object) -> object or new_string
3856 *
3857 * Returns a string converted from +object+.
3858 *
3859 * Tries to convert +object+ to a string
3860 * using +to_str+ first and +to_s+ second:
3861 *
3862 * String([0, 1, 2]) # => "[0, 1, 2]"
3863 * String(0..5) # => "0..5"
3864 * String({foo: 0, bar: 1}) # => "{foo: 0, bar: 1}"
3865 *
3866 * Raises +TypeError+ if +object+ cannot be converted to a string.
3867 */
3868
3869static VALUE
3870rb_f_string(VALUE obj, VALUE arg)
3871{
3872 return rb_String(arg);
3873}
3874
3875VALUE
3877{
3878 VALUE tmp = rb_check_array_type(val);
3879
3880 if (NIL_P(tmp)) {
3881 tmp = rb_check_to_array(val);
3882 if (NIL_P(tmp)) {
3883 return rb_ary_new3(1, val);
3884 }
3885 }
3886 return tmp;
3887}
3888
3889/*
3890 * call-seq:
3891 * Array(object) -> object or new_array
3892 *
3893 * Returns an array converted from +object+.
3894 *
3895 * Tries to convert +object+ to an array
3896 * using +to_ary+ first and +to_a+ second:
3897 *
3898 * Array([0, 1, 2]) # => [0, 1, 2]
3899 * Array({foo: 0, bar: 1}) # => [[:foo, 0], [:bar, 1]]
3900 * Array(0..4) # => [0, 1, 2, 3, 4]
3901 *
3902 * Returns +object+ in an array, <tt>[object]</tt>,
3903 * if +object+ cannot be converted:
3904 *
3905 * Array(:foo) # => [:foo]
3906 *
3907 */
3908
3909static VALUE
3910rb_f_array(VALUE obj, VALUE arg)
3911{
3912 return rb_Array(arg);
3913}
3914
3918VALUE
3920{
3921 VALUE tmp;
3922
3923 if (NIL_P(val)) return rb_hash_new();
3924 tmp = rb_check_hash_type(val);
3925 if (NIL_P(tmp)) {
3926 if (RB_TYPE_P(val, T_ARRAY) && RARRAY_LEN(val) == 0)
3927 return rb_hash_new();
3928 rb_raise(rb_eTypeError, "can't convert %s into Hash", rb_obj_classname(val));
3929 }
3930 return tmp;
3931}
3932
3933/*
3934 * call-seq:
3935 * Hash(object) -> object or new_hash
3936 *
3937 * Returns a hash converted from +object+.
3938 *
3939 * - If +object+ is:
3940 *
3941 * - A hash, returns +object+.
3942 * - An empty array or +nil+, returns an empty hash.
3943 *
3944 * - Otherwise, if <tt>object.to_hash</tt> returns a hash, returns that hash.
3945 * - Otherwise, returns TypeError.
3946 *
3947 * Examples:
3948 *
3949 * Hash({foo: 0, bar: 1}) # => {:foo=>0, :bar=>1}
3950 * Hash(nil) # => {}
3951 * Hash([]) # => {}
3952 *
3953 */
3954
3955static VALUE
3956rb_f_hash(VALUE obj, VALUE arg)
3957{
3958 return rb_Hash(arg);
3959}
3960
3962struct dig_method {
3963 VALUE klass;
3964 int basic;
3965};
3966
3967static ID id_dig;
3968
3969static int
3970dig_basic_p(VALUE obj, struct dig_method *cache)
3971{
3972 VALUE klass = RBASIC_CLASS(obj);
3973 if (klass != cache->klass) {
3974 cache->klass = klass;
3975 cache->basic = rb_method_basic_definition_p(klass, id_dig);
3976 }
3977 return cache->basic;
3978}
3979
3980static void
3981no_dig_method(int found, VALUE recv, ID mid, int argc, const VALUE *argv, VALUE data)
3982{
3983 if (!found) {
3984 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not have #dig method",
3985 CLASS_OF(data));
3986 }
3987}
3988
3990VALUE
3991rb_obj_dig(int argc, VALUE *argv, VALUE obj, VALUE notfound)
3992{
3993 struct dig_method hash = {Qnil}, ary = {Qnil}, strt = {Qnil};
3994
3995 for (; argc > 0; ++argv, --argc) {
3996 if (NIL_P(obj)) return notfound;
3997 if (!SPECIAL_CONST_P(obj)) {
3998 switch (BUILTIN_TYPE(obj)) {
3999 case T_HASH:
4000 if (dig_basic_p(obj, &hash)) {
4001 obj = rb_hash_aref(obj, *argv);
4002 continue;
4003 }
4004 break;
4005 case T_ARRAY:
4006 if (dig_basic_p(obj, &ary)) {
4007 obj = rb_ary_at(obj, *argv);
4008 continue;
4009 }
4010 break;
4011 case T_STRUCT:
4012 if (dig_basic_p(obj, &strt)) {
4013 obj = rb_struct_lookup(obj, *argv);
4014 continue;
4015 }
4016 break;
4017 default:
4018 break;
4019 }
4020 }
4021 return rb_check_funcall_with_hook_kw(obj, id_dig, argc, argv,
4022 no_dig_method, obj,
4024 }
4025 return obj;
4026}
4027
4028/*
4029 * call-seq:
4030 * sprintf(format_string *objects) -> string
4031 *
4032 * Returns the string resulting from formatting +objects+
4033 * into +format_string+.
4034 *
4035 * For details on +format_string+, see
4036 * {Format Specifications}[rdoc-ref:language/format_specifications.rdoc].
4037 */
4038
4039static VALUE
4040f_sprintf(int c, const VALUE *v, VALUE _)
4041{
4042 return rb_f_sprintf(c, v);
4043}
4044
4045static VALUE
4046rb_f_loop_size(VALUE self, VALUE args, VALUE eobj)
4047{
4048 return DBL2NUM(HUGE_VAL);
4049}
4050
4051/*
4052 * Document-class: Class
4053 *
4054 * Classes in Ruby are first-class objects---each is an instance of
4055 * class Class.
4056 *
4057 * Typically, you create a new class by using:
4058 *
4059 * class Name
4060 * # some code describing the class behavior
4061 * end
4062 *
4063 * When a new class is created, an object of type Class is initialized and
4064 * assigned to a global constant (Name in this case).
4065 *
4066 * When <code>Name.new</code> is called to create a new object, the
4067 * #new method in Class is run by default.
4068 * This can be demonstrated by overriding #new in Class:
4069 *
4070 * class Class
4071 * alias old_new new
4072 * def new(*args)
4073 * print "Creating a new ", self.name, "\n"
4074 * old_new(*args)
4075 * end
4076 * end
4077 *
4078 * class Name
4079 * end
4080 *
4081 * n = Name.new
4082 *
4083 * <em>produces:</em>
4084 *
4085 * Creating a new Name
4086 *
4087 * Classes, modules, and objects are interrelated. In the diagram
4088 * that follows, the vertical arrows represent inheritance, and the
4089 * parentheses metaclasses. All metaclasses are instances
4090 * of the class `Class'.
4091 * +---------+ +-...
4092 * | | |
4093 * BasicObject-----|-->(BasicObject)-------|-...
4094 * ^ | ^ |
4095 * | | | |
4096 * Object---------|----->(Object)---------|-...
4097 * ^ | ^ |
4098 * | | | |
4099 * +-------+ | +--------+ |
4100 * | | | | | |
4101 * | Module-|---------|--->(Module)-|-...
4102 * | ^ | | ^ |
4103 * | | | | | |
4104 * | Class-|---------|---->(Class)-|-...
4105 * | ^ | | ^ |
4106 * | +---+ | +----+
4107 * | |
4108 * obj--->OtherClass---------->(OtherClass)-----------...
4109 *
4110 */
4111
4112
4113/*
4114 * Document-class: BasicObject
4115 *
4116 * +BasicObject+ is the parent class of all classes in Ruby.
4117 * In particular, +BasicObject+ is the parent class of class Object,
4118 * which is itself the default parent class of every Ruby class:
4119 *
4120 * class Foo; end
4121 * Foo.superclass # => Object
4122 * Object.superclass # => BasicObject
4123 *
4124 * +BasicObject+ is the only class that has no parent:
4125 *
4126 * BasicObject.superclass # => nil
4127 *
4128 * Class +BasicObject+ can be used to create an object hierarchy
4129 * (e.g., class Delegator) that is independent of Ruby's object hierarchy.
4130 * Such objects:
4131 *
4132 * - Do not have namespace "pollution" from the many methods
4133 * provided in class Object and its included module Kernel.
4134 * - Do not have definitions of common classes,
4135 * and so references to such common classes must be fully qualified
4136 * (+::String+, not +String+).
4137 *
4138 * A variety of strategies can be used to provide useful portions
4139 * of the Standard Library in subclasses of +BasicObject+:
4140 *
4141 * - The immediate subclass could <tt>include Kernel</tt>,
4142 * which would define methods such as +puts+, +exit+, etc.
4143 * - A custom Kernel-like module could be created and included.
4144 * - Delegation can be used via #method_missing:
4145 *
4146 * class MyObjectSystem < BasicObject
4147 * DELEGATE = [:puts, :p]
4148 *
4149 * def method_missing(name, *args, &block)
4150 * return super unless DELEGATE.include? name
4151 * ::Kernel.send(name, *args, &block)
4152 * end
4153 *
4154 * def respond_to_missing?(name, include_private = false)
4155 * DELEGATE.include?(name)
4156 * end
4157 * end
4158 *
4159 * === What's Here
4160 *
4161 * These are the methods defined for \BasicObject:
4162 *
4163 * - ::new: Returns a new \BasicObject instance.
4164 * - #!: Returns the boolean negation of +self+: +true+ or +false+.
4165 * - #!=: Returns whether +self+ and the given object are _not_ equal.
4166 * - #==: Returns whether +self+ and the given object are equivalent.
4167 * - #__id__: Returns the integer object identifier for +self+.
4168 * - #__send__: Calls the method identified by the given symbol.
4169 * - #equal?: Returns whether +self+ and the given object are the same object.
4170 * - #instance_eval: Evaluates the given string or block in the context of +self+.
4171 * - #instance_exec: Executes the given block in the context of +self+, passing the given arguments.
4172 * - #method_missing: Called when +self+ is called with a method it does not define.
4173 * - #singleton_method_added: Called when a singleton method is added to +self+.
4174 * - #singleton_method_removed: Called when a singleton method is removed from +self+.
4175 * - #singleton_method_undefined: Called when a singleton method is undefined in +self+.
4176 *
4177 */
4178
4179/* Document-class: Object
4180 *
4181 * Object is the default root of all Ruby objects. Object inherits from
4182 * BasicObject which allows creating alternate object hierarchies. Methods
4183 * on Object are available to all classes unless explicitly overridden.
4184 *
4185 * Object mixes in the Kernel module, making the built-in kernel functions
4186 * globally accessible. Although the instance methods of Object are defined
4187 * by the Kernel module, we have chosen to document them here for clarity.
4188 *
4189 * When referencing constants in classes inheriting from Object you do not
4190 * need to use the full namespace. For example, referencing +File+ inside
4191 * +YourClass+ will find the top-level File class.
4192 *
4193 * In the descriptions of Object's methods, the parameter <i>symbol</i> refers
4194 * to a symbol, which is either a quoted string or a Symbol (such as
4195 * <code>:name</code>).
4196 *
4197 * == What's Here
4198 *
4199 * First, what's elsewhere. Class \Object:
4200 *
4201 * - Inherits from {class BasicObject}[rdoc-ref:BasicObject@What-27s+Here].
4202 * - Includes {module Kernel}[rdoc-ref:Kernel@What-27s+Here].
4203 *
4204 * Here, class \Object provides methods for:
4205 *
4206 * - {Querying}[rdoc-ref:Object@Querying]
4207 * - {Instance Variables}[rdoc-ref:Object@Instance+Variables]
4208 * - {Other}[rdoc-ref:Object@Other]
4209 *
4210 * === Querying
4211 *
4212 * - #!~: Returns +true+ if +self+ does not match the given object,
4213 * otherwise +false+.
4214 * - #<=>: Returns 0 if +self+ and the given object +object+ are the same
4215 * object, or if <tt>self == object</tt>; otherwise returns +nil+.
4216 * - #===: Implements case equality, effectively the same as calling #==.
4217 * - #eql?: Implements hash equality, effectively the same as calling #==.
4218 * - #kind_of? (aliased as #is_a?): Returns whether given argument is an ancestor
4219 * of the singleton class of +self+.
4220 * - #instance_of?: Returns whether +self+ is an instance of the given class.
4221 * - #instance_variable_defined?: Returns whether the given instance variable
4222 * is defined in +self+.
4223 * - #method: Returns the +Method+ object for the given method in +self+.
4224 * - #methods: Returns an array of symbol names of public and protected methods
4225 * in +self+.
4226 * - #nil?: Returns +false+. (Only +nil+ responds +true+ to method <tt>nil?</tt>.)
4227 * - #object_id: Returns an integer corresponding to +self+ that is unique
4228 * for the current process
4229 * - #private_methods: Returns an array of the symbol names
4230 * of the private methods in +self+.
4231 * - #protected_methods: Returns an array of the symbol names
4232 * of the protected methods in +self+.
4233 * - #public_method: Returns the +Method+ object for the given public method in +self+.
4234 * - #public_methods: Returns an array of the symbol names
4235 * of the public methods in +self+.
4236 * - #respond_to?: Returns whether +self+ responds to the given method.
4237 * - #singleton_class: Returns the singleton class of +self+.
4238 * - #singleton_method: Returns the +Method+ object for the given singleton method
4239 * in +self+.
4240 * - #singleton_methods: Returns an array of the symbol names
4241 * of the singleton methods in +self+.
4242 *
4243 * - #define_singleton_method: Defines a singleton method in +self+
4244 * for the given symbol method-name and block or proc.
4245 * - #extend: Includes the given modules in the singleton class of +self+.
4246 * - #public_send: Calls the given public method in +self+ with the given argument.
4247 * - #send: Calls the given method in +self+ with the given argument.
4248 *
4249 * === Instance Variables
4250 *
4251 * - #instance_variable_get: Returns the value of the given instance variable
4252 * in +self+, or +nil+ if the instance variable is not set.
4253 * - #instance_variable_set: Sets the value of the given instance variable in +self+
4254 * to the given object.
4255 * - #instance_variables: Returns an array of the symbol names
4256 * of the instance variables in +self+.
4257 * - #remove_instance_variable: Removes the named instance variable from +self+.
4258 *
4259 * === Other
4260 *
4261 * - #clone: Returns a shallow copy of +self+, including singleton class
4262 * and frozen state.
4263 * - #define_singleton_method: Defines a singleton method in +self+
4264 * for the given symbol method-name and block or proc.
4265 * - #display: Prints +self+ to the given IO stream or <tt>$stdout</tt>.
4266 * - #dup: Returns a shallow unfrozen copy of +self+.
4267 * - #enum_for (aliased as #to_enum): Returns an Enumerator for +self+
4268 * using the using the given method, arguments, and block.
4269 * - #extend: Includes the given modules in the singleton class of +self+.
4270 * - #freeze: Prevents further modifications to +self+.
4271 * - #hash: Returns the integer hash value for +self+.
4272 * - #inspect: Returns a human-readable string representation of +self+.
4273 * - #itself: Returns +self+.
4274 * - #method_missing: Method called when an undefined method is called on +self+.
4275 * - #public_send: Calls the given public method in +self+ with the given argument.
4276 * - #send: Calls the given method in +self+ with the given argument.
4277 * - #to_s: Returns a string representation of +self+.
4278 *
4279 */
4280
4281void
4282InitVM_Object(void)
4283{
4284 Init_class_hierarchy();
4285
4286#if 0
4287 // teach RDoc about these classes
4288 rb_cBasicObject = rb_define_class("BasicObject", Qnil);
4292 rb_cRefinement = rb_define_class("Refinement", rb_cModule);
4293#endif
4294
4295 rb_define_private_method(rb_cBasicObject, "initialize", rb_obj_initialize, 0);
4296 rb_define_alloc_func(rb_cBasicObject, rb_class_allocate_instance);
4297 rb_define_method(rb_cBasicObject, "==", rb_obj_equal, 1);
4298 rb_define_method(rb_cBasicObject, "equal?", rb_obj_equal, 1);
4299 rb_define_method(rb_cBasicObject, "!", rb_obj_not, 0);
4300 rb_define_method(rb_cBasicObject, "!=", rb_obj_not_equal, 1);
4301
4302 rb_define_private_method(rb_cBasicObject, "singleton_method_added", rb_obj_singleton_method_added, 1);
4303 rb_define_private_method(rb_cBasicObject, "singleton_method_removed", rb_obj_singleton_method_removed, 1);
4304 rb_define_private_method(rb_cBasicObject, "singleton_method_undefined", rb_obj_singleton_method_undefined, 1);
4305
4306 /* Document-module: Kernel
4307 *
4308 * The Kernel module is included by class Object, so its methods are
4309 * available in every Ruby object.
4310 *
4311 * The Kernel instance methods are documented in class Object while the
4312 * module methods are documented here. These methods are called without a
4313 * receiver and thus can be called in functional form:
4314 *
4315 * sprintf "%.1f", 1.234 #=> "1.2"
4316 *
4317 * == What's Here
4318 *
4319 * Module \Kernel provides methods that are useful for:
4320 *
4321 * - {Converting}[rdoc-ref:Kernel@Converting]
4322 * - {Querying}[rdoc-ref:Kernel@Querying]
4323 * - {Exiting}[rdoc-ref:Kernel@Exiting]
4324 * - {Exceptions}[rdoc-ref:Kernel@Exceptions]
4325 * - {IO}[rdoc-ref:Kernel@IO]
4326 * - {Procs}[rdoc-ref:Kernel@Procs]
4327 * - {Tracing}[rdoc-ref:Kernel@Tracing]
4328 * - {Subprocesses}[rdoc-ref:Kernel@Subprocesses]
4329 * - {Loading}[rdoc-ref:Kernel@Loading]
4330 * - {Yielding}[rdoc-ref:Kernel@Yielding]
4331 * - {Random Values}[rdoc-ref:Kernel@Random+Values]
4332 * - {Other}[rdoc-ref:Kernel@Other]
4333 *
4334 * === Converting
4335 *
4336 * - #Array: Returns an Array based on the given argument.
4337 * - #Complex: Returns a Complex based on the given arguments.
4338 * - #Float: Returns a Float based on the given arguments.
4339 * - #Hash: Returns a Hash based on the given argument.
4340 * - #Integer: Returns an Integer based on the given arguments.
4341 * - #Rational: Returns a Rational based on the given arguments.
4342 * - #String: Returns a String based on the given argument.
4343 *
4344 * === Querying
4345 *
4346 * - #__callee__: Returns the called name of the current method as a symbol.
4347 * - #__dir__: Returns the path to the directory from which the current
4348 * method is called.
4349 * - #__method__: Returns the name of the current method as a symbol.
4350 * - #autoload?: Returns the file to be loaded when the given module is referenced.
4351 * - #binding: Returns a Binding for the context at the point of call.
4352 * - #block_given?: Returns +true+ if a block was passed to the calling method.
4353 * - #caller: Returns the current execution stack as an array of strings.
4354 * - #caller_locations: Returns the current execution stack as an array
4355 * of Thread::Backtrace::Location objects.
4356 * - #class: Returns the class of +self+.
4357 * - #frozen?: Returns whether +self+ is frozen.
4358 * - #global_variables: Returns an array of global variables as symbols.
4359 * - #local_variables: Returns an array of local variables as symbols.
4360 * - #test: Performs specified tests on the given single file or pair of files.
4361 *
4362 * === Exiting
4363 *
4364 * - #abort: Exits the current process after printing the given arguments.
4365 * - #at_exit: Executes the given block when the process exits.
4366 * - #exit: Exits the current process after calling any registered
4367 * +at_exit+ handlers.
4368 * - #exit!: Exits the current process without calling any registered
4369 * +at_exit+ handlers.
4370 *
4371 * === Exceptions
4372 *
4373 * - #catch: Executes the given block, possibly catching a thrown object.
4374 * - #raise (aliased as #fail): Raises an exception based on the given arguments.
4375 * - #throw: Returns from the active catch block waiting for the given tag.
4376 *
4377 *
4378 * === \IO
4379 *
4380 * - ::pp: Prints the given objects in pretty form.
4381 * - #gets: Returns and assigns to <tt>$_</tt> the next line from the current input.
4382 * - #open: Creates an IO object connected to the given stream, file, or subprocess.
4383 * - #p: Prints the given objects' inspect output to the standard output.
4384 * - #print: Prints the given objects to standard output without a newline.
4385 * - #printf: Prints the string resulting from applying the given format string
4386 * to any additional arguments.
4387 * - #putc: Equivalent to <tt>$stdout.putc(object)</tt> for the given object.
4388 * - #puts: Equivalent to <tt>$stdout.puts(*objects)</tt> for the given objects.
4389 * - #readline: Similar to #gets, but raises an exception at the end of file.
4390 * - #readlines: Returns an array of the remaining lines from the current input.
4391 * - #select: Same as IO.select.
4392 *
4393 * === Procs
4394 *
4395 * - #lambda: Returns a lambda proc for the given block.
4396 * - #proc: Returns a new Proc; equivalent to Proc.new.
4397 *
4398 * === Tracing
4399 *
4400 * - #set_trace_func: Sets the given proc as the handler for tracing,
4401 * or disables tracing if given +nil+.
4402 * - #trace_var: Starts tracing assignments to the given global variable.
4403 * - #untrace_var: Disables tracing of assignments to the given global variable.
4404 *
4405 * === Subprocesses
4406 *
4407 * - {\`command`}[rdoc-ref:Kernel#`]: Returns the standard output of running
4408 * +command+ in a subshell.
4409 * - #exec: Replaces current process with a new process.
4410 * - #fork: Forks the current process into two processes.
4411 * - #spawn: Executes the given command and returns its pid without waiting
4412 * for completion.
4413 * - #system: Executes the given command in a subshell.
4414 *
4415 * === Loading
4416 *
4417 * - #autoload: Registers the given file to be loaded when the given constant
4418 * is first referenced.
4419 * - #load: Loads the given Ruby file.
4420 * - #require: Loads the given Ruby file unless it has already been loaded.
4421 * - #require_relative: Loads the Ruby file path relative to the calling file,
4422 * unless it has already been loaded.
4423 *
4424 * === Yielding
4425 *
4426 * - #tap: Yields +self+ to the given block; returns +self+.
4427 * - #then (aliased as #yield_self): Yields +self+ to the block
4428 * and returns the result of the block.
4429 *
4430 * === \Random Values
4431 *
4432 * - #rand: Returns a pseudo-random floating point number
4433 * strictly between 0.0 and 1.0.
4434 * - #srand: Seeds the pseudo-random number generator with the given number.
4435 *
4436 * === Other
4437 *
4438 * - #eval: Evaluates the given string as Ruby code.
4439 * - #loop: Repeatedly executes the given block.
4440 * - #sleep: Suspends the current thread for the given number of seconds.
4441 * - #sprintf (aliased as #format): Returns the string resulting from applying
4442 * the given format string to any additional arguments.
4443 * - #syscall: Runs an operating system call.
4444 * - #trap: Specifies the handling of system signals.
4445 * - #warn: Issue a warning based on the given messages and options.
4446 *
4447 */
4448 rb_mKernel = rb_define_module("Kernel");
4450 rb_define_private_method(rb_cClass, "inherited", rb_obj_class_inherited, 1);
4451 rb_define_private_method(rb_cModule, "included", rb_obj_mod_included, 1);
4452 rb_define_private_method(rb_cModule, "extended", rb_obj_mod_extended, 1);
4453 rb_define_private_method(rb_cModule, "prepended", rb_obj_mod_prepended, 1);
4454 rb_define_private_method(rb_cModule, "method_added", rb_obj_mod_method_added, 1);
4455 rb_define_private_method(rb_cModule, "const_added", rb_obj_mod_const_added, 1);
4456 rb_define_private_method(rb_cModule, "method_removed", rb_obj_mod_method_removed, 1);
4457 rb_define_private_method(rb_cModule, "method_undefined", rb_obj_mod_method_undefined, 1);
4458
4459 rb_define_method(rb_mKernel, "nil?", rb_false, 0);
4460 rb_define_method(rb_mKernel, "===", case_equal, 1);
4461 rb_define_method(rb_mKernel, "!~", rb_obj_not_match, 1);
4462 rb_define_method(rb_mKernel, "eql?", rb_obj_equal, 1);
4463 rb_define_method(rb_mKernel, "hash", rb_obj_hash, 0); /* in hash.c */
4464 rb_define_method(rb_mKernel, "<=>", rb_obj_cmp, 1);
4465
4466 rb_define_method(rb_mKernel, "singleton_class", rb_obj_singleton_class, 0);
4468 rb_define_method(rb_mKernel, "itself", rb_obj_itself, 0);
4469 rb_define_method(rb_mKernel, "initialize_copy", rb_obj_init_copy, 1);
4470 rb_define_method(rb_mKernel, "initialize_dup", rb_obj_init_dup_clone, 1);
4471 rb_define_method(rb_mKernel, "initialize_clone", rb_obj_init_clone, -1);
4472
4474
4476 rb_define_method(rb_mKernel, "inspect", rb_obj_inspect, 0);
4477 rb_define_private_method(rb_mKernel, "instance_variables_to_inspect", rb_obj_instance_variables_to_inspect, 0);
4478 rb_define_method(rb_mKernel, "methods", rb_obj_methods, -1); /* in class.c */
4479 rb_define_method(rb_mKernel, "singleton_methods", rb_obj_singleton_methods, -1); /* in class.c */
4480 rb_define_method(rb_mKernel, "protected_methods", rb_obj_protected_methods, -1); /* in class.c */
4481 rb_define_method(rb_mKernel, "private_methods", rb_obj_private_methods, -1); /* in class.c */
4482 rb_define_method(rb_mKernel, "public_methods", rb_obj_public_methods, -1); /* in class.c */
4483 rb_define_method(rb_mKernel, "instance_variables", rb_obj_instance_variables, 0); /* in variable.c */
4484 rb_define_method(rb_mKernel, "instance_variable_get", rb_obj_ivar_get, 1);
4485 rb_define_method(rb_mKernel, "instance_variable_set", rb_obj_ivar_set_m, 2);
4486 rb_define_method(rb_mKernel, "instance_variable_defined?", rb_obj_ivar_defined, 1);
4487 rb_define_method(rb_mKernel, "remove_instance_variable",
4488 rb_obj_remove_instance_variable, 1); /* in variable.c */
4489
4493
4494 rb_define_global_function("sprintf", f_sprintf, -1);
4495 rb_define_global_function("format", f_sprintf, -1);
4496
4497 rb_define_global_function("String", rb_f_string, 1);
4498 rb_define_global_function("Array", rb_f_array, 1);
4499 rb_define_global_function("Hash", rb_f_hash, 1);
4500
4502 rb_cNilClass_to_s = rb_fstring_enc_lit("", rb_usascii_encoding());
4503 rb_vm_register_global_object(rb_cNilClass_to_s);
4504 rb_define_method(rb_cNilClass, "to_s", rb_nil_to_s, 0);
4505 rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0);
4506 rb_define_method(rb_cNilClass, "to_h", nil_to_h, 0);
4507 rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0);
4508 rb_define_method(rb_cNilClass, "=~", nil_match, 1);
4509 rb_define_method(rb_cNilClass, "&", false_and, 1);
4510 rb_define_method(rb_cNilClass, "|", false_or, 1);
4511 rb_define_method(rb_cNilClass, "^", false_xor, 1);
4512 rb_define_method(rb_cNilClass, "===", case_equal, 1);
4513
4514 rb_define_method(rb_cNilClass, "nil?", rb_true, 0);
4517
4518 rb_define_method(rb_cModule, "freeze", rb_mod_freeze, 0);
4519 rb_define_method(rb_cModule, "===", rb_mod_eqq, 1);
4520 rb_define_method(rb_cModule, "==", rb_obj_equal, 1);
4521 rb_define_method(rb_cModule, "<=>", rb_mod_cmp, 1);
4522 rb_define_method(rb_cModule, "<", rb_mod_lt, 1);
4524 rb_define_method(rb_cModule, ">", rb_mod_gt, 1);
4525 rb_define_method(rb_cModule, ">=", rb_mod_ge, 1);
4526 rb_define_method(rb_cModule, "to_s", rb_mod_to_s, 0);
4527 rb_define_alias(rb_cModule, "inspect", "to_s");
4528 rb_define_method(rb_cModule, "included_modules", rb_mod_included_modules, 0); /* in class.c */
4529 rb_define_method(rb_cModule, "include?", rb_mod_include_p, 1); /* in class.c */
4530 rb_define_method(rb_cModule, "name", rb_mod_name, 0); /* in variable.c */
4531 rb_define_method(rb_cModule, "set_temporary_name", rb_mod_set_temporary_name, 1); /* in variable.c */
4532 rb_define_method(rb_cModule, "ancestors", rb_mod_ancestors, 0); /* in class.c */
4533
4534 rb_define_method(rb_cModule, "attr", rb_mod_attr, -1);
4535 rb_define_method(rb_cModule, "attr_reader", rb_mod_attr_reader, -1);
4536 rb_define_method(rb_cModule, "attr_writer", rb_mod_attr_writer, -1);
4537 rb_define_method(rb_cModule, "attr_accessor", rb_mod_attr_accessor, -1);
4538
4539 rb_define_alloc_func(rb_cModule, rb_module_s_alloc);
4541 rb_define_method(rb_cModule, "initialize", rb_mod_initialize, 0);
4542 rb_define_method(rb_cModule, "initialize_clone", rb_mod_initialize_clone, -1);
4543 rb_define_method(rb_cModule, "instance_methods", rb_class_instance_methods, -1); /* in class.c */
4544 rb_define_method(rb_cModule, "public_instance_methods",
4545 rb_class_public_instance_methods, -1); /* in class.c */
4546 rb_define_method(rb_cModule, "protected_instance_methods",
4547 rb_class_protected_instance_methods, -1); /* in class.c */
4548 rb_define_method(rb_cModule, "private_instance_methods",
4549 rb_class_private_instance_methods, -1); /* in class.c */
4550 rb_define_method(rb_cModule, "undefined_instance_methods",
4551 rb_class_undefined_instance_methods, 0); /* in class.c */
4552
4553 rb_define_method(rb_cModule, "constants", rb_mod_constants, -1); /* in variable.c */
4554 rb_define_method(rb_cModule, "const_get", rb_mod_const_get, -1);
4555 rb_define_method(rb_cModule, "const_set", rb_mod_const_set, 2);
4556 rb_define_method(rb_cModule, "const_defined?", rb_mod_const_defined, -1);
4557 rb_define_method(rb_cModule, "const_source_location", rb_mod_const_source_location, -1);
4558 rb_define_private_method(rb_cModule, "remove_const",
4559 rb_mod_remove_const, 1); /* in variable.c */
4560 rb_define_method(rb_cModule, "const_missing",
4561 rb_mod_const_missing, 1); /* in variable.c */
4562 rb_define_method(rb_cModule, "class_variables",
4563 rb_mod_class_variables, -1); /* in variable.c */
4564 rb_define_method(rb_cModule, "remove_class_variable",
4565 rb_mod_remove_cvar, 1); /* in variable.c */
4566 rb_define_method(rb_cModule, "class_variable_get", rb_mod_cvar_get, 1);
4567 rb_define_method(rb_cModule, "class_variable_set", rb_mod_cvar_set, 2);
4568 rb_define_method(rb_cModule, "class_variable_defined?", rb_mod_cvar_defined, 1);
4569 rb_define_method(rb_cModule, "public_constant", rb_mod_public_constant, -1); /* in variable.c */
4570 rb_define_method(rb_cModule, "private_constant", rb_mod_private_constant, -1); /* in variable.c */
4571 rb_define_method(rb_cModule, "deprecate_constant", rb_mod_deprecate_constant, -1); /* in variable.c */
4572 rb_define_method(rb_cModule, "singleton_class?", rb_mod_singleton_p, 0);
4573
4574 rb_define_method(rb_singleton_class(rb_cClass), "allocate", rb_class_alloc, 0);
4575 rb_define_method(rb_cClass, "allocate", rb_class_alloc, 0);
4577 rb_define_method(rb_cClass, "initialize", rb_class_initialize, -1);
4579 rb_define_method(rb_cClass, "subclasses", rb_class_subclasses, 0); /* in class.c */
4580 rb_define_method(rb_cClass, "attached_object", rb_class_attached_object, 0); /* in class.c */
4581 rb_define_alloc_func(rb_cClass, rb_class_s_alloc);
4582 rb_undef_method(rb_cClass, "extend_object");
4583 rb_undef_method(rb_cClass, "append_features");
4584 rb_undef_method(rb_cClass, "prepend_features");
4585
4587 rb_cTrueClass_to_s = rb_fstring_enc_lit("true", rb_usascii_encoding());
4588 rb_vm_register_global_object(rb_cTrueClass_to_s);
4589 rb_define_method(rb_cTrueClass, "to_s", rb_true_to_s, 0);
4590 rb_define_alias(rb_cTrueClass, "inspect", "to_s");
4591 rb_define_method(rb_cTrueClass, "&", true_and, 1);
4592 rb_define_method(rb_cTrueClass, "|", true_or, 1);
4593 rb_define_method(rb_cTrueClass, "^", true_xor, 1);
4594 rb_define_method(rb_cTrueClass, "===", case_equal, 1);
4597
4598 rb_cFalseClass = rb_define_class("FalseClass", rb_cObject);
4599 rb_cFalseClass_to_s = rb_fstring_enc_lit("false", rb_usascii_encoding());
4600 rb_vm_register_global_object(rb_cFalseClass_to_s);
4601 rb_define_method(rb_cFalseClass, "to_s", rb_false_to_s, 0);
4602 rb_define_alias(rb_cFalseClass, "inspect", "to_s");
4603 rb_define_method(rb_cFalseClass, "&", false_and, 1);
4604 rb_define_method(rb_cFalseClass, "|", false_or, 1);
4605 rb_define_method(rb_cFalseClass, "^", false_xor, 1);
4606 rb_define_method(rb_cFalseClass, "===", case_equal, 1);
4609}
4610
4611#include "kernel.rbinc"
4612#include "nilclass.rbinc"
4613
4614void
4615Init_Object(void)
4616{
4617 id_dig = rb_intern_const("dig");
4618 id_instance_variables_to_inspect = rb_intern_const("instance_variables_to_inspect");
4619 InitVM(Object);
4620}
4621
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
static int rb_tolower(int c)
Our own locale-insensitive version of tolower(3).
Definition ctype.h:514
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
static bool RB_OBJ_FROZEN(VALUE obj)
Checks if an object is frozen.
Definition fl_type.h:892
@ RUBY_FL_PROMOTED
Ruby objects are "generational".
Definition fl_type.h:217
VALUE rb_class_protected_instance_methods(int argc, const VALUE *argv, VALUE mod)
Identical to rb_class_instance_methods(), except it returns names of methods that are protected only.
Definition class.c:2513
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1795
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1588
VALUE rb_class_subclasses(VALUE klass)
Queries the class's direct descendants.
Definition class.c:2293
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2899
VALUE rb_class_attached_object(VALUE klass)
Returns the attached object for a singleton class.
Definition class.c:2316
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:2690
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:2498
void rb_check_inheritable(VALUE super)
Asserts that the given class can derive a child class.
Definition class.c:953
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:2551
VALUE rb_define_module(const char *name)
Defines a top-level module.
Definition class.c:1701
void rb_singleton_class_attached(VALUE klass, VALUE obj)
Attaches a singleton class to its corresponding object.
Definition class.c:1315
VALUE rb_mod_included_modules(VALUE mod)
Queries the list of included modules.
Definition class.c:2111
VALUE rb_mod_ancestors(VALUE mod)
Queries the module's ancestors.
Definition class.c:2179
VALUE rb_class_inherited(VALUE super, VALUE klass)
Calls Class::inherited.
Definition class.c:1579
VALUE rb_mod_include_p(VALUE mod, VALUE mod2)
Queries if the passed module is included by the module.
Definition class.c:2147
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:2536
VALUE rb_mod_init_copy(VALUE clone, VALUE orig)
The comment that comes with this function says :nodoc:.
Definition class.c:1129
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2947
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2767
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:3237
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1007
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3026
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define FL_SINGLETON
Old name of RUBY_FL_SINGLETON.
Definition fl_type.h:58
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define ALLOCV
Old name of RB_ALLOCV.
Definition memory.h:404
#define ISSPACE
Old name of rb_isspace.
Definition ctype.h:88
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define T_MASK
Old name of RUBY_T_MASK.
Definition value_type.h:68
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:136
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1682
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define T_IMEMO
Old name of RUBY_T_IMEMO.
Definition value_type.h:67
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition value_type.h:79
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:134
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define T_DATA
Old name of RUBY_T_DATA.
Definition value_type.h:60
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h: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:131
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1679
#define FLONUM_P
Old name of RB_FLONUM_P.
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define T_OBJECT
Old name of RUBY_T_OBJECT.
Definition value_type.h:75
#define NIL_P
Old name of RB_NIL_P.
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition fl_type.h:59
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define FL_FREEZE
Old name of RUBY_FL_FREEZE.
Definition fl_type.h:66
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:129
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
void rb_category_warning(rb_warning_category_t category, const char *fmt,...)
Identical to rb_warning(), except it takes additional "category" parameter.
Definition error.c:508
VALUE rb_eTypeError
TypeError exception.
Definition error.c: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:2247
VALUE rb_class_get_superclass(VALUE klass)
Returns the superclass of a class.
Definition object.c:2272
VALUE rb_convert_type(VALUE val, int type, const char *tname, const char *method)
Converts an object into another type.
Definition object.c:3189
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition object.c:3721
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:3295
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:3216
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:2191
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2232
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:2220
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:2209
VALUE rb_check_to_float(VALUE val)
This is complicated.
Definition object.c:3760
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:3919
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:3605
VALUE rb_Integer(VALUE val)
This is the logic behind Kernel#Integer.
Definition object.c:3364
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:3876
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:1850
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:3750
double rb_num2dbl(VALUE val)
Converts an instance of rb_cNumeric into C's double.
Definition object.c:3812
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:3561
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:3276
VALUE rb_String(VALUE val)
This is the logic behind Kernel#String.
Definition object.c:3844
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:3289
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:2005
VALUE rb_rational_den(VALUE rat)
Queries the denominator of the passed Rational.
Definition rational.c:2011
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:1638
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:2265
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:1644
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:2448
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:284
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1133
int len
Length of the buffer.
Definition io.h:8
const signed char ruby_digit36_to_number_table[]
Character to number mapping like ‘'a’->10,'b'->11etc.
Definition util.c:60
#define strtod(s, e)
Just another name of ruby_strtod.
Definition util.h:223
VALUE rb_f_sprintf(int argc, const VALUE *argv)
Identical to rb_str_format(), except how the arguments are arranged.
Definition sprintf.c:209
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
VALUE type(ANYARGS)
ANYARGS-ed function type.
void rb_ivar_foreach(VALUE q, int_type *w, VALUE e)
Iteration over each instance variable of the object.
void rb_copy_generic_ivar(VALUE clone, VALUE obj)
Copies the list of instance variables.
Definition variable.c: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