Ruby: object.c Source File

Ruby 3.2.5p208 (2024-07-26 revision 31d0f1a2e7dbfb60731d1f05b868e1d578cda493)

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