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