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