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