Ruby: object.c Source File

Ruby 3.4.1p0 (2024-12-25 revision 48d4efcb85000e1ebae42004e963b5d0cedddcf2)

object.c
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
63
64 VALUE rb_cBasicObject;
65 VALUE rb_mKernel;
66 VALUE rb_cObject;
67 VALUE rb_cModule;
68 VALUE rb_cClass;
69 VALUE rb_cRefinement;
70
71 VALUE rb_cNilClass;
72 VALUE rb_cTrueClass;
73 VALUE rb_cFalseClass;
74
75static VALUE rb_cNilClass_to_s;
76static VALUE rb_cTrueClass_to_s;
77static VALUE rb_cFalseClass_to_s;
78
80
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
96
97size_t
98rb_obj_embedded_size(uint32_t numiv)
99{
100 return offsetof(struct RObject, as.ary) + (sizeof(VALUE) * numiv);
101}
102
103 VALUE
104rb_obj_hide(VALUE obj)
105{
106 if (!SPECIAL_CONST_P(obj)) {
107 RBASIC_CLEAR_CLASS(obj);
108 }
109 return obj;
110}
111
112 VALUE
113rb_obj_reveal(VALUE obj, VALUE klass)
114{
115 if (!SPECIAL_CONST_P(obj)) {
116 RBASIC_SET_CLASS(obj, klass);
117 }
118 return obj;
119}
120
121 VALUE
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
151 VALUE
152rb_obj_setup(VALUE obj, VALUE klass, VALUE type)
153{
154 VALUE ignored_flags = RUBY_FL_PROMOTED | RUBY_FL_SEEN_OBJ_ID;
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
178 VALUE
179rb_equal(VALUE obj1, VALUE obj2)
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
207 VALUE
208rb_obj_equal(VALUE obj1, VALUE obj2)
209{
210 return RBOOL(obj1 == obj2);
211}
212
213 VALUE rb_obj_hash(VALUE obj);
214
218
219 VALUE
220rb_obj_not(VALUE obj)
221{
222 return RBOOL(!RTEST(obj));
223}
224
228
229 VALUE
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
236 VALUE
237rb_class_real(VALUE cl)
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
246 VALUE
247rb_obj_class(VALUE obj)
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{
279 RUBY_ASSERT(!RB_TYPE_P(obj, T_CLASS) && !RB_TYPE_P(obj, T_MODULE));
280
281 RUBY_ASSERT(BUILTIN_TYPE(dest) == BUILTIN_TYPE(obj));
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
401 VALUE
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
408 VALUE
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
436 VALUE
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
520 VALUE
521rb_obj_clone(VALUE obj)
522{
523 if (special_object_p(obj)) return obj;
524 return mutable_obj_clone(obj, Qnil);
525}
526
527 VALUE
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 */
575 VALUE
576rb_obj_dup(VALUE obj)
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
604 VALUE
605rb_obj_size(VALUE self, VALUE args, VALUE obj)
606{
607 return LONG2FIX(1);
608}
609
615 VALUE
616rb_obj_init_copy(VALUE obj, VALUE orig)
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
632 VALUE
633rb_obj_init_dup_clone(VALUE obj, VALUE orig)
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 */
668 VALUE
669rb_any_to_s(VALUE obj)
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
679 VALUE
680rb_inspect(VALUE obj)
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
808 VALUE
809rb_obj_is_instance_of(VALUE obj, VALUE c)
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{
820 RUBY_ASSERT(RB_TYPE_P(c, T_CLASS));
821 RUBY_ASSERT(RB_TYPE_P(cl, T_CLASS));
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
864 VALUE
865rb_obj_is_kind_of(VALUE obj, VALUE c)
866{
867 VALUE cl = CLASS_OF(obj);
868
869 RUBY_ASSERT(RB_TYPE_P(cl, T_CLASS));
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");
905 UNREACHABLE_RETURN(Qfalse);
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
922 VALUE
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
1259 VALUE
1260rb_obj_freeze(VALUE obj)
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
1271 VALUE
1272rb_obj_frozen_p(VALUE obj)
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
1325 VALUE
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
1434 VALUE
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
1521 VALUE
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
1604 VALUE
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
1689 VALUE
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)) {
1700 rb_str_append(s, rb_inspect(v));
1701 }
1702 else {
1703 rb_str_append(s, rb_any_to_s(v));
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
1767 VALUE
1768rb_class_inherited_p(VALUE mod, VALUE arg)
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
2096 VALUE
2097rb_obj_alloc(VALUE klass)
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
2114 VALUE
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
2125 VALUE
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
2137 VALUE
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
2151
2152 VALUE
2153rb_class_superclass(VALUE klass)
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
2174 VALUE
2175rb_class_get_superclass(VALUE klass)
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
2258 VALUE
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);
2473 UNREACHABLE_RETURN(Qundef);
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);
2652 UNREACHABLE_RETURN(Qundef);
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);
2805 UNREACHABLE_RETURN(Qundef);
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
3091 VALUE
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
3105 VALUE
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
3118 VALUE
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
3134 VALUE
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
3178 VALUE
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
3191 VALUE
3192rb_to_int(VALUE val)
3193{
3194 return rb_to_integer(val, "to_int", idTo_int);
3195}
3196
3197 VALUE
3198rb_check_to_int(VALUE val)
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
3266 VALUE
3267rb_Integer(VALUE val)
3268{
3269 return rb_convert_to_integer(val, 0, TRUE);
3270}
3271
3272 VALUE
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 double
3321rb_cstr_to_dbl_raise(const char *p, rb_encoding *enc, int badcheck, int raise, int *error)
3322{
3323 const char *q;
3324 char *end;
3325 double d;
3326 const char *ellipsis = "";
3327 int w;
3328 enum {max_width = 20};
3329#define OutOfRange() ((end - p > max_width) ? \
3330 (w = max_width, ellipsis = "...") : \
3331 (w = (int)(end - p), ellipsis = ""))
3332 /* p...end has been parsed with strtod, should be ASCII-only */
3333
3334 if (!p) return 0.0;
3335 q = p;
3336 while (ISSPACE(*p)) p++;
3337
3338 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3339 return 0.0;
3340 }
3341
3342 d = strtod(p, &end);
3343 if (errno == ERANGE) {
3344 OutOfRange();
3345 rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3346 errno = 0;
3347 }
3348 if (p == end) {
3349 if (badcheck) {
3350 goto bad;
3351 }
3352 return d;
3353 }
3354 if (*end) {
3355 char buf[DBL_DIG * 4 + 10];
3356 char *n = buf;
3357 char *const init_e = buf + DBL_DIG * 4;
3358 char *e = init_e;
3359 char prev = 0;
3360 int dot_seen = FALSE;
3361
3362 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3363 if (*p == '0') {
3364 prev = *n++ = '0';
3365 while (*++p == '0');
3366 }
3367 while (p < end && n < e) prev = *n++ = *p++;
3368 while (*p) {
3369 if (*p == '_') {
3370 /* remove an underscore between digits */
3371 if (n == buf || !ISDIGIT(prev) || (++p, !ISDIGIT(*p))) {
3372 if (badcheck) goto bad;
3373 break;
3374 }
3375 }
3376 prev = *p++;
3377 if (e == init_e && (prev == 'e' || prev == 'E' || prev == 'p' || prev == 'P')) {
3378 e = buf + sizeof(buf) - 1;
3379 *n++ = prev;
3380 switch (*p) {case '+': case '-': prev = *n++ = *p++;}
3381 if (*p == '0') {
3382 prev = *n++ = '0';
3383 while (*++p == '0');
3384 }
3385 continue;
3386 }
3387 else if (ISSPACE(prev)) {
3388 while (ISSPACE(*p)) ++p;
3389 if (*p) {
3390 if (badcheck) goto bad;
3391 break;
3392 }
3393 }
3394 else if (prev == '.' ? dot_seen++ : !ISDIGIT(prev)) {
3395 if (badcheck) goto bad;
3396 break;
3397 }
3398 if (n < e) *n++ = prev;
3399 }
3400 *n = '\0';
3401 p = buf;
3402
3403 if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3404 return 0.0;
3405 }
3406
3407 d = strtod(p, &end);
3408 if (errno == ERANGE) {
3409 OutOfRange();
3410 rb_warning("Float %.*s%s out of range", w, p, ellipsis);
3411 errno = 0;
3412 }
3413 if (badcheck) {
3414 if (!end || p == end) goto bad;
3415 while (*end && ISSPACE(*end)) end++;
3416 if (*end) goto bad;
3417 }
3418 }
3419 if (errno == ERANGE) {
3420 errno = 0;
3421 OutOfRange();
3422 rb_raise(rb_eArgError, "Float %.*s%s out of range", w, q, ellipsis);
3423 }
3424 return d;
3425
3426 bad:
3427 if (raise) {
3428 VALUE s = rb_enc_str_new_cstr(q, enc);
3429 rb_raise(rb_eArgError, "invalid value for Float(): %+"PRIsVALUE, s);
3430 UNREACHABLE_RETURN(nan(""));
3431 }
3432 else {
3433 if (error) *error = 1;
3434 return 0.0;
3435 }
3436}
3437
3438double
3439rb_cstr_to_dbl(const char *p, int badcheck)
3440{
3441 return rb_cstr_to_dbl_raise(p, NULL, badcheck, TRUE, NULL);
3442}
3443
3444static double
3445rb_str_to_dbl_raise(VALUE str, int badcheck, int raise, int *error)
3446{
3447 char *s;
3448 long len;
3449 double ret;
3450 VALUE v = 0;
3451
3452 StringValue(str);
3453 rb_must_asciicompat(str);
3454 s = RSTRING_PTR(str);
3455 len = RSTRING_LEN(str);
3456 if (s) {
3457 if (badcheck && memchr(s, '\0', len)) {
3458 if (raise)
3459 rb_raise(rb_eArgError, "string for Float contains null byte");
3460 else {
3461 if (error) *error = 1;
3462 return 0.0;
3463 }
3464 }
3465 if (s[len]) { /* no sentinel somehow */
3466 char *p = ALLOCV(v, (size_t)len + 1);
3467 MEMCPY(p, s, char, len);
3468 p[len] = '\0';
3469 s = p;
3470 }
3471 }
3472 ret = rb_cstr_to_dbl_raise(s, rb_enc_get(str), badcheck, raise, error);
3473 if (v)
3474 ALLOCV_END(v);
3475 else
3476 RB_GC_GUARD(str);
3477 return ret;
3478}
3479
3480FUNC_MINIMIZED(double rb_str_to_dbl(VALUE str, int badcheck));
3481
3482double
3483rb_str_to_dbl(VALUE str, int badcheck)
3484{
3485 return rb_str_to_dbl_raise(str, badcheck, TRUE, NULL);
3486}
3487
3489#define fix2dbl_without_to_f(x) (double)FIX2LONG(x)
3490#define big2dbl_without_to_f(x) rb_big2dbl(x)
3491#define int2dbl_without_to_f(x) \
3492 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : big2dbl_without_to_f(x))
3493#define num2dbl_without_to_f(x) \
3494 (FIXNUM_P(x) ? fix2dbl_without_to_f(x) : \
3495 RB_BIGNUM_TYPE_P(x) ? big2dbl_without_to_f(x) : \
3496 (Check_Type(x, T_FLOAT), RFLOAT_VALUE(x)))
3497static inline double
3498rat2dbl_without_to_f(VALUE x)
3499{
3500 VALUE num = rb_rational_num(x);
3501 VALUE den = rb_rational_den(x);
3502 return num2dbl_without_to_f(num) / num2dbl_without_to_f(den);
3503}
3504
3505#define special_const_to_float(val, pre, post) \
3506 switch (val) { \
3507 case Qnil: \
3508 rb_raise_static(rb_eTypeError, pre "nil" post); \
3509 case Qtrue: \
3510 rb_raise_static(rb_eTypeError, pre "true" post); \
3511 case Qfalse: \
3512 rb_raise_static(rb_eTypeError, pre "false" post); \
3513 }
3515
3516static inline void
3517conversion_to_float(VALUE val)
3518{
3519 special_const_to_float(val, "can't convert ", " into Float");
3520}
3521
3522static inline void
3523implicit_conversion_to_float(VALUE val)
3524{
3525 special_const_to_float(val, "no implicit conversion to float from ", "");
3526}
3527
3528static int
3529to_float(VALUE *valp, int raise_exception)
3530{
3531 VALUE val = *valp;
3532 if (SPECIAL_CONST_P(val)) {
3533 if (FIXNUM_P(val)) {
3534 *valp = DBL2NUM(fix2dbl_without_to_f(val));
3535 return T_FLOAT;
3536 }
3537 else if (FLONUM_P(val)) {
3538 return T_FLOAT;
3539 }
3540 else if (raise_exception) {
3541 conversion_to_float(val);
3542 }
3543 }
3544 else {
3545 int type = BUILTIN_TYPE(val);
3546 switch (type) {
3547 case T_FLOAT:
3548 return T_FLOAT;
3549 case T_BIGNUM:
3550 *valp = DBL2NUM(big2dbl_without_to_f(val));
3551 return T_FLOAT;
3552 case T_RATIONAL:
3553 *valp = DBL2NUM(rat2dbl_without_to_f(val));
3554 return T_FLOAT;
3555 case T_STRING:
3556 return T_STRING;
3557 }
3558 }
3559 return T_NONE;
3560}
3561
3562static VALUE
3563convert_type_to_float_protected(VALUE val)
3564{
3565 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3566}
3567
3568static VALUE
3569rb_convert_to_float(VALUE val, int raise_exception)
3570{
3571 switch (to_float(&val, raise_exception)) {
3572 case T_FLOAT:
3573 return val;
3574 case T_STRING:
3575 if (!raise_exception) {
3576 int e = 0;
3577 double x = rb_str_to_dbl_raise(val, TRUE, raise_exception, &e);
3578 return e ? Qnil : DBL2NUM(x);
3579 }
3580 return DBL2NUM(rb_str_to_dbl(val, TRUE));
3581 case T_NONE:
3582 if (SPECIAL_CONST_P(val) && !raise_exception)
3583 return Qnil;
3584 }
3585
3586 if (!raise_exception) {
3587 int state;
3588 VALUE result = rb_protect(convert_type_to_float_protected, val, &state);
3589 if (state) rb_set_errinfo(Qnil);
3590 return result;
3591 }
3592
3593 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3594}
3595
3596FUNC_MINIMIZED(VALUE rb_Float(VALUE val));
3597
3598 VALUE
3599rb_Float(VALUE val)
3600{
3601 return rb_convert_to_float(val, TRUE);
3602}
3603
3604static VALUE
3605rb_f_float1(rb_execution_context_t *ec, VALUE obj, VALUE arg)
3606{
3607 return rb_convert_to_float(arg, TRUE);
3608}
3609
3610static VALUE
3611rb_f_float(rb_execution_context_t *ec, VALUE obj, VALUE arg, VALUE opts)
3612{
3613 int exception = rb_bool_expected(opts, "exception", TRUE);
3614 return rb_convert_to_float(arg, exception);
3615}
3616
3617static VALUE
3618numeric_to_float(VALUE val)
3619{
3620 if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3621 rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into Float",
3622 rb_obj_class(val));
3623 }
3624 return rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3625}
3626
3627 VALUE
3628rb_to_float(VALUE val)
3629{
3630 switch (to_float(&val, TRUE)) {
3631 case T_FLOAT:
3632 return val;
3633 }
3634 return numeric_to_float(val);
3635}
3636
3637 VALUE
3638rb_check_to_float(VALUE val)
3639{
3640 if (RB_FLOAT_TYPE_P(val)) return val;
3641 if (!rb_obj_is_kind_of(val, rb_cNumeric)) {
3642 return Qnil;
3643 }
3644 return rb_check_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3645}
3646
3647static inline int
3648basic_to_f_p(VALUE klass)
3649{
3650 return rb_method_basic_definition_p(klass, id_to_f);
3651}
3652
3654double
3655rb_num_to_dbl(VALUE val)
3656{
3657 if (SPECIAL_CONST_P(val)) {
3658 if (FIXNUM_P(val)) {
3659 if (basic_to_f_p(rb_cInteger))
3660 return fix2dbl_without_to_f(val);
3661 }
3662 else if (FLONUM_P(val)) {
3663 return rb_float_flonum_value(val);
3664 }
3665 else {
3666 conversion_to_float(val);
3667 }
3668 }
3669 else {
3670 switch (BUILTIN_TYPE(val)) {
3671 case T_FLOAT:
3672 return rb_float_noflonum_value(val);
3673 case T_BIGNUM:
3674 if (basic_to_f_p(rb_cInteger))
3675 return big2dbl_without_to_f(val);
3676 break;
3677 case T_RATIONAL:
3678 if (basic_to_f_p(rb_cRational))
3679 return rat2dbl_without_to_f(val);
3680 break;
3681 default:
3682 break;
3683 }
3684 }
3685 val = numeric_to_float(val);
3686 return RFLOAT_VALUE(val);
3687}
3688
3689double
3690rb_num2dbl(VALUE val)
3691{
3692 if (SPECIAL_CONST_P(val)) {
3693 if (FIXNUM_P(val)) {
3694 return fix2dbl_without_to_f(val);
3695 }
3696 else if (FLONUM_P(val)) {
3697 return rb_float_flonum_value(val);
3698 }
3699 else {
3700 implicit_conversion_to_float(val);
3701 }
3702 }
3703 else {
3704 switch (BUILTIN_TYPE(val)) {
3705 case T_FLOAT:
3706 return rb_float_noflonum_value(val);
3707 case T_BIGNUM:
3708 return big2dbl_without_to_f(val);
3709 case T_RATIONAL:
3710 return rat2dbl_without_to_f(val);
3711 case T_STRING:
3712 rb_raise(rb_eTypeError, "no implicit conversion to float from string");
3713 default:
3714 break;
3715 }
3716 }
3717 val = rb_convert_type_with_id(val, T_FLOAT, "Float", id_to_f);
3718 return RFLOAT_VALUE(val);
3719}
3720
3721 VALUE
3722rb_String(VALUE val)
3723{
3724 VALUE tmp = rb_check_string_type(val);
3725 if (NIL_P(tmp))
3726 tmp = rb_convert_type_with_id(val, T_STRING, "String", idTo_s);
3727 return tmp;
3728}
3729
3730
3731/*
3732 * call-seq:
3733 * String(object) -> object or new_string
3734 *
3735 * Returns a string converted from +object+.
3736 *
3737 * Tries to convert +object+ to a string
3738 * using +to_str+ first and +to_s+ second:
3739 *
3740 * String([0, 1, 2]) # => "[0, 1, 2]"
3741 * String(0..5) # => "0..5"
3742 * String({foo: 0, bar: 1}) # => "{foo: 0, bar: 1}"
3743 *
3744 * Raises +TypeError+ if +object+ cannot be converted to a string.
3745 */
3746
3747static VALUE
3748rb_f_string(VALUE obj, VALUE arg)
3749{
3750 return rb_String(arg);
3751}
3752
3753 VALUE
3754rb_Array(VALUE val)
3755{
3756 VALUE tmp = rb_check_array_type(val);
3757
3758 if (NIL_P(tmp)) {
3759 tmp = rb_check_to_array(val);
3760 if (NIL_P(tmp)) {
3761 return rb_ary_new3(1, val);
3762 }
3763 }
3764 return tmp;
3765}
3766
3767/*
3768 * call-seq:
3769 * Array(object) -> object or new_array
3770 *
3771 * Returns an array converted from +object+.
3772 *
3773 * Tries to convert +object+ to an array
3774 * using +to_ary+ first and +to_a+ second:
3775 *
3776 * Array([0, 1, 2]) # => [0, 1, 2]
3777 * Array({foo: 0, bar: 1}) # => [[:foo, 0], [:bar, 1]]
3778 * Array(0..4) # => [0, 1, 2, 3, 4]
3779 *
3780 * Returns +object+ in an array, <tt>[object]</tt>,
3781 * if +object+ cannot be converted:
3782 *
3783 * Array(:foo) # => [:foo]
3784 *
3785 */
3786
3787static VALUE
3788rb_f_array(VALUE obj, VALUE arg)
3789{
3790 return rb_Array(arg);
3791}
3792
3796 VALUE
3797rb_Hash(VALUE val)
3798{
3799 VALUE tmp;
3800
3801 if (NIL_P(val)) return rb_hash_new();
3802 tmp = rb_check_hash_type(val);
3803 if (NIL_P(tmp)) {
3804 if (RB_TYPE_P(val, T_ARRAY) && RARRAY_LEN(val) == 0)
3805 return rb_hash_new();
3806 rb_raise(rb_eTypeError, "can't convert %s into Hash", rb_obj_classname(val));
3807 }
3808 return tmp;
3809}
3810
3811/*
3812 * call-seq:
3813 * Hash(object) -> object or new_hash
3814 *
3815 * Returns a hash converted from +object+.
3816 *
3817 * - If +object+ is:
3818 *
3819 * - A hash, returns +object+.
3820 * - An empty array or +nil+, returns an empty hash.
3821 *
3822 * - Otherwise, if <tt>object.to_hash</tt> returns a hash, returns that hash.
3823 * - Otherwise, returns TypeError.
3824 *
3825 * Examples:
3826 *
3827 * Hash({foo: 0, bar: 1}) # => {:foo=>0, :bar=>1}
3828 * Hash(nil) # => {}
3829 * Hash([]) # => {}
3830 *
3831 */
3832
3833static VALUE
3834rb_f_hash(VALUE obj, VALUE arg)
3835{
3836 return rb_Hash(arg);
3837}
3838
3840struct dig_method {
3841 VALUE klass;
3842 int basic;
3843};
3844
3845static ID id_dig;
3846
3847static int
3848dig_basic_p(VALUE obj, struct dig_method *cache)
3849{
3850 VALUE klass = RBASIC_CLASS(obj);
3851 if (klass != cache->klass) {
3852 cache->klass = klass;
3853 cache->basic = rb_method_basic_definition_p(klass, id_dig);
3854 }
3855 return cache->basic;
3856}
3857
3858static void
3859no_dig_method(int found, VALUE recv, ID mid, int argc, const VALUE *argv, VALUE data)
3860{
3861 if (!found) {
3862 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not have #dig method",
3863 CLASS_OF(data));
3864 }
3865}
3866
3868 VALUE
3869rb_obj_dig(int argc, VALUE *argv, VALUE obj, VALUE notfound)
3870{
3871 struct dig_method hash = {Qnil}, ary = {Qnil}, strt = {Qnil};
3872
3873 for (; argc > 0; ++argv, --argc) {
3874 if (NIL_P(obj)) return notfound;
3875 if (!SPECIAL_CONST_P(obj)) {
3876 switch (BUILTIN_TYPE(obj)) {
3877 case T_HASH:
3878 if (dig_basic_p(obj, &hash)) {
3879 obj = rb_hash_aref(obj, *argv);
3880 continue;
3881 }
3882 break;
3883 case T_ARRAY:
3884 if (dig_basic_p(obj, &ary)) {
3885 obj = rb_ary_at(obj, *argv);
3886 continue;
3887 }
3888 break;
3889 case T_STRUCT:
3890 if (dig_basic_p(obj, &strt)) {
3891 obj = rb_struct_lookup(obj, *argv);
3892 continue;
3893 }
3894 break;
3895 default:
3896 break;
3897 }
3898 }
3899 return rb_check_funcall_with_hook_kw(obj, id_dig, argc, argv,
3900 no_dig_method, obj,
3901 RB_NO_KEYWORDS);
3902 }
3903 return obj;
3904}
3905
3906/*
3907 * call-seq:
3908 * sprintf(format_string *objects) -> string
3909 *
3910 * Returns the string resulting from formatting +objects+
3911 * into +format_string+.
3912 *
3913 * For details on +format_string+, see
3914 * {Format Specifications}[rdoc-ref:format_specifications.rdoc].
3915 */
3916
3917static VALUE
3918f_sprintf(int c, const VALUE *v, VALUE _)
3919{
3920 return rb_f_sprintf(c, v);
3921}
3922
3923static VALUE
3924rb_f_loop_size(VALUE self, VALUE args, VALUE eobj)
3925{
3926 return DBL2NUM(HUGE_VAL);
3927}
3928
3929/*
3930 * Document-class: Class
3931 *
3932 * Classes in Ruby are first-class objects---each is an instance of
3933 * class Class.
3934 *
3935 * Typically, you create a new class by using:
3936 *
3937 * class Name
3938 * # some code describing the class behavior
3939 * end
3940 *
3941 * When a new class is created, an object of type Class is initialized and
3942 * assigned to a global constant (Name in this case).
3943 *
3944 * When <code>Name.new</code> is called to create a new object, the
3945 * #new method in Class is run by default.
3946 * This can be demonstrated by overriding #new in Class:
3947 *
3948 * class Class
3949 * alias old_new new
3950 * def new(*args)
3951 * print "Creating a new ", self.name, "\n"
3952 * old_new(*args)
3953 * end
3954 * end
3955 *
3956 * class Name
3957 * end
3958 *
3959 * n = Name.new
3960 *
3961 * <em>produces:</em>
3962 *
3963 * Creating a new Name
3964 *
3965 * Classes, modules, and objects are interrelated. In the diagram
3966 * that follows, the vertical arrows represent inheritance, and the
3967 * parentheses metaclasses. All metaclasses are instances
3968 * of the class `Class'.
3969 * +---------+ +-...
3970 * | | |
3971 * BasicObject-----|-->(BasicObject)-------|-...
3972 * ^ | ^ |
3973 * | | | |
3974 * Object---------|----->(Object)---------|-...
3975 * ^ | ^ |
3976 * | | | |
3977 * +-------+ | +--------+ |
3978 * | | | | | |
3979 * | Module-|---------|--->(Module)-|-...
3980 * | ^ | | ^ |
3981 * | | | | | |
3982 * | Class-|---------|---->(Class)-|-...
3983 * | ^ | | ^ |
3984 * | +---+ | +----+
3985 * | |
3986 * obj--->OtherClass---------->(OtherClass)-----------...
3987 *
3988 */
3989
3990
3991/*
3992 * Document-class: BasicObject
3993 *
3994 * +BasicObject+ is the parent class of all classes in Ruby.
3995 * In particular, +BasicObject+ is the parent class of class Object,
3996 * which is itself the default parent class of every Ruby class:
3997 *
3998 * class Foo; end
3999 * Foo.superclass # => Object
4000 * Object.superclass # => BasicObject
4001 *
4002 * +BasicObject+ is the only class that has no parent:
4003 *
4004 * BasicObject.superclass # => nil
4005 *
4006 * \Class +BasicObject+ can be used to create an object hierarchy
4007 * (e.g., class Delegator) that is independent of Ruby's object hierarchy.
4008 * Such objects:
4009 *
4010 * - Do not have namespace "pollution" from the many methods
4011 * provided in class Object and its included module Kernel.
4012 * - Do not have definitions of common classes,
4013 * and so references to such common classes must be fully qualified
4014 * (+::String+, not +String+).
4015 *
4016 * A variety of strategies can be used to provide useful portions
4017 * of the Standard Library in subclasses of +BasicObject+:
4018 *
4019 * - The immediate subclass could <tt>include Kernel</tt>,
4020 * which would define methods such as +puts+, +exit+, etc.
4021 * - A custom Kernel-like module could be created and included.
4022 * - Delegation can be used via #method_missing:
4023 *
4024 * class MyObjectSystem < BasicObject
4025 * DELEGATE = [:puts, :p]
4026 *
4027 * def method_missing(name, *args, &block)
4028 * return super unless DELEGATE.include? name
4029 * ::Kernel.send(name, *args, &block)
4030 * end
4031 *
4032 * def respond_to_missing?(name, include_private = false)
4033 * DELEGATE.include?(name)
4034 * end
4035 * end
4036 *
4037 * === What's Here
4038 *
4039 * These are the methods defined for \BasicObject:
4040 *
4041 * - ::new: Returns a new \BasicObject instance.
4042 * - #!: Returns the boolean negation of +self+: +true+ or +false+.
4043 * - #!=: Returns whether +self+ and the given object are _not_ equal.
4044 * - #==: Returns whether +self+ and the given object are equivalent.
4045 * - #__id__: Returns the integer object identifier for +self+.
4046 * - #__send__: Calls the method identified by the given symbol.
4047 * - #equal?: Returns whether +self+ and the given object are the same object.
4048 * - #instance_eval: Evaluates the given string or block in the context of +self+.
4049 * - #instance_exec: Executes the given block in the context of +self+, passing the given arguments.
4050 * - #method_missing: Called when +self+ is called with a method it does not define.
4051 * - #singleton_method_added: Called when a singleton method is added to +self+.
4052 * - #singleton_method_removed: Called when a singleton method is removed from +self+.
4053 * - #singleton_method_undefined: Called when a singleton method is undefined in +self+.
4054 *
4055 */
4056
4057/* Document-class: Object
4058 *
4059 * Object is the default root of all Ruby objects. Object inherits from
4060 * BasicObject which allows creating alternate object hierarchies. Methods
4061 * on Object are available to all classes unless explicitly overridden.
4062 *
4063 * Object mixes in the Kernel module, making the built-in kernel functions
4064 * globally accessible. Although the instance methods of Object are defined
4065 * by the Kernel module, we have chosen to document them here for clarity.
4066 *
4067 * When referencing constants in classes inheriting from Object you do not
4068 * need to use the full namespace. For example, referencing +File+ inside
4069 * +YourClass+ will find the top-level File class.
4070 *
4071 * In the descriptions of Object's methods, the parameter <i>symbol</i> refers
4072 * to a symbol, which is either a quoted string or a Symbol (such as
4073 * <code>:name</code>).
4074 *
4075 * == What's Here
4076 *
4077 * First, what's elsewhere. \Class \Object:
4078 *
4079 * - Inherits from {class BasicObject}[rdoc-ref:BasicObject@What-27s+Here].
4080 * - Includes {module Kernel}[rdoc-ref:Kernel@What-27s+Here].
4081 *
4082 * Here, class \Object provides methods for:
4083 *
4084 * - {Querying}[rdoc-ref:Object@Querying]
4085 * - {Instance Variables}[rdoc-ref:Object@Instance+Variables]
4086 * - {Other}[rdoc-ref:Object@Other]
4087 *
4088 * === Querying
4089 *
4090 * - #!~: Returns +true+ if +self+ does not match the given object,
4091 * otherwise +false+.
4092 * - #<=>: Returns 0 if +self+ and the given object +object+ are the same
4093 * object, or if <tt>self == object</tt>; otherwise returns +nil+.
4094 * - #===: Implements case equality, effectively the same as calling #==.
4095 * - #eql?: Implements hash equality, effectively the same as calling #==.
4096 * - #kind_of? (aliased as #is_a?): Returns whether given argument is an ancestor
4097 * of the singleton class of +self+.
4098 * - #instance_of?: Returns whether +self+ is an instance of the given class.
4099 * - #instance_variable_defined?: Returns whether the given instance variable
4100 * is defined in +self+.
4101 * - #method: Returns the Method object for the given method in +self+.
4102 * - #methods: Returns an array of symbol names of public and protected methods
4103 * in +self+.
4104 * - #nil?: Returns +false+. (Only +nil+ responds +true+ to method <tt>nil?</tt>.)
4105 * - #object_id: Returns an integer corresponding to +self+ that is unique
4106 * for the current process
4107 * - #private_methods: Returns an array of the symbol names
4108 * of the private methods in +self+.
4109 * - #protected_methods: Returns an array of the symbol names
4110 * of the protected methods in +self+.
4111 * - #public_method: Returns the Method object for the given public method in +self+.
4112 * - #public_methods: Returns an array of the symbol names
4113 * of the public methods in +self+.
4114 * - #respond_to?: Returns whether +self+ responds to the given method.
4115 * - #singleton_class: Returns the singleton class of +self+.
4116 * - #singleton_method: Returns the Method object for the given singleton method
4117 * in +self+.
4118 * - #singleton_methods: Returns an array of the symbol names
4119 * of the singleton methods in +self+.
4120 *
4121 * - #define_singleton_method: Defines a singleton method in +self+
4122 * for the given symbol method-name and block or proc.
4123 * - #extend: Includes the given modules in the singleton class of +self+.
4124 * - #public_send: Calls the given public method in +self+ with the given argument.
4125 * - #send: Calls the given method in +self+ with the given argument.
4126 *
4127 * === Instance Variables
4128 *
4129 * - #instance_variable_get: Returns the value of the given instance variable
4130 * in +self+, or +nil+ if the instance variable is not set.
4131 * - #instance_variable_set: Sets the value of the given instance variable in +self+
4132 * to the given object.
4133 * - #instance_variables: Returns an array of the symbol names
4134 * of the instance variables in +self+.
4135 * - #remove_instance_variable: Removes the named instance variable from +self+.
4136 *
4137 * === Other
4138 *
4139 * - #clone: Returns a shallow copy of +self+, including singleton class
4140 * and frozen state.
4141 * - #define_singleton_method: Defines a singleton method in +self+
4142 * for the given symbol method-name and block or proc.
4143 * - #display: Prints +self+ to the given IO stream or <tt>$stdout</tt>.
4144 * - #dup: Returns a shallow unfrozen copy of +self+.
4145 * - #enum_for (aliased as #to_enum): Returns an Enumerator for +self+
4146 * using the using the given method, arguments, and block.
4147 * - #extend: Includes the given modules in the singleton class of +self+.
4148 * - #freeze: Prevents further modifications to +self+.
4149 * - #hash: Returns the integer hash value for +self+.
4150 * - #inspect: Returns a human-readable string representation of +self+.
4151 * - #itself: Returns +self+.
4152 * - #method_missing: Method called when an undefined method is called on +self+.
4153 * - #public_send: Calls the given public method in +self+ with the given argument.
4154 * - #send: Calls the given method in +self+ with the given argument.
4155 * - #to_s: Returns a string representation of +self+.
4156 *
4157 */
4158
4159void
4160InitVM_Object(void)
4161{
4162 Init_class_hierarchy();
4163
4164#if 0
4165 // teach RDoc about these classes
4166 rb_cBasicObject = rb_define_class("BasicObject", Qnil);
4167 rb_cObject = rb_define_class("Object", rb_cBasicObject);
4168 rb_cModule = rb_define_class("Module", rb_cObject);
4169 rb_cClass = rb_define_class("Class", rb_cModule);
4170 rb_cRefinement = rb_define_class("Refinement", rb_cModule);
4171#endif
4172
4173 rb_define_private_method(rb_cBasicObject, "initialize", rb_obj_initialize, 0);
4174 rb_define_alloc_func(rb_cBasicObject, rb_class_allocate_instance);
4175 rb_define_method(rb_cBasicObject, "==", rb_obj_equal, 1);
4176 rb_define_method(rb_cBasicObject, "equal?", rb_obj_equal, 1);
4177 rb_define_method(rb_cBasicObject, "!", rb_obj_not, 0);
4178 rb_define_method(rb_cBasicObject, "!=", rb_obj_not_equal, 1);
4179
4180 rb_define_private_method(rb_cBasicObject, "singleton_method_added", rb_obj_singleton_method_added, 1);
4181 rb_define_private_method(rb_cBasicObject, "singleton_method_removed", rb_obj_singleton_method_removed, 1);
4182 rb_define_private_method(rb_cBasicObject, "singleton_method_undefined", rb_obj_singleton_method_undefined, 1);
4183
4184 /* Document-module: Kernel
4185 *
4186 * The Kernel module is included by class Object, so its methods are
4187 * available in every Ruby object.
4188 *
4189 * The Kernel instance methods are documented in class Object while the
4190 * module methods are documented here. These methods are called without a
4191 * receiver and thus can be called in functional form:
4192 *
4193 * sprintf "%.1f", 1.234 #=> "1.2"
4194 *
4195 * == What's Here
4196 *
4197 * \Module \Kernel provides methods that are useful for:
4198 *
4199 * - {Converting}[rdoc-ref:Kernel@Converting]
4200 * - {Querying}[rdoc-ref:Kernel@Querying]
4201 * - {Exiting}[rdoc-ref:Kernel@Exiting]
4202 * - {Exceptions}[rdoc-ref:Kernel@Exceptions]
4203 * - {IO}[rdoc-ref:Kernel@IO]
4204 * - {Procs}[rdoc-ref:Kernel@Procs]
4205 * - {Tracing}[rdoc-ref:Kernel@Tracing]
4206 * - {Subprocesses}[rdoc-ref:Kernel@Subprocesses]
4207 * - {Loading}[rdoc-ref:Kernel@Loading]
4208 * - {Yielding}[rdoc-ref:Kernel@Yielding]
4209 * - {Random Values}[rdoc-ref:Kernel@Random+Values]
4210 * - {Other}[rdoc-ref:Kernel@Other]
4211 *
4212 * === Converting
4213 *
4214 * - #Array: Returns an Array based on the given argument.
4215 * - #Complex: Returns a Complex based on the given arguments.
4216 * - #Float: Returns a Float based on the given arguments.
4217 * - #Hash: Returns a Hash based on the given argument.
4218 * - #Integer: Returns an Integer based on the given arguments.
4219 * - #Rational: Returns a Rational based on the given arguments.
4220 * - #String: Returns a String based on the given argument.
4221 *
4222 * === Querying
4223 *
4224 * - #__callee__: Returns the called name of the current method as a symbol.
4225 * - #__dir__: Returns the path to the directory from which the current
4226 * method is called.
4227 * - #__method__: Returns the name of the current method as a symbol.
4228 * - #autoload?: Returns the file to be loaded when the given module is referenced.
4229 * - #binding: Returns a Binding for the context at the point of call.
4230 * - #block_given?: Returns +true+ if a block was passed to the calling method.
4231 * - #caller: Returns the current execution stack as an array of strings.
4232 * - #caller_locations: Returns the current execution stack as an array
4233 * of Thread::Backtrace::Location objects.
4234 * - #class: Returns the class of +self+.
4235 * - #frozen?: Returns whether +self+ is frozen.
4236 * - #global_variables: Returns an array of global variables as symbols.
4237 * - #local_variables: Returns an array of local variables as symbols.
4238 * - #test: Performs specified tests on the given single file or pair of files.
4239 *
4240 * === Exiting
4241 *
4242 * - #abort: Exits the current process after printing the given arguments.
4243 * - #at_exit: Executes the given block when the process exits.
4244 * - #exit: Exits the current process after calling any registered
4245 * +at_exit+ handlers.
4246 * - #exit!: Exits the current process without calling any registered
4247 * +at_exit+ handlers.
4248 *
4249 * === Exceptions
4250 *
4251 * - #catch: Executes the given block, possibly catching a thrown object.
4252 * - #raise (aliased as #fail): Raises an exception based on the given arguments.
4253 * - #throw: Returns from the active catch block waiting for the given tag.
4254 *
4255 *
4256 * === \IO
4257 *
4258 * - ::pp: Prints the given objects in pretty form.
4259 * - #gets: Returns and assigns to <tt>$_</tt> the next line from the current input.
4260 * - #open: Creates an IO object connected to the given stream, file, or subprocess.
4261 * - #p: Prints the given objects' inspect output to the standard output.
4262 * - #print: Prints the given objects to standard output without a newline.
4263 * - #printf: Prints the string resulting from applying the given format string
4264 * to any additional arguments.
4265 * - #putc: Equivalent to <tt.$stdout.putc(object)</tt> for the given object.
4266 * - #puts: Equivalent to <tt>$stdout.puts(*objects)</tt> for the given objects.
4267 * - #readline: Similar to #gets, but raises an exception at the end of file.
4268 * - #readlines: Returns an array of the remaining lines from the current input.
4269 * - #select: Same as IO.select.
4270 *
4271 * === Procs
4272 *
4273 * - #lambda: Returns a lambda proc for the given block.
4274 * - #proc: Returns a new Proc; equivalent to Proc.new.
4275 *
4276 * === Tracing
4277 *
4278 * - #set_trace_func: Sets the given proc as the handler for tracing,
4279 * or disables tracing if given +nil+.
4280 * - #trace_var: Starts tracing assignments to the given global variable.
4281 * - #untrace_var: Disables tracing of assignments to the given global variable.
4282 *
4283 * === Subprocesses
4284 *
4285 * - {\`command`}[rdoc-ref:Kernel#`]: Returns the standard output of running
4286 * +command+ in a subshell.
4287 * - #exec: Replaces current process with a new process.
4288 * - #fork: Forks the current process into two processes.
4289 * - #spawn: Executes the given command and returns its pid without waiting
4290 * for completion.
4291 * - #system: Executes the given command in a subshell.
4292 *
4293 * === Loading
4294 *
4295 * - #autoload: Registers the given file to be loaded when the given constant
4296 * is first referenced.
4297 * - #load: Loads the given Ruby file.
4298 * - #require: Loads the given Ruby file unless it has already been loaded.
4299 * - #require_relative: Loads the Ruby file path relative to the calling file,
4300 * unless it has already been loaded.
4301 *
4302 * === Yielding
4303 *
4304 * - #tap: Yields +self+ to the given block; returns +self+.
4305 * - #then (aliased as #yield_self): Yields +self+ to the block
4306 * and returns the result of the block.
4307 *
4308 * === \Random Values
4309 *
4310 * - #rand: Returns a pseudo-random floating point number
4311 * strictly between 0.0 and 1.0.
4312 * - #srand: Seeds the pseudo-random number generator with the given number.
4313 *
4314 * === Other
4315 *
4316 * - #eval: Evaluates the given string as Ruby code.
4317 * - #loop: Repeatedly executes the given block.
4318 * - #sleep: Suspends the current thread for the given number of seconds.
4319 * - #sprintf (aliased as #format): Returns the string resulting from applying
4320 * the given format string to any additional arguments.
4321 * - #syscall: Runs an operating system call.
4322 * - #trap: Specifies the handling of system signals.
4323 * - #warn: Issue a warning based on the given messages and options.
4324 *
4325 */
4326 rb_mKernel = rb_define_module("Kernel");
4327 rb_include_module(rb_cObject, rb_mKernel);
4328 rb_define_private_method(rb_cClass, "inherited", rb_obj_class_inherited, 1);
4329 rb_define_private_method(rb_cModule, "included", rb_obj_mod_included, 1);
4330 rb_define_private_method(rb_cModule, "extended", rb_obj_mod_extended, 1);
4331 rb_define_private_method(rb_cModule, "prepended", rb_obj_mod_prepended, 1);
4332 rb_define_private_method(rb_cModule, "method_added", rb_obj_mod_method_added, 1);
4333 rb_define_private_method(rb_cModule, "const_added", rb_obj_mod_const_added, 1);
4334 rb_define_private_method(rb_cModule, "method_removed", rb_obj_mod_method_removed, 1);
4335 rb_define_private_method(rb_cModule, "method_undefined", rb_obj_mod_method_undefined, 1);
4336
4337 rb_define_method(rb_mKernel, "nil?", rb_false, 0);
4338 rb_define_method(rb_mKernel, "===", case_equal, 1);
4339 rb_define_method(rb_mKernel, "!~", rb_obj_not_match, 1);
4340 rb_define_method(rb_mKernel, "eql?", rb_obj_equal, 1);
4341 rb_define_method(rb_mKernel, "hash", rb_obj_hash, 0); /* in hash.c */
4342 rb_define_method(rb_mKernel, "<=>", rb_obj_cmp, 1);
4343
4344 rb_define_method(rb_mKernel, "singleton_class", rb_obj_singleton_class, 0);
4345 rb_define_method(rb_mKernel, "dup", rb_obj_dup, 0);
4346 rb_define_method(rb_mKernel, "itself", rb_obj_itself, 0);
4347 rb_define_method(rb_mKernel, "initialize_copy", rb_obj_init_copy, 1);
4348 rb_define_method(rb_mKernel, "initialize_dup", rb_obj_init_dup_clone, 1);
4349 rb_define_method(rb_mKernel, "initialize_clone", rb_obj_init_clone, -1);
4350
4351 rb_define_method(rb_mKernel, "freeze", rb_obj_freeze, 0);
4352
4353 rb_define_method(rb_mKernel, "to_s", rb_any_to_s, 0);
4354 rb_define_method(rb_mKernel, "inspect", rb_obj_inspect, 0);
4355 rb_define_method(rb_mKernel, "methods", rb_obj_methods, -1); /* in class.c */
4356 rb_define_method(rb_mKernel, "singleton_methods", rb_obj_singleton_methods, -1); /* in class.c */
4357 rb_define_method(rb_mKernel, "protected_methods", rb_obj_protected_methods, -1); /* in class.c */
4358 rb_define_method(rb_mKernel, "private_methods", rb_obj_private_methods, -1); /* in class.c */
4359 rb_define_method(rb_mKernel, "public_methods", rb_obj_public_methods, -1); /* in class.c */
4360 rb_define_method(rb_mKernel, "instance_variables", rb_obj_instance_variables, 0); /* in variable.c */
4361 rb_define_method(rb_mKernel, "instance_variable_get", rb_obj_ivar_get, 1);
4362 rb_define_method(rb_mKernel, "instance_variable_set", rb_obj_ivar_set_m, 2);
4363 rb_define_method(rb_mKernel, "instance_variable_defined?", rb_obj_ivar_defined, 1);
4364 rb_define_method(rb_mKernel, "remove_instance_variable",
4365 rb_obj_remove_instance_variable, 1); /* in variable.c */
4366
4367 rb_define_method(rb_mKernel, "instance_of?", rb_obj_is_instance_of, 1);
4368 rb_define_method(rb_mKernel, "kind_of?", rb_obj_is_kind_of, 1);
4369 rb_define_method(rb_mKernel, "is_a?", rb_obj_is_kind_of, 1);
4370
4371 rb_define_global_function("sprintf", f_sprintf, -1);
4372 rb_define_global_function("format", f_sprintf, -1);
4373
4374 rb_define_global_function("String", rb_f_string, 1);
4375 rb_define_global_function("Array", rb_f_array, 1);
4376 rb_define_global_function("Hash", rb_f_hash, 1);
4377
4378 rb_cNilClass = rb_define_class("NilClass", rb_cObject);
4379 rb_cNilClass_to_s = rb_fstring_enc_lit("", rb_usascii_encoding());
4380 rb_vm_register_global_object(rb_cNilClass_to_s);
4381 rb_define_method(rb_cNilClass, "to_s", rb_nil_to_s, 0);
4382 rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0);
4383 rb_define_method(rb_cNilClass, "to_h", nil_to_h, 0);
4384 rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0);
4385 rb_define_method(rb_cNilClass, "=~", nil_match, 1);
4386 rb_define_method(rb_cNilClass, "&", false_and, 1);
4387 rb_define_method(rb_cNilClass, "|", false_or, 1);
4388 rb_define_method(rb_cNilClass, "^", false_xor, 1);
4389 rb_define_method(rb_cNilClass, "===", case_equal, 1);
4390
4391 rb_define_method(rb_cNilClass, "nil?", rb_true, 0);
4392 rb_undef_alloc_func(rb_cNilClass);
4393 rb_undef_method(CLASS_OF(rb_cNilClass), "new");
4394
4395 rb_define_method(rb_cModule, "freeze", rb_mod_freeze, 0);
4396 rb_define_method(rb_cModule, "===", rb_mod_eqq, 1);
4397 rb_define_method(rb_cModule, "==", rb_obj_equal, 1);
4398 rb_define_method(rb_cModule, "<=>", rb_mod_cmp, 1);
4399 rb_define_method(rb_cModule, "<", rb_mod_lt, 1);
4400 rb_define_method(rb_cModule, "<=", rb_class_inherited_p, 1);
4401 rb_define_method(rb_cModule, ">", rb_mod_gt, 1);
4402 rb_define_method(rb_cModule, ">=", rb_mod_ge, 1);
4403 rb_define_method(rb_cModule, "initialize_copy", rb_mod_init_copy, 1); /* in class.c */
4404 rb_define_method(rb_cModule, "to_s", rb_mod_to_s, 0);
4405 rb_define_alias(rb_cModule, "inspect", "to_s");
4406 rb_define_method(rb_cModule, "included_modules", rb_mod_included_modules, 0); /* in class.c */
4407 rb_define_method(rb_cModule, "include?", rb_mod_include_p, 1); /* in class.c */
4408 rb_define_method(rb_cModule, "name", rb_mod_name, 0); /* in variable.c */
4409 rb_define_method(rb_cModule, "set_temporary_name", rb_mod_set_temporary_name, 1); /* in variable.c */
4410 rb_define_method(rb_cModule, "ancestors", rb_mod_ancestors, 0); /* in class.c */
4411
4412 rb_define_method(rb_cModule, "attr", rb_mod_attr, -1);
4413 rb_define_method(rb_cModule, "attr_reader", rb_mod_attr_reader, -1);
4414 rb_define_method(rb_cModule, "attr_writer", rb_mod_attr_writer, -1);
4415 rb_define_method(rb_cModule, "attr_accessor", rb_mod_attr_accessor, -1);
4416
4417 rb_define_alloc_func(rb_cModule, rb_module_s_alloc);
4418 rb_undef_method(rb_singleton_class(rb_cModule), "allocate");
4419 rb_define_method(rb_cModule, "initialize", rb_mod_initialize, 0);
4420 rb_define_method(rb_cModule, "initialize_clone", rb_mod_initialize_clone, -1);
4421 rb_define_method(rb_cModule, "instance_methods", rb_class_instance_methods, -1); /* in class.c */
4422 rb_define_method(rb_cModule, "public_instance_methods",
4423 rb_class_public_instance_methods, -1); /* in class.c */
4424 rb_define_method(rb_cModule, "protected_instance_methods",
4425 rb_class_protected_instance_methods, -1); /* in class.c */
4426 rb_define_method(rb_cModule, "private_instance_methods",
4427 rb_class_private_instance_methods, -1); /* in class.c */
4428 rb_define_method(rb_cModule, "undefined_instance_methods",
4429 rb_class_undefined_instance_methods, 0); /* in class.c */
4430
4431 rb_define_method(rb_cModule, "constants", rb_mod_constants, -1); /* in variable.c */
4432 rb_define_method(rb_cModule, "const_get", rb_mod_const_get, -1);
4433 rb_define_method(rb_cModule, "const_set", rb_mod_const_set, 2);
4434 rb_define_method(rb_cModule, "const_defined?", rb_mod_const_defined, -1);
4435 rb_define_method(rb_cModule, "const_source_location", rb_mod_const_source_location, -1);
4436 rb_define_private_method(rb_cModule, "remove_const",
4437 rb_mod_remove_const, 1); /* in variable.c */
4438 rb_define_method(rb_cModule, "const_missing",
4439 rb_mod_const_missing, 1); /* in variable.c */
4440 rb_define_method(rb_cModule, "class_variables",
4441 rb_mod_class_variables, -1); /* in variable.c */
4442 rb_define_method(rb_cModule, "remove_class_variable",
4443 rb_mod_remove_cvar, 1); /* in variable.c */
4444 rb_define_method(rb_cModule, "class_variable_get", rb_mod_cvar_get, 1);
4445 rb_define_method(rb_cModule, "class_variable_set", rb_mod_cvar_set, 2);
4446 rb_define_method(rb_cModule, "class_variable_defined?", rb_mod_cvar_defined, 1);
4447 rb_define_method(rb_cModule, "public_constant", rb_mod_public_constant, -1); /* in variable.c */
4448 rb_define_method(rb_cModule, "private_constant", rb_mod_private_constant, -1); /* in variable.c */
4449 rb_define_method(rb_cModule, "deprecate_constant", rb_mod_deprecate_constant, -1); /* in variable.c */
4450 rb_define_method(rb_cModule, "singleton_class?", rb_mod_singleton_p, 0);
4451
4452 rb_define_method(rb_singleton_class(rb_cClass), "allocate", rb_class_alloc_m, 0);
4453 rb_define_method(rb_cClass, "allocate", rb_class_alloc_m, 0);
4454 rb_define_method(rb_cClass, "new", rb_class_new_instance_pass_kw, -1);
4455 rb_define_method(rb_cClass, "initialize", rb_class_initialize, -1);
4456 rb_define_method(rb_cClass, "superclass", rb_class_superclass, 0);
4457 rb_define_method(rb_cClass, "subclasses", rb_class_subclasses, 0); /* in class.c */
4458 rb_define_method(rb_cClass, "attached_object", rb_class_attached_object, 0); /* in class.c */
4459 rb_define_alloc_func(rb_cClass, rb_class_s_alloc);
4460 rb_undef_method(rb_cClass, "extend_object");
4461 rb_undef_method(rb_cClass, "append_features");
4462 rb_undef_method(rb_cClass, "prepend_features");
4463
4464 rb_cTrueClass = rb_define_class("TrueClass", rb_cObject);
4465 rb_cTrueClass_to_s = rb_fstring_enc_lit("true", rb_usascii_encoding());
4466 rb_vm_register_global_object(rb_cTrueClass_to_s);
4467 rb_define_method(rb_cTrueClass, "to_s", rb_true_to_s, 0);
4468 rb_define_alias(rb_cTrueClass, "inspect", "to_s");
4469 rb_define_method(rb_cTrueClass, "&", true_and, 1);
4470 rb_define_method(rb_cTrueClass, "|", true_or, 1);
4471 rb_define_method(rb_cTrueClass, "^", true_xor, 1);
4472 rb_define_method(rb_cTrueClass, "===", case_equal, 1);
4473 rb_undef_alloc_func(rb_cTrueClass);
4474 rb_undef_method(CLASS_OF(rb_cTrueClass), "new");
4475
4476 rb_cFalseClass = rb_define_class("FalseClass", rb_cObject);
4477 rb_cFalseClass_to_s = rb_fstring_enc_lit("false", rb_usascii_encoding());
4478 rb_vm_register_global_object(rb_cFalseClass_to_s);
4479 rb_define_method(rb_cFalseClass, "to_s", rb_false_to_s, 0);
4480 rb_define_alias(rb_cFalseClass, "inspect", "to_s");
4481 rb_define_method(rb_cFalseClass, "&", false_and, 1);
4482 rb_define_method(rb_cFalseClass, "|", false_or, 1);
4483 rb_define_method(rb_cFalseClass, "^", false_xor, 1);
4484 rb_define_method(rb_cFalseClass, "===", case_equal, 1);
4485 rb_undef_alloc_func(rb_cFalseClass);
4486 rb_undef_method(CLASS_OF(rb_cFalseClass), "new");
4487}
4488
4489#include "kernel.rbinc"
4490#include "nilclass.rbinc"
4491
4492void
4493Init_Object(void)
4494{
4495 id_dig = rb_intern_const("dig");
4496 InitVM(Object);
4497}
4498
assert.h
RUBY_ASSERT
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
rb_define_method
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
Definition cxxanyargs.hpp:670
rb_define_private_method
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
Definition cxxanyargs.hpp:677
rb_define_global_function
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
Definition cxxanyargs.hpp:695
RB_OBJ_FROZEN
static bool RB_OBJ_FROZEN(VALUE obj)
Checks if an object is frozen.
Definition fl_type.h:898
RUBY_FL_PROMOTED
@ RUBY_FL_PROMOTED
Ruby objects are "generational".
Definition fl_type.h:218
RUBY_FL_SEEN_OBJ_ID
@ RUBY_FL_SEEN_OBJ_ID
This flag has something to do with object IDs.
Definition fl_type.h:300
rb_class_protected_instance_methods
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:1912
rb_include_module
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1187
rb_define_class
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:980
rb_class_subclasses
VALUE rb_class_subclasses(VALUE klass)
Queries the class's direct descendants.
Definition class.c:1692
rb_singleton_class
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2297
rb_class_attached_object
VALUE rb_class_attached_object(VALUE klass)
Returns the attached object for a singleton class.
Definition class.c:1715
rb_obj_singleton_methods
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:2089
rb_class_instance_methods
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:1897
rb_check_inheritable
void rb_check_inheritable(VALUE super)
Asserts that the given class can derive a child class.
Definition class.c:344
rb_class_public_instance_methods
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:1950
rb_define_module
VALUE rb_define_module(const char *name)
Defines a top-level module.
Definition class.c:1095
rb_singleton_class_attached
void rb_singleton_class_attached(VALUE klass, VALUE obj)
Attaches a singleton class to its corresponding object.
Definition class.c:709
rb_mod_included_modules
VALUE rb_mod_included_modules(VALUE mod)
Queries the list of included modules.
Definition class.c:1510
rb_mod_ancestors
VALUE rb_mod_ancestors(VALUE mod)
Queries the module's ancestors.
Definition class.c:1578
rb_class_inherited
VALUE rb_class_inherited(VALUE super, VALUE klass)
Calls Class#inherited.
Definition class.c:971
rb_mod_include_p
VALUE rb_mod_include_p(VALUE mod, VALUE mod2)
Queries if the passed module is included by the module.
Definition class.c:1546
rb_class_private_instance_methods
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:1935
rb_mod_init_copy
VALUE rb_mod_init_copy(VALUE clone, VALUE orig)
The comment that comes with this function says :nodoc:.
Definition class.c:533
rb_define_alias
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2345
rb_undef_method
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2166
rb_scan_args
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:2635
rb_block_given_p
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:937
rb_get_kwargs
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2424
T_COMPLEX
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
TYPE
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
RB_INTEGER_TYPE_P
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
FL_EXIVAR
#define FL_EXIVAR
Old name of RUBY_FL_EXIVAR.
Definition fl_type.h:66
ALLOCV
#define ALLOCV
Old name of RB_ALLOCV.
Definition memory.h:404
ISSPACE
#define ISSPACE
Old name of rb_isspace.
Definition ctype.h:88
RFLOAT_VALUE
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
T_STRING
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
T_MASK
#define T_MASK
Old name of RUBY_T_MASK.
Definition value_type.h:68
Qundef
#define Qundef
Old name of RUBY_Qundef.
Definition special_consts.h:62
INT2FIX
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
OBJ_FROZEN
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:137
rb_str_cat2
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1683
T_FLOAT
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
ID2SYM
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
T_BIGNUM
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
SPECIAL_CONST_P
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
Definition special_consts.h:56
T_STRUCT
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition value_type.h:79
OBJ_FREEZE
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:135
UNREACHABLE_RETURN
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
T_DATA
#define T_DATA
Old name of RUBY_T_DATA.
Definition value_type.h:60
CLASS_OF
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:203
T_NONE
#define T_NONE
Old name of RUBY_T_NONE.
Definition value_type.h:74
FIXABLE
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
LONG2FIX
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
T_MODULE
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
ISDIGIT
#define ISDIGIT
Old name of rb_isdigit.
Definition ctype.h:93
T_RATIONAL
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
T_ICLASS
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
T_HASH
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
FL_TEST_RAW
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:132
rb_ary_new3
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
rb_usascii_str_new2
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1680
FLONUM_P
#define FLONUM_P
Old name of RB_FLONUM_P.
Definition special_consts.h:67
Qtrue
#define Qtrue
Old name of RUBY_Qtrue.
Definition special_consts.h:61
NUM2INT
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
Qnil
#define Qnil
Old name of RUBY_Qnil.
Definition special_consts.h:60
Qfalse
#define Qfalse
Old name of RUBY_Qfalse.
Definition special_consts.h:59
T_ARRAY
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
T_OBJECT
#define T_OBJECT
Old name of RUBY_T_OBJECT.
Definition value_type.h:75
NIL_P
#define NIL_P
Old name of RB_NIL_P.
Definition special_consts.h:55
FL_WB_PROTECTED
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition fl_type.h:59
T_SYMBOL
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
DBL2NUM
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
T_CLASS
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
BUILTIN_TYPE
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
FL_FREEZE
#define FL_FREEZE
Old name of RUBY_FL_FREEZE.
Definition fl_type.h:67
FIXNUM_P
#define FIXNUM_P
Old name of RB_FIXNUM_P.
Definition special_consts.h:53
CONST_ID
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
rb_ary_new2
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
FL_SET_RAW
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:130
ALLOCV_END
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
SYMBOL_P
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
rb_category_warning
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
rb_eTypeError
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1430
rb_warning
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:497
RB_WARN_CATEGORY_DEPRECATED
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition error.h:48
rb_cClass
VALUE rb_cClass
Class class.
Definition object.c:68
rb_cRational
VALUE rb_cRational
Rational class.
Definition rational.c:53
rb_class_superclass
VALUE rb_class_superclass(VALUE klass)
Returns the superclass of klass.
Definition object.c:2153
rb_obj_embedded_size
size_t rb_obj_embedded_size(uint32_t numiv)
Internal header for Object.
Definition object.c:98
rb_class_get_superclass
VALUE rb_class_get_superclass(VALUE klass)
Returns the superclass of a class.
Definition object.c:2175
rb_convert_type
VALUE rb_convert_type(VALUE val, int type, const char *tname, const char *method)
Converts an object into another type.
Definition object.c:3092
rb_Float
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition object.c:3599
rb_mKernel
VALUE rb_mKernel
Kernel module.
Definition object.c:65
rb_check_to_int
VALUE rb_check_to_int(VALUE val)
Identical to rb_check_to_integer(), except it uses #to_int for conversion.
Definition object.c:3198
rb_obj_reveal
VALUE rb_obj_reveal(VALUE obj, VALUE klass)
Make a hidden object visible again.
Definition object.c:113
rb_check_convert_type
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
rb_any_to_s
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:669
rb_obj_alloc
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2097
rb_class_new_instance
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
rb_class_new_instance_kw
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
rb_cRefinement
VALUE rb_cRefinement
Refinement class.
Definition object.c:69
rb_cInteger
VALUE rb_cInteger
Module class.
Definition numeric.c:198
rb_obj_hide
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:104
rb_class_new_instance_pass_kw
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
rb_check_to_float
VALUE rb_check_to_float(VALUE val)
This is complicated.
Definition object.c:3638
rb_obj_init_clone
static VALUE rb_obj_init_clone(int argc, VALUE *argv, VALUE obj)
Default implementation of #initialize_clone
Definition object.c:647
rb_cNilClass
VALUE rb_cNilClass
NilClass class.
Definition object.c:71
rb_Hash
VALUE rb_Hash(VALUE val)
Equivalent to Kernel#Hash in Ruby.
Definition object.c:3797
rb_obj_frozen_p
VALUE rb_obj_frozen_p(VALUE obj)
Just calls RB_OBJ_FROZEN() inside.
Definition object.c:1272
rb_obj_init_copy
VALUE rb_obj_init_copy(VALUE obj, VALUE orig)
Default implementation of #initialize_copy
Definition object.c:616
rb_eql
int rb_eql(VALUE obj1, VALUE obj2)
Checks for equality of the passed objects, in terms of Object#eql?.
Definition object.c:192
rb_str_to_dbl
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:3483
rb_Integer
VALUE rb_Integer(VALUE val)
This is the logic behind Kernel#Integer.
Definition object.c:3267
rb_cFalseClass
VALUE rb_cFalseClass
FalseClass class.
Definition object.c:73
rb_cNumeric
VALUE rb_cNumeric
Numeric class.
Definition numeric.c:196
rb_Array
VALUE rb_Array(VALUE val)
This is the logic behind Kernel#Array.
Definition object.c:3754
rb_obj_class
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:247
rb_obj_dup
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition object.c:576
rb_inspect
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:680
rb_cBasicObject
VALUE rb_cBasicObject
BasicObject class.
Definition object.c:64
rb_cModule
VALUE rb_cModule
Module class.
Definition object.c:67
rb_class_inherited_p
VALUE rb_class_inherited_p(VALUE mod, VALUE arg)
Determines if the given two modules are relatives.
Definition object.c:1768
rb_obj_is_instance_of
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
rb_class_real
VALUE rb_class_real(VALUE cl)
Finds a "real" class.
Definition object.c:237
rb_obj_init_dup_clone
VALUE rb_obj_init_dup_clone(VALUE obj, VALUE orig)
Default implementation of #initialize_dup
Definition object.c:633
rb_to_float
VALUE rb_to_float(VALUE val)
Identical to rb_check_to_float(), except it raises on error.
Definition object.c:3628
rb_num2dbl
double rb_num2dbl(VALUE val)
Converts an instance of rb_cNumeric into C's double.
Definition object.c:3690
rb_equal
VALUE rb_equal(VALUE obj1, VALUE obj2)
This function is an optimised version of calling #==.
Definition object.c:179
rb_obj_clone
VALUE rb_obj_clone(VALUE obj)
Produces a shallow copy of the given object.
Definition object.c:521
rb_obj_is_kind_of
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
rb_cstr_to_dbl
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:3439
rb_obj_freeze
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1260
rb_check_to_integer
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
rb_String
VALUE rb_String(VALUE val)
This is the logic behind Kernel#String.
Definition object.c:3722
rb_cTrueClass
VALUE rb_cTrueClass
TrueClass class.
Definition object.c:72
rb_to_int
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3192
rb_obj_setup
VALUE rb_obj_setup(VALUE obj, VALUE klass, VALUE type)
Fills common fields in the object.
Definition object.c:152
RB_OBJ_WRITTEN
#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.h
Encoding relates APIs.
rb_enc_str_new_cstr
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:1098
rb_enc_str_asciionly_p
int rb_enc_str_asciionly_p(VALUE str)
Queries if the passed string is "ASCII only".
Definition string.c:919
rb_check_id_cstr
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:1215
rb_funcall
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1099
rb_funcallv_kw
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
RGENGC_WB_PROTECTED_OBJECT
#define RGENGC_WB_PROTECTED_OBJECT
This is a compile-time flag to enable/disable write barrier for struct RObject.
Definition gc.h:490
rb_check_arity
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
rb_is_instance_id
int rb_is_instance_id(ID id)
Classifies the given ID, then sees if it is an instance variable.
Definition symbol.c:1081
rb_is_const_id
int rb_is_const_id(ID id)
Classifies the given ID, then sees if it is a constant.
Definition symbol.c:1063
rb_is_local_id
int rb_is_local_id(ID id)
Classifies the given ID, then sees if it is a local variable.
Definition symbol.c:1093
rb_rational_num
VALUE rb_rational_num(VALUE rat)
Queries the numerator of the passed Rational.
Definition rational.c:1989
rb_rational_den
VALUE rb_rational_den(VALUE rat)
Queries the denominator of the passed Rational.
Definition rational.c:1995
rb_str_append
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:3676
rb_str_subseq
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:3051
rb_str_buf_append
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:3642
rb_must_asciicompat
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2692
rb_str_concat
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:3918
rb_check_string_type
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2850
rb_str_intern
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:878
rb_exec_recursive
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
Definition thread.c:5332
rb_mod_remove_cvar
VALUE rb_mod_remove_cvar(VALUE mod, VALUE name)
Resembles Module#remove_class_variable.
Definition variable.c:4193
rb_obj_instance_variables
VALUE rb_obj_instance_variables(VALUE obj)
Resembles Object#instance_variables.
Definition variable.c:2207
rb_const_get
VALUE rb_const_get(VALUE space, ID name)
Identical to rb_const_defined(), except it returns the actual defined value.
Definition variable.c:3163
rb_ivar_set
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:1871
rb_mod_remove_const
VALUE rb_mod_remove_const(VALUE space, VALUE name)
Resembles Module#remove_const.
Definition variable.c:3268
rb_cvar_set
void rb_cvar_set(VALUE klass, ID name, VALUE val)
Assigns a value to a class variable.
Definition variable.c:3958
rb_cvar_get
VALUE rb_cvar_get(VALUE klass, ID name)
Obtains a value from a class variable.
Definition variable.c:4028
rb_mod_constants
VALUE rb_mod_constants(int argc, const VALUE *argv, VALUE recv)
Resembles Module#constants.
Definition variable.c:3429
rb_ivar_get
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:1362
rb_const_set
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:3635
rb_mod_name
VALUE rb_mod_name(VALUE mod)
Queries the name of a module.
Definition variable.c:130
rb_class_name
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:412
rb_const_get_at
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:3169
rb_obj_remove_instance_variable
VALUE rb_obj_remove_instance_variable(VALUE obj, VALUE name)
Resembles Object#remove_instance_variable.
Definition variable.c:2261
rb_ivar_count
st_index_t rb_ivar_count(VALUE obj)
Number of instance variables defined on an object.
Definition variable.c:2155
rb_const_get_from
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:3157
rb_ivar_defined
VALUE rb_ivar_defined(VALUE obj, ID name)
Queries if the instance variable is defined at the object.
Definition variable.c:1888
rb_const_defined_at
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:3491
rb_mod_class_variables
VALUE rb_mod_class_variables(int argc, const VALUE *argv, VALUE recv)
Resembles Module#class_variables.
Definition variable.c:4158
rb_cvar_defined
VALUE rb_cvar_defined(VALUE klass, ID name)
Queries if the given class has the given class variable.
Definition variable.c:4035
rb_const_defined_from
int rb_const_defined_from(VALUE space, ID name)
Identical to rb_const_defined(), except it returns false for private constants.
Definition variable.c:3479
rb_const_defined
int rb_const_defined(VALUE space, ID name)
Queries if the constant is defined at the namespace.
Definition variable.c:3485
rb_alloc_func_t
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
rb_undef_alloc_func
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1291
rb_attr
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:1869
rb_check_funcall
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_get_alloc_func
rb_alloc_func_t rb_get_alloc_func(VALUE klass)
Queries the allocator function of a class.
Definition vm_method.c:1297
rb_mod_module_exec
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:2333
rb_define_alloc_func
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
rb_obj_respond_to
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:2944
rb_intern_const
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:284
rb_check_id
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1117
len
int len
Length of the buffer.
Definition io.h:8
util.h
strtod
#define strtod(s, e)
Just another name of ruby_strtod.
Definition util.h:223
rb_f_sprintf
VALUE rb_f_sprintf(int argc, const VALUE *argv)
Identical to rb_str_format(), except how the arguments are arranged.
Definition sprintf.c:209
MEMCPY
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
RB_GC_GUARD
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
ruby::backward::cxxanyargs::type
VALUE type(ANYARGS)
ANYARGS-ed function type.
Definition cxxanyargs.hpp:56
ruby::backward::cxxanyargs::rb_ivar_foreach
void rb_ivar_foreach(VALUE q, int_type *w, VALUE e)
Iteration over each instance variable of the object.
Definition cxxanyargs.hpp:498
rb_copy_generic_ivar
void rb_copy_generic_ivar(VALUE clone, VALUE obj)
Copies the list of instance variables.
Definition variable.c:2048
RARRAY_LEN
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
RBASIC_CLASS
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition rbasic.h:150
RBASIC
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
RCLASS_SUPER
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
Definition rclass.h:44
RCLASS
#define RCLASS(obj)
Convenient casting macro.
Definition rclass.h:38
ROBJECT_IVPTR
static VALUE * ROBJECT_IVPTR(VALUE obj)
Queries the instance variables.
Definition robject.h:136
StringValue
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
StringValuePtr
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
Definition rstring.h:76
rb_class2name
const char * rb_class2name(VALUE klass)
Queries the name of the passed class.
Definition variable.c:418
rb_obj_classname
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:427
errno
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
InitVM
#define InitVM(ext)
This macro is for internal use.
Definition ruby.h:231
RB_PASS_KEYWORDS
#define RB_PASS_KEYWORDS
Pass keywords, final argument should be a hash of keywords.
Definition scan_args.h:72
RB_PASS_CALLED_KEYWORDS
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition scan_args.h:78
RB_NO_KEYWORDS
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
RTEST
#define RTEST
This is an old name of RB_TEST.
Definition special_consts.h:51
_
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
RObject
Ruby's ordinal objects.
Definition robject.h:83
ID
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
VALUE
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
RB_FLOAT_TYPE_P
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:264
Check_Type
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
RB_TYPE_P
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