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