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