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