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