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