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