Ruby 4.0.0dev (2025-12-06 revision 0346206d3eab2a8e659be0dd52aea6fc7b0ebb06)
variable.c (0346206d3eab2a8e659be0dd52aea6fc7b0ebb06)
1/**********************************************************************
2
3 variable.c -
4
5 $Author$
6 created at: Tue Apr 19 23:55:15 JST 1994
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#include <stddef.h>
17#include "ccan/list/list.h"
18#include "constant.h"
19#include "debug_counter.h"
20#include "id.h"
21#include "id_table.h"
22#include "internal.h"
23#include "internal/box.h"
24#include "internal/class.h"
25#include "internal/compilers.h"
26#include "internal/error.h"
27#include "internal/eval.h"
28#include "internal/hash.h"
29#include "internal/object.h"
30#include "internal/gc.h"
31#include "internal/re.h"
32#include "internal/struct.h"
33#include "internal/symbol.h"
34#include "internal/thread.h"
35#include "internal/variable.h"
36#include "ruby/encoding.h"
37#include "ruby/st.h"
38#include "ruby/util.h"
39#include "shape.h"
40#include "symbol.h"
41#include "variable.h"
42#include "vm_core.h"
43#include "ractor_core.h"
44#include "vm_sync.h"
45
46RUBY_EXTERN rb_serial_t ruby_vm_global_cvar_state;
47#define GET_GLOBAL_CVAR_STATE() (ruby_vm_global_cvar_state)
48
49typedef void rb_gvar_compact_t(void *var);
50
51static struct rb_id_table *rb_global_tbl;
52static ID autoload;
53
54// This hash table maps file paths to loadable features. We use this to track
55// autoload state until it's no longer needed.
56// feature (file path) => struct autoload_data
57static VALUE autoload_features;
58
59// This mutex is used to protect autoloading state. We use a global mutex which
60// is held until a per-feature mutex can be created. This ensures there are no
61// race conditions relating to autoload state.
62static VALUE autoload_mutex;
63
64static void check_before_mod_set(VALUE, ID, VALUE, const char *);
65static void setup_const_entry(rb_const_entry_t *, VALUE, VALUE, rb_const_flag_t);
66static VALUE rb_const_search(VALUE klass, ID id, int exclude, int recurse, int visibility);
67static st_table *generic_fields_tbl_;
68
69typedef int rb_ivar_foreach_callback_func(ID key, VALUE val, st_data_t arg);
70static void rb_field_foreach(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg, bool ivar_only);
71
72void
73Init_var_tables(void)
74{
75 rb_global_tbl = rb_id_table_create(0);
76 generic_fields_tbl_ = st_init_numtable();
77 autoload = rb_intern_const("__autoload__");
78
79 autoload_mutex = rb_mutex_new();
80 rb_obj_hide(autoload_mutex);
81 rb_vm_register_global_object(autoload_mutex);
82
83 autoload_features = rb_ident_hash_new();
84 rb_obj_hide(autoload_features);
85 rb_vm_register_global_object(autoload_features);
86}
87
88static inline bool
89rb_namespace_p(VALUE obj)
90{
91 if (RB_SPECIAL_CONST_P(obj)) return false;
92 switch (RB_BUILTIN_TYPE(obj)) {
93 case T_MODULE: case T_CLASS: return true;
94 default: break;
95 }
96 return false;
97}
98
109static VALUE
110classname(VALUE klass, bool *permanent)
111{
112 *permanent = false;
113
114 VALUE classpath = RCLASS_CLASSPATH(klass);
115 if (classpath == 0) return Qnil;
116
117 *permanent = RCLASS_PERMANENT_CLASSPATH_P(klass);
118
119 return classpath;
120}
121
122VALUE
123rb_mod_name0(VALUE klass, bool *permanent)
124{
125 return classname(klass, permanent);
126}
127
128/*
129 * call-seq:
130 * mod.name -> string or nil
131 *
132 * Returns the name of the module <i>mod</i>. Returns +nil+ for anonymous modules.
133 */
134
135VALUE
137{
138 // YJIT needs this function to not allocate.
139 bool permanent;
140 return classname(mod, &permanent);
141}
142
143// Similar to logic in rb_mod_const_get().
144static bool
145is_constant_path(VALUE name)
146{
147 const char *path = RSTRING_PTR(name);
148 const char *pend = RSTRING_END(name);
149 rb_encoding *enc = rb_enc_get(name);
150
151 const char *p = path;
152
153 if (p >= pend || !*p) {
154 return false;
155 }
156
157 while (p < pend) {
158 if (p + 2 <= pend && p[0] == ':' && p[1] == ':') {
159 p += 2;
160 }
161
162 const char *pbeg = p;
163 while (p < pend && *p != ':') p++;
164
165 if (pbeg == p) return false;
166
167 if (rb_enc_symname_type(pbeg, p - pbeg, enc, 0) != ID_CONST) {
168 return false;
169 }
170 }
171
172 return true;
173}
174
176 VALUE names;
177 ID last;
178};
179
180static VALUE build_const_path(VALUE head, ID tail);
181static void set_sub_temporary_name_foreach(VALUE mod, struct sub_temporary_name_args *args, VALUE name);
182
183static VALUE
184set_sub_temporary_name_recursive(VALUE mod, VALUE data, int recursive)
185{
186 if (recursive) return Qfalse;
187
188 struct sub_temporary_name_args *args = (void *)data;
189 VALUE name = 0;
190 if (args->names) {
191 name = build_const_path(rb_ary_last(0, 0, args->names), args->last);
192 }
193 set_sub_temporary_name_foreach(mod, args, name);
194 return Qtrue;
195}
196
197static VALUE
198set_sub_temporary_name_topmost(VALUE mod, VALUE data, int recursive)
199{
200 if (recursive) return Qfalse;
201
202 struct sub_temporary_name_args *args = (void *)data;
203 VALUE name = args->names;
204 if (name) {
205 args->names = rb_ary_hidden_new(0);
206 }
207 set_sub_temporary_name_foreach(mod, args, name);
208 return Qtrue;
209}
210
211static enum rb_id_table_iterator_result
212set_sub_temporary_name_i(ID id, VALUE val, void *data)
213{
214 val = ((rb_const_entry_t *)val)->value;
215 if (rb_namespace_p(val) && !RCLASS_PERMANENT_CLASSPATH_P(val)) {
216 VALUE arg = (VALUE)data;
217 struct sub_temporary_name_args *args = data;
218 args->last = id;
219 rb_exec_recursive_paired(set_sub_temporary_name_recursive, val, arg, arg);
220 }
221 return ID_TABLE_CONTINUE;
222}
223
224static void
225set_sub_temporary_name_foreach(VALUE mod, struct sub_temporary_name_args *args, VALUE name)
226{
227 RCLASS_WRITE_CLASSPATH(mod, name, FALSE);
228 struct rb_id_table *tbl = RCLASS_CONST_TBL(mod);
229 if (!tbl) return;
230 if (!name) {
231 rb_id_table_foreach(tbl, set_sub_temporary_name_i, args);
232 }
233 else {
234 long names_len = RARRAY_LEN(args->names); // paranoiac check?
235 rb_ary_push(args->names, name);
236 rb_id_table_foreach(tbl, set_sub_temporary_name_i, args);
237 rb_ary_set_len(args->names, names_len);
238 }
239}
240
241static void
242set_sub_temporary_name(VALUE mod, VALUE name)
243{
244 struct sub_temporary_name_args args = {name};
245 VALUE arg = (VALUE)&args;
246 rb_exec_recursive_paired(set_sub_temporary_name_topmost, mod, arg, arg);
247}
248
249/*
250 * call-seq:
251 * mod.set_temporary_name(string) -> self
252 * mod.set_temporary_name(nil) -> self
253 *
254 * Sets the temporary name of the module. This name is reflected in
255 * introspection of the module and the values that are related to it, such
256 * as instances, constants, and methods.
257 *
258 * The name should be +nil+ or a non-empty string that is not a valid constant
259 * path (to avoid confusing between permanent and temporary names).
260 *
261 * The method can be useful to distinguish dynamically generated classes and
262 * modules without assigning them to constants.
263 *
264 * If the module is given a permanent name by assigning it to a constant,
265 * the temporary name is discarded. A temporary name can't be assigned to
266 * modules that have a permanent name.
267 *
268 * If the given name is +nil+, the module becomes anonymous again.
269 *
270 * Example:
271 *
272 * m = Module.new # => #<Module:0x0000000102c68f38>
273 * m.name #=> nil
274 *
275 * m.set_temporary_name("fake_name") # => fake_name
276 * m.name #=> "fake_name"
277 *
278 * m.set_temporary_name(nil) # => #<Module:0x0000000102c68f38>
279 * m.name #=> nil
280 *
281 * c = Class.new
282 * c.set_temporary_name("MyClass(with description)")
283 *
284 * c.new # => #<MyClass(with description):0x0....>
285 *
286 * c::M = m
287 * c::M.name #=> "MyClass(with description)::M"
288 *
289 * # Assigning to a constant replaces the name with a permanent one
290 * C = c
291 *
292 * C.name #=> "C"
293 * C::M.name #=> "C::M"
294 * c.new # => #<C:0x0....>
295 */
296
297VALUE
298rb_mod_set_temporary_name(VALUE mod, VALUE name)
299{
300 // We don't allow setting the name if the classpath is already permanent:
301 if (RCLASS_PERMANENT_CLASSPATH_P(mod)) {
302 rb_raise(rb_eRuntimeError, "can't change permanent name");
303 }
304
305 if (NIL_P(name)) {
306 // Set the temporary classpath to NULL (anonymous):
307 RB_VM_LOCKING() {
308 set_sub_temporary_name(mod, 0);
309 }
310 }
311 else {
312 // Ensure the name is a string:
313 StringValue(name);
314
315 if (RSTRING_LEN(name) == 0) {
316 rb_raise(rb_eArgError, "empty class/module name");
317 }
318
319 if (is_constant_path(name)) {
320 rb_raise(rb_eArgError, "the temporary name must not be a constant path to avoid confusion");
321 }
322
323 name = rb_str_new_frozen(name);
324 RB_OBJ_SET_SHAREABLE(name);
325
326 // Set the temporary classpath to the given name:
327 RB_VM_LOCKING() {
328 set_sub_temporary_name(mod, name);
329 }
330 }
331
332 return mod;
333}
334
335static VALUE
336make_temporary_path(VALUE obj, VALUE klass)
337{
338 VALUE path;
339 switch (klass) {
340 case Qnil:
341 path = rb_sprintf("#<Class:%p>", (void*)obj);
342 break;
343 case Qfalse:
344 path = rb_sprintf("#<Module:%p>", (void*)obj);
345 break;
346 default:
347 path = rb_sprintf("#<%"PRIsVALUE":%p>", klass, (void*)obj);
348 break;
349 }
350 OBJ_FREEZE(path);
351 return path;
352}
353
354typedef VALUE (*fallback_func)(VALUE obj, VALUE name);
355
356static VALUE
357rb_tmp_class_path(VALUE klass, bool *permanent, fallback_func fallback)
358{
359 VALUE path = classname(klass, permanent);
360
361 if (!NIL_P(path)) {
362 return path;
363 }
364
365 if (RB_TYPE_P(klass, T_MODULE)) {
366 if (rb_obj_class(klass) == rb_cModule) {
367 path = Qfalse;
368 }
369 else {
370 bool perm;
371 path = rb_tmp_class_path(RBASIC(klass)->klass, &perm, fallback);
372 }
373 }
374
375 *permanent = false;
376 return fallback(klass, path);
377}
378
379VALUE
381{
382 bool permanent;
383 VALUE path = rb_tmp_class_path(klass, &permanent, make_temporary_path);
384 if (!NIL_P(path)) path = rb_str_dup(path);
385 return path;
386}
387
388VALUE
390{
391 return rb_mod_name(klass);
392}
393
394static VALUE
395no_fallback(VALUE obj, VALUE name)
396{
397 return name;
398}
399
400VALUE
401rb_search_class_path(VALUE klass)
402{
403 bool permanent;
404 return rb_tmp_class_path(klass, &permanent, no_fallback);
405}
406
407static VALUE
408build_const_pathname(VALUE head, VALUE tail)
409{
410 VALUE path = rb_str_dup(head);
411 rb_str_cat2(path, "::");
412 rb_str_append(path, tail);
413 return rb_fstring(path);
414}
415
416static VALUE
417build_const_path(VALUE head, ID tail)
418{
419 return build_const_pathname(head, rb_id2str(tail));
420}
421
422void
424{
425 bool permanent = true;
426
427 VALUE str;
428 if (under == rb_cObject) {
429 str = rb_str_new_frozen(name);
430 }
431 else {
432 str = rb_tmp_class_path(under, &permanent, make_temporary_path);
433 str = build_const_pathname(str, name);
434 }
435
436 RB_OBJ_SET_SHAREABLE(str);
437 RCLASS_SET_CLASSPATH(klass, str, permanent);
438}
439
440void
441rb_set_class_path(VALUE klass, VALUE under, const char *name)
442{
443 VALUE str = rb_str_new2(name);
444 OBJ_FREEZE(str);
445 rb_set_class_path_string(klass, under, str);
446}
447
448VALUE
450{
451 rb_encoding *enc = rb_enc_get(pathname);
452 const char *pbeg, *pend, *p, *path = RSTRING_PTR(pathname);
453 ID id;
454 VALUE c = rb_cObject;
455
456 if (!rb_enc_asciicompat(enc)) {
457 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
458 }
459 pbeg = p = path;
460 pend = path + RSTRING_LEN(pathname);
461 if (path == pend || path[0] == '#') {
462 rb_raise(rb_eArgError, "can't retrieve anonymous class %"PRIsVALUE,
463 QUOTE(pathname));
464 }
465 while (p < pend) {
466 while (p < pend && *p != ':') p++;
467 id = rb_check_id_cstr(pbeg, p-pbeg, enc);
468 if (p < pend && p[0] == ':') {
469 if ((size_t)(pend - p) < 2 || p[1] != ':') goto undefined_class;
470 p += 2;
471 pbeg = p;
472 }
473 if (!id) {
474 goto undefined_class;
475 }
476 c = rb_const_search(c, id, TRUE, FALSE, FALSE);
477 if (UNDEF_P(c)) goto undefined_class;
478 if (!rb_namespace_p(c)) {
479 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
480 pathname);
481 }
482 }
483 RB_GC_GUARD(pathname);
484
485 return c;
486
487 undefined_class:
488 rb_raise(rb_eArgError, "undefined class/module % "PRIsVALUE,
489 rb_str_subseq(pathname, 0, p-path));
491}
492
493VALUE
494rb_path2class(const char *path)
495{
496 return rb_path_to_class(rb_str_new_cstr(path));
497}
498
499VALUE
501{
502 return rb_class_path(rb_class_real(klass));
503}
504
505const char *
507{
508 bool permanent;
509 VALUE path = rb_tmp_class_path(rb_class_real(klass), &permanent, make_temporary_path);
510 if (NIL_P(path)) return NULL;
511 return RSTRING_PTR(path);
512}
513
514const char *
516{
517 return rb_class2name(CLASS_OF(obj));
518}
519
520struct trace_var {
521 int removed;
522 void (*func)(VALUE arg, VALUE val);
523 VALUE data;
524 struct trace_var *next;
525};
526
528 int counter;
529 int block_trace;
530 VALUE *data;
531 rb_gvar_getter_t *getter;
532 rb_gvar_setter_t *setter;
533 rb_gvar_marker_t *marker;
534 rb_gvar_compact_t *compactor;
535 struct trace_var *trace;
536 bool box_ready;
537};
538
540 struct rb_global_variable *var;
541 ID id;
542 bool ractor_local;
543};
544
545static void
546free_global_variable(struct rb_global_variable *var)
547{
548 RUBY_ASSERT(var->counter == 0);
549
550 struct trace_var *trace = var->trace;
551 while (trace) {
552 struct trace_var *next = trace->next;
553 xfree(trace);
554 trace = next;
555 }
556 xfree(var);
557}
558
559static enum rb_id_table_iterator_result
560free_global_entry_i(VALUE val, void *arg)
561{
562 struct rb_global_entry *entry = (struct rb_global_entry *)val;
563 entry->var->counter--;
564 if (entry->var->counter == 0) {
565 free_global_variable(entry->var);
566 }
567 ruby_xfree(entry);
568 return ID_TABLE_DELETE;
569}
570
571void
572rb_free_rb_global_tbl(void)
573{
574 rb_id_table_foreach_values(rb_global_tbl, free_global_entry_i, 0);
575 rb_id_table_free(rb_global_tbl);
576}
577
578void
579rb_free_generic_fields_tbl_(void)
580{
581 st_free_table(generic_fields_tbl_);
582}
583
584static struct rb_global_entry*
585rb_find_global_entry(ID id)
586{
587 struct rb_global_entry *entry;
588 VALUE data;
589
590 RB_VM_LOCKING() {
591 if (!rb_id_table_lookup(rb_global_tbl, id, &data)) {
592 entry = NULL;
593 }
594 else {
595 entry = (struct rb_global_entry *)data;
596 RUBY_ASSERT(entry != NULL);
597 }
598 }
599
600 if (UNLIKELY(!rb_ractor_main_p()) && (!entry || !entry->ractor_local)) {
601 rb_raise(rb_eRactorIsolationError, "can not access global variable %s from non-main Ractor", rb_id2name(id));
602 }
603
604 return entry;
605}
606
607void
608rb_gvar_ractor_local(const char *name)
609{
610 struct rb_global_entry *entry = rb_find_global_entry(rb_intern(name));
611 entry->ractor_local = true;
612}
613
614void
615rb_gvar_box_ready(const char *name)
616{
617 struct rb_global_entry *entry = rb_find_global_entry(rb_intern(name));
618 entry->var->box_ready = true;
619}
620
621static void
622rb_gvar_undef_compactor(void *var)
623{
624}
625
626static struct rb_global_entry*
628{
629 struct rb_global_entry *entry;
630 RB_VM_LOCKING() {
631 entry = rb_find_global_entry(id);
632 if (!entry) {
633 struct rb_global_variable *var;
634 entry = ALLOC(struct rb_global_entry);
635 var = ALLOC(struct rb_global_variable);
636 entry->id = id;
637 entry->var = var;
638 entry->ractor_local = false;
639 var->counter = 1;
640 var->data = 0;
641 var->getter = rb_gvar_undef_getter;
642 var->setter = rb_gvar_undef_setter;
643 var->marker = rb_gvar_undef_marker;
644 var->compactor = rb_gvar_undef_compactor;
645
646 var->block_trace = 0;
647 var->trace = 0;
648 var->box_ready = false;
649 rb_id_table_insert(rb_global_tbl, id, (VALUE)entry);
650 }
651 }
652 return entry;
653}
654
655VALUE
657{
658 rb_warning("global variable '%"PRIsVALUE"' not initialized", QUOTE_ID(id));
659
660 return Qnil;
661}
662
663static void
664rb_gvar_val_compactor(void *_var)
665{
666 struct rb_global_variable *var = (struct rb_global_variable *)_var;
667
668 VALUE obj = (VALUE)var->data;
669
670 if (obj) {
671 VALUE new = rb_gc_location(obj);
672 if (new != obj) {
673 var->data = (void*)new;
674 }
675 }
676}
677
678void
680{
681 struct rb_global_variable *var = rb_global_entry(id)->var;
682 var->getter = rb_gvar_val_getter;
683 var->setter = rb_gvar_val_setter;
684 var->marker = rb_gvar_val_marker;
685 var->compactor = rb_gvar_val_compactor;
686
687 var->data = (void*)val;
688}
689
690void
692{
693}
694
695VALUE
696rb_gvar_val_getter(ID id, VALUE *data)
697{
698 return (VALUE)data;
699}
700
701void
703{
704 struct rb_global_variable *var = rb_global_entry(id)->var;
705 var->data = (void*)val;
706}
707
708void
710{
711 VALUE data = (VALUE)var;
712 if (data) rb_gc_mark_movable(data);
713}
714
715VALUE
717{
718 if (!var) return Qnil;
719 return *var;
720}
721
722void
723rb_gvar_var_setter(VALUE val, ID id, VALUE *data)
724{
725 *data = val;
726}
727
728void
730{
731 if (var) rb_gc_mark_maybe(*var);
732}
733
734void
736{
737 rb_name_error(id, "%"PRIsVALUE" is a read-only variable", QUOTE_ID(id));
738}
739
740static enum rb_id_table_iterator_result
741mark_global_entry(VALUE v, void *ignored)
742{
743 struct rb_global_entry *entry = (struct rb_global_entry *)v;
744 struct trace_var *trace;
745 struct rb_global_variable *var = entry->var;
746
747 (*var->marker)(var->data);
748 trace = var->trace;
749 while (trace) {
750 if (trace->data) rb_gc_mark_maybe(trace->data);
751 trace = trace->next;
752 }
753 return ID_TABLE_CONTINUE;
754}
755
756#define gc_mark_table(task) \
757 if (rb_global_tbl) { rb_id_table_foreach_values(rb_global_tbl, task##_global_entry, 0); }
758
759void
760rb_gc_mark_global_tbl(void)
761{
762 gc_mark_table(mark);
763}
764
765static enum rb_id_table_iterator_result
766update_global_entry(VALUE v, void *ignored)
767{
768 struct rb_global_entry *entry = (struct rb_global_entry *)v;
769 struct rb_global_variable *var = entry->var;
770
771 (*var->compactor)(var);
772 return ID_TABLE_CONTINUE;
773}
774
775void
776rb_gc_update_global_tbl(void)
777{
778 gc_mark_table(update);
779}
780
781static ID
782global_id(const char *name)
783{
784 ID id;
785
786 if (name[0] == '$') id = rb_intern(name);
787 else {
788 size_t len = strlen(name);
789 VALUE vbuf = 0;
790 char *buf = ALLOCV_N(char, vbuf, len+1);
791 buf[0] = '$';
792 memcpy(buf+1, name, len);
793 id = rb_intern2(buf, len+1);
794 ALLOCV_END(vbuf);
795 }
796 return id;
797}
798
799static ID
800find_global_id(const char *name)
801{
802 ID id;
803 size_t len = strlen(name);
804
805 if (name[0] == '$') {
806 id = rb_check_id_cstr(name, len, NULL);
807 }
808 else {
809 VALUE vbuf = 0;
810 char *buf = ALLOCV_N(char, vbuf, len+1);
811 buf[0] = '$';
812 memcpy(buf+1, name, len);
813 id = rb_check_id_cstr(buf, len+1, NULL);
814 ALLOCV_END(vbuf);
815 }
816
817 return id;
818}
819
820void
822 const char *name,
823 VALUE *var,
824 rb_gvar_getter_t *getter,
825 rb_gvar_setter_t *setter)
826{
827 volatile VALUE tmp = var ? *var : Qnil;
828 ID id = global_id(name);
829 struct rb_global_variable *gvar = rb_global_entry(id)->var;
830
831 gvar->data = (void*)var;
832 gvar->getter = getter ? (rb_gvar_getter_t *)getter : rb_gvar_var_getter;
833 gvar->setter = setter ? (rb_gvar_setter_t *)setter : rb_gvar_var_setter;
834 gvar->marker = rb_gvar_var_marker;
835
836 RB_GC_GUARD(tmp);
837}
838
839void
840rb_define_variable(const char *name, VALUE *var)
841{
842 rb_define_hooked_variable(name, var, 0, 0);
843}
844
845void
846rb_define_readonly_variable(const char *name, const VALUE *var)
847{
849}
850
851void
853 const char *name,
854 rb_gvar_getter_t *getter,
855 rb_gvar_setter_t *setter)
856{
857 if (!getter) getter = rb_gvar_val_getter;
858 if (!setter) setter = rb_gvar_readonly_setter;
859 rb_define_hooked_variable(name, 0, getter, setter);
860}
861
862static void
863rb_trace_eval(VALUE cmd, VALUE val)
864{
865 rb_eval_cmd_call_kw(cmd, 1, &val, RB_NO_KEYWORDS);
866}
867
868VALUE
869rb_f_trace_var(int argc, const VALUE *argv)
870{
871 VALUE var, cmd;
872 struct rb_global_entry *entry;
873 struct trace_var *trace;
874
875 if (rb_scan_args(argc, argv, "11", &var, &cmd) == 1) {
876 cmd = rb_block_proc();
877 }
878 if (NIL_P(cmd)) {
879 return rb_f_untrace_var(argc, argv);
880 }
881 entry = rb_global_entry(rb_to_id(var));
882 trace = ALLOC(struct trace_var);
883 trace->next = entry->var->trace;
884 trace->func = rb_trace_eval;
885 trace->data = cmd;
886 trace->removed = 0;
887 entry->var->trace = trace;
888
889 return Qnil;
890}
891
892static void
893remove_trace(struct rb_global_variable *var)
894{
895 struct trace_var *trace = var->trace;
896 struct trace_var t;
897 struct trace_var *next;
898
899 t.next = trace;
900 trace = &t;
901 while (trace->next) {
902 next = trace->next;
903 if (next->removed) {
904 trace->next = next->next;
905 xfree(next);
906 }
907 else {
908 trace = next;
909 }
910 }
911 var->trace = t.next;
912}
913
914VALUE
915rb_f_untrace_var(int argc, const VALUE *argv)
916{
917 VALUE var, cmd;
918 ID id;
919 struct rb_global_entry *entry;
920 struct trace_var *trace;
921
922 rb_scan_args(argc, argv, "11", &var, &cmd);
923 id = rb_check_id(&var);
924 if (!id) {
925 rb_name_error_str(var, "undefined global variable %"PRIsVALUE"", QUOTE(var));
926 }
927 if ((entry = rb_find_global_entry(id)) == NULL) {
928 rb_name_error(id, "undefined global variable %"PRIsVALUE"", QUOTE_ID(id));
929 }
930
931 trace = entry->var->trace;
932 if (NIL_P(cmd)) {
933 VALUE ary = rb_ary_new();
934
935 while (trace) {
936 struct trace_var *next = trace->next;
937 rb_ary_push(ary, (VALUE)trace->data);
938 trace->removed = 1;
939 trace = next;
940 }
941
942 if (!entry->var->block_trace) remove_trace(entry->var);
943 return ary;
944 }
945 else {
946 while (trace) {
947 if (trace->data == cmd) {
948 trace->removed = 1;
949 if (!entry->var->block_trace) remove_trace(entry->var);
950 return rb_ary_new3(1, cmd);
951 }
952 trace = trace->next;
953 }
954 }
955 return Qnil;
956}
957
959 struct trace_var *trace;
960 VALUE val;
961};
962
963static VALUE
964trace_ev(VALUE v)
965{
966 struct trace_data *data = (void *)v;
967 struct trace_var *trace = data->trace;
968
969 while (trace) {
970 (*trace->func)(trace->data, data->val);
971 trace = trace->next;
972 }
973
974 return Qnil;
975}
976
977static VALUE
978trace_en(VALUE v)
979{
980 struct rb_global_variable *var = (void *)v;
981 var->block_trace = 0;
982 remove_trace(var);
983 return Qnil; /* not reached */
984}
985
986static VALUE
987rb_gvar_set_entry(struct rb_global_entry *entry, VALUE val)
988{
989 struct trace_data trace;
990 struct rb_global_variable *var = entry->var;
991
992 (*var->setter)(val, entry->id, var->data);
993
994 if (var->trace && !var->block_trace) {
995 var->block_trace = 1;
996 trace.trace = var->trace;
997 trace.val = val;
998 rb_ensure(trace_ev, (VALUE)&trace, trace_en, (VALUE)var);
999 }
1000 return val;
1001}
1002
1003#define USE_BOX_GVAR_TBL(ns,entry) \
1004 (BOX_USER_P(ns) && \
1005 (!entry || !entry->var->box_ready || entry->var->setter != rb_gvar_readonly_setter))
1006
1007VALUE
1008rb_gvar_set(ID id, VALUE val)
1009{
1010 VALUE retval;
1011 struct rb_global_entry *entry;
1012 const rb_box_t *box = rb_current_box();
1013 bool use_box_tbl = false;
1014
1015 RB_VM_LOCKING() {
1016 entry = rb_global_entry(id);
1017
1018 if (USE_BOX_GVAR_TBL(box, entry)) {
1019 use_box_tbl = true;
1020 rb_hash_aset(box->gvar_tbl, rb_id2sym(entry->id), val);
1021 retval = val;
1022 // TODO: think about trace
1023 }
1024 }
1025
1026 if (!use_box_tbl) {
1027 retval = rb_gvar_set_entry(entry, val);
1028 }
1029 return retval;
1030}
1031
1032VALUE
1033rb_gv_set(const char *name, VALUE val)
1034{
1035 return rb_gvar_set(global_id(name), val);
1036}
1037
1038VALUE
1039rb_gvar_get(ID id)
1040{
1041 VALUE retval, gvars, key;
1042 const rb_box_t *box = rb_current_box();
1043 bool use_box_tbl = false;
1044 struct rb_global_entry *entry;
1045 struct rb_global_variable *var;
1046 // TODO: use lock-free rb_id_table when it's available for use (doesn't yet exist)
1047 RB_VM_LOCKING() {
1048 entry = rb_global_entry(id);
1049 var = entry->var;
1050
1051 if (USE_BOX_GVAR_TBL(box, entry)) {
1052 use_box_tbl = true;
1053 gvars = box->gvar_tbl;
1054 key = rb_id2sym(entry->id);
1055 if (RTEST(rb_hash_has_key(gvars, key))) { // this gvar is already cached
1056 retval = rb_hash_aref(gvars, key);
1057 }
1058 else {
1059 RB_VM_UNLOCK();
1060 {
1061 retval = (*var->getter)(entry->id, var->data);
1062 if (rb_obj_respond_to(retval, rb_intern("clone"), 1)) {
1063 retval = rb_funcall(retval, rb_intern("clone"), 0);
1064 }
1065 }
1066 RB_VM_LOCK();
1067 rb_hash_aset(gvars, key, retval);
1068 }
1069 }
1070 }
1071 if (!use_box_tbl) {
1072 retval = (*var->getter)(entry->id, var->data);
1073 }
1074 return retval;
1075}
1076
1077VALUE
1078rb_gv_get(const char *name)
1079{
1080 ID id = find_global_id(name);
1081
1082 if (!id) {
1083 rb_warning("global variable '%s' not initialized", name);
1084 return Qnil;
1085 }
1086
1087 return rb_gvar_get(id);
1088}
1089
1090VALUE
1091rb_gvar_defined(ID id)
1092{
1093 struct rb_global_entry *entry = rb_global_entry(id);
1094 return RBOOL(entry->var->getter != rb_gvar_undef_getter);
1095}
1096
1098rb_gvar_getter_function_of(ID id)
1099{
1100 const struct rb_global_entry *entry = rb_global_entry(id);
1101 return entry->var->getter;
1102}
1103
1105rb_gvar_setter_function_of(ID id)
1106{
1107 const struct rb_global_entry *entry = rb_global_entry(id);
1108 return entry->var->setter;
1109}
1110
1111static enum rb_id_table_iterator_result
1112gvar_i(ID key, VALUE val, void *a)
1113{
1114 VALUE ary = (VALUE)a;
1115 rb_ary_push(ary, ID2SYM(key));
1116 return ID_TABLE_CONTINUE;
1117}
1118
1119VALUE
1121{
1122 VALUE ary = rb_ary_new();
1123 VALUE sym, backref = rb_backref_get();
1124
1125 if (!rb_ractor_main_p()) {
1126 rb_raise(rb_eRactorIsolationError, "can not access global variables from non-main Ractors");
1127 }
1128 /* gvar access (get/set) in boxes creates gvar entries globally */
1129
1130 rb_id_table_foreach(rb_global_tbl, gvar_i, (void *)ary);
1131 if (!NIL_P(backref)) {
1132 char buf[2];
1133 int i, nmatch = rb_match_count(backref);
1134 buf[0] = '$';
1135 for (i = 1; i <= nmatch; ++i) {
1136 if (!RTEST(rb_reg_nth_defined(i, backref))) continue;
1137 if (i < 10) {
1138 /* probably reused, make static ID */
1139 buf[1] = (char)(i + '0');
1140 sym = ID2SYM(rb_intern2(buf, 2));
1141 }
1142 else {
1143 /* dynamic symbol */
1144 sym = rb_str_intern(rb_sprintf("$%d", i));
1145 }
1146 rb_ary_push(ary, sym);
1147 }
1148 }
1149 return ary;
1150}
1151
1152void
1154{
1155 struct rb_global_entry *entry1 = NULL, *entry2;
1156 VALUE data1;
1157 struct rb_id_table *gtbl = rb_global_tbl;
1158
1159 if (!rb_ractor_main_p()) {
1160 rb_raise(rb_eRactorIsolationError, "can not access global variables from non-main Ractors");
1161 }
1162
1163 RB_VM_LOCKING() {
1164 entry2 = rb_global_entry(name2);
1165 if (!rb_id_table_lookup(gtbl, name1, &data1)) {
1166 entry1 = ZALLOC(struct rb_global_entry);
1167 entry1->id = name1;
1168 rb_id_table_insert(gtbl, name1, (VALUE)entry1);
1169 }
1170 else if ((entry1 = (struct rb_global_entry *)data1)->var != entry2->var) {
1171 struct rb_global_variable *var = entry1->var;
1172 if (var->block_trace) {
1173 RB_VM_UNLOCK();
1174 rb_raise(rb_eRuntimeError, "can't alias in tracer");
1175 }
1176 var->counter--;
1177 if (var->counter == 0) {
1178 free_global_variable(var);
1179 }
1180 }
1181 if (entry1->var != entry2->var) {
1182 entry2->var->counter++;
1183 entry1->var = entry2->var;
1184 }
1185 }
1186}
1187
1188static void
1189IVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(ID id)
1190{
1191 if (UNLIKELY(!rb_ractor_main_p())) {
1192 if (rb_is_instance_id(id)) { // check only normal ivars
1193 rb_raise(rb_eRactorIsolationError, "can not set instance variables of classes/modules by non-main Ractors");
1194 }
1195 }
1196}
1197
1198#define CVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR() \
1199 if (UNLIKELY(!rb_ractor_main_p())) { \
1200 rb_raise(rb_eRactorIsolationError, "can not access class variables from non-main Ractors"); \
1201 }
1202
1203static inline void
1204ivar_ractor_check(VALUE obj, ID id)
1205{
1206 if (LIKELY(rb_is_instance_id(id)) /* not internal ID */ &&
1207 !RB_OBJ_FROZEN_RAW(obj) &&
1208 UNLIKELY(!rb_ractor_main_p()) &&
1209 UNLIKELY(rb_ractor_shareable_p(obj))) {
1210
1211 rb_raise(rb_eRactorIsolationError, "can not access instance variables of shareable objects from non-main Ractors");
1212 }
1213}
1214
1215static inline struct st_table *
1216generic_fields_tbl_no_ractor_check(void)
1217{
1218 ASSERT_vm_locking();
1219
1220 return generic_fields_tbl_;
1221}
1222
1223struct st_table *
1224rb_generic_fields_tbl_get(void)
1225{
1226 return generic_fields_tbl_;
1227}
1228
1229void
1230rb_mark_generic_ivar(VALUE obj)
1231{
1232 VALUE data;
1233 // Bypass ASSERT_vm_locking() check because marking may happen concurrently with mmtk
1234 if (st_lookup(generic_fields_tbl_, (st_data_t)obj, (st_data_t *)&data)) {
1235 rb_gc_mark_movable(data);
1236 }
1237}
1238
1239VALUE
1240rb_obj_fields_generic_uncached(VALUE obj)
1241{
1242 VALUE fields_obj = 0;
1243 RB_VM_LOCKING() {
1244 if (!st_lookup(generic_fields_tbl_, (st_data_t)obj, (st_data_t *)&fields_obj)) {
1245 rb_bug("Object is missing entry in generic_fields_tbl");
1246 }
1247 }
1248 return fields_obj;
1249}
1250
1251VALUE
1252rb_obj_fields(VALUE obj, ID field_name)
1253{
1255 ivar_ractor_check(obj, field_name);
1256
1257 VALUE fields_obj = 0;
1258 if (rb_shape_obj_has_fields(obj)) {
1259 switch (BUILTIN_TYPE(obj)) {
1260 case T_DATA:
1261 if (LIKELY(RTYPEDDATA_P(obj))) {
1262 fields_obj = RTYPEDDATA(obj)->fields_obj;
1263 break;
1264 }
1265 goto generic_fields;
1266 case T_STRUCT:
1267 if (LIKELY(!FL_TEST_RAW(obj, RSTRUCT_GEN_FIELDS))) {
1268 fields_obj = RSTRUCT_FIELDS_OBJ(obj);
1269 break;
1270 }
1271 goto generic_fields;
1272 default:
1273 generic_fields:
1274 {
1275 rb_execution_context_t *ec = GET_EC();
1276 if (ec->gen_fields_cache.obj == obj && !UNDEF_P(ec->gen_fields_cache.fields_obj) && rb_imemo_fields_owner(ec->gen_fields_cache.fields_obj) == obj) {
1277 fields_obj = ec->gen_fields_cache.fields_obj;
1278 RUBY_ASSERT(fields_obj == rb_obj_fields_generic_uncached(obj));
1279 }
1280 else {
1281 fields_obj = rb_obj_fields_generic_uncached(obj);
1282 ec->gen_fields_cache.fields_obj = fields_obj;
1283 ec->gen_fields_cache.obj = obj;
1284 }
1285 }
1286 }
1287 }
1288 return fields_obj;
1289}
1290
1291void
1293{
1294 if (rb_obj_gen_fields_p(obj)) {
1295 st_data_t key = (st_data_t)obj, value;
1296 switch (BUILTIN_TYPE(obj)) {
1297 case T_DATA:
1298 if (LIKELY(RTYPEDDATA_P(obj))) {
1299 RB_OBJ_WRITE(obj, &RTYPEDDATA(obj)->fields_obj, 0);
1300 break;
1301 }
1302 goto generic_fields;
1303 case T_STRUCT:
1304 if (LIKELY(!FL_TEST_RAW(obj, RSTRUCT_GEN_FIELDS))) {
1305 RSTRUCT_SET_FIELDS_OBJ(obj, 0);
1306 break;
1307 }
1308 goto generic_fields;
1309 default:
1310 generic_fields:
1311 {
1312 // Other EC may have stale caches, so fields_obj should be
1313 // invalidated and the GC will replace with Qundef
1314 rb_execution_context_t *ec = GET_EC();
1315 if (ec->gen_fields_cache.obj == obj) {
1316 ec->gen_fields_cache.obj = Qundef;
1317 ec->gen_fields_cache.fields_obj = Qundef;
1318 }
1319 RB_VM_LOCKING() {
1320 if (!st_delete(generic_fields_tbl_no_ractor_check(), &key, &value)) {
1321 rb_bug("Object is missing entry in generic_fields_tbl");
1322 }
1323 }
1324 }
1325 }
1326 RBASIC_SET_SHAPE_ID(obj, ROOT_SHAPE_ID);
1327 }
1328}
1329
1330static void
1331rb_obj_set_fields(VALUE obj, VALUE fields_obj, ID field_name, VALUE original_fields_obj)
1332{
1333 ivar_ractor_check(obj, field_name);
1334
1335 if (!fields_obj) {
1336 RUBY_ASSERT(original_fields_obj);
1338 rb_imemo_fields_clear(original_fields_obj);
1339 return;
1340 }
1341
1342 RUBY_ASSERT(IMEMO_TYPE_P(fields_obj, imemo_fields));
1343 RUBY_ASSERT(!original_fields_obj || IMEMO_TYPE_P(original_fields_obj, imemo_fields));
1344
1345 if (fields_obj != original_fields_obj) {
1346 switch (BUILTIN_TYPE(obj)) {
1347 case T_DATA:
1348 if (LIKELY(RTYPEDDATA_P(obj))) {
1349 RB_OBJ_WRITE(obj, &RTYPEDDATA(obj)->fields_obj, fields_obj);
1350 break;
1351 }
1352 goto generic_fields;
1353 case T_STRUCT:
1354 if (LIKELY(!FL_TEST_RAW(obj, RSTRUCT_GEN_FIELDS))) {
1355 RSTRUCT_SET_FIELDS_OBJ(obj, fields_obj);
1356 break;
1357 }
1358 goto generic_fields;
1359 default:
1360 generic_fields:
1361 {
1362 RB_VM_LOCKING() {
1363 st_insert(generic_fields_tbl_, (st_data_t)obj, (st_data_t)fields_obj);
1364 }
1365 RB_OBJ_WRITTEN(obj, original_fields_obj, fields_obj);
1366
1367 rb_execution_context_t *ec = GET_EC();
1368 if (ec->gen_fields_cache.fields_obj != fields_obj) {
1369 ec->gen_fields_cache.obj = obj;
1370 ec->gen_fields_cache.fields_obj = fields_obj;
1371 }
1372 }
1373 }
1374
1375 if (original_fields_obj) {
1376 // Clear root shape to avoid triggering cleanup such as free_object_id.
1377 rb_imemo_fields_clear(original_fields_obj);
1378 }
1379 }
1380
1381 RBASIC_SET_SHAPE_ID(obj, RBASIC_SHAPE_ID(fields_obj));
1382}
1383
1384void
1385rb_obj_replace_fields(VALUE obj, VALUE fields_obj)
1386{
1387 RB_VM_LOCKING() {
1388 VALUE original_fields_obj = rb_obj_fields_no_ractor_check(obj);
1389 rb_obj_set_fields(obj, fields_obj, 0, original_fields_obj);
1390 }
1391}
1392
1393VALUE
1394rb_obj_field_get(VALUE obj, shape_id_t target_shape_id)
1395{
1397 RUBY_ASSERT(RSHAPE_TYPE_P(target_shape_id, SHAPE_IVAR) || RSHAPE_TYPE_P(target_shape_id, SHAPE_OBJ_ID));
1398
1399 VALUE fields_obj;
1400
1401 switch (BUILTIN_TYPE(obj)) {
1402 case T_CLASS:
1403 case T_MODULE:
1404 fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
1405 break;
1406 case T_OBJECT:
1407 fields_obj = obj;
1408 break;
1409 case T_IMEMO:
1410 RUBY_ASSERT(IMEMO_TYPE_P(obj, imemo_fields));
1411 fields_obj = obj;
1412 break;
1413 default:
1414 fields_obj = rb_obj_fields(obj, RSHAPE_EDGE_NAME(target_shape_id));
1415 break;
1416 }
1417
1418 if (UNLIKELY(rb_shape_too_complex_p(target_shape_id))) {
1419 st_table *fields_hash = rb_imemo_fields_complex_tbl(fields_obj);
1420 VALUE value = Qundef;
1421 st_lookup(fields_hash, RSHAPE_EDGE_NAME(target_shape_id), &value);
1422 RUBY_ASSERT(!UNDEF_P(value));
1423 return value;
1424 }
1425
1426 attr_index_t index = RSHAPE_INDEX(target_shape_id);
1427 return rb_imemo_fields_ptr(fields_obj)[index];
1428}
1429
1430VALUE
1431rb_ivar_lookup(VALUE obj, ID id, VALUE undef)
1432{
1433 if (SPECIAL_CONST_P(obj)) return undef;
1434
1435 VALUE fields_obj;
1436
1437 switch (BUILTIN_TYPE(obj)) {
1438 case T_CLASS:
1439 case T_MODULE:
1440 {
1441 VALUE val = rb_ivar_lookup(RCLASS_WRITABLE_FIELDS_OBJ(obj), id, undef);
1442 if (val != undef &&
1443 rb_is_instance_id(id) &&
1444 UNLIKELY(!rb_ractor_main_p()) &&
1445 !rb_ractor_shareable_p(val)) {
1446 rb_raise(rb_eRactorIsolationError,
1447 "can not get unshareable values from instance variables of classes/modules from non-main Ractors");
1448 }
1449 return val;
1450 }
1451 case T_IMEMO:
1452 // Handled like T_OBJECT
1453 RUBY_ASSERT(IMEMO_TYPE_P(obj, imemo_fields));
1454 fields_obj = obj;
1455 break;
1456 case T_OBJECT:
1457 fields_obj = obj;
1458 break;
1459 default:
1460 fields_obj = rb_obj_fields(obj, id);
1461 break;
1462 }
1463
1464 if (!fields_obj) {
1465 return undef;
1466 }
1467
1468 shape_id_t shape_id = RBASIC_SHAPE_ID(fields_obj);
1469
1470 if (UNLIKELY(rb_shape_too_complex_p(shape_id))) {
1471 st_table *iv_table = rb_imemo_fields_complex_tbl(fields_obj);
1472 VALUE val;
1473 if (rb_st_lookup(iv_table, (st_data_t)id, (st_data_t *)&val)) {
1474 return val;
1475 }
1476 return undef;
1477 }
1478
1479 attr_index_t index = 0;
1480 if (rb_shape_get_iv_index(shape_id, id, &index)) {
1481 return rb_imemo_fields_ptr(fields_obj)[index];
1482 }
1483
1484 return undef;
1485}
1486
1487VALUE
1489{
1490 VALUE iv = rb_ivar_lookup(obj, id, Qnil);
1491 RB_DEBUG_COUNTER_INC(ivar_get_base);
1492 return iv;
1493}
1494
1495VALUE
1496rb_ivar_get_at(VALUE obj, attr_index_t index, ID id)
1497{
1499 // Used by JITs, but never for T_OBJECT.
1500
1501 switch (BUILTIN_TYPE(obj)) {
1502 case T_OBJECT:
1504 case T_CLASS:
1505 case T_MODULE:
1506 {
1507 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
1508 VALUE val = rb_imemo_fields_ptr(fields_obj)[index];
1509
1510 if (UNLIKELY(!rb_ractor_main_p()) && !rb_ractor_shareable_p(val)) {
1511 rb_raise(rb_eRactorIsolationError,
1512 "can not get unshareable values from instance variables of classes/modules from non-main Ractors");
1513 }
1514
1515 return val;
1516 }
1517 default:
1518 {
1519 VALUE fields_obj = rb_obj_fields(obj, id);
1520 return rb_imemo_fields_ptr(fields_obj)[index];
1521 }
1522 }
1523}
1524
1525VALUE
1526rb_ivar_get_at_no_ractor_check(VALUE obj, attr_index_t index)
1527{
1528 // Used by JITs, but never for T_OBJECT.
1529
1530 VALUE fields_obj;
1531 switch (BUILTIN_TYPE(obj)) {
1532 case T_OBJECT:
1534 case T_CLASS:
1535 case T_MODULE:
1536 fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
1537 break;
1538 default:
1539 fields_obj = rb_obj_fields_no_ractor_check(obj);
1540 break;
1541 }
1542 return rb_imemo_fields_ptr(fields_obj)[index];
1543}
1544
1545VALUE
1546rb_attr_get(VALUE obj, ID id)
1547{
1548 return rb_ivar_lookup(obj, id, Qnil);
1549}
1550
1551void rb_obj_copy_fields_to_hash_table(VALUE obj, st_table *table);
1552static VALUE imemo_fields_complex_from_obj(VALUE owner, VALUE source_fields_obj, shape_id_t shape_id);
1553
1554static shape_id_t
1555obj_transition_too_complex(VALUE obj, st_table *table)
1556{
1557 RUBY_ASSERT(!rb_shape_obj_too_complex_p(obj));
1558 shape_id_t shape_id = rb_shape_transition_complex(obj);
1559
1560 switch (BUILTIN_TYPE(obj)) {
1561 case T_OBJECT:
1562 {
1563 VALUE *old_fields = NULL;
1564 if (FL_TEST_RAW(obj, ROBJECT_HEAP)) {
1565 old_fields = ROBJECT_FIELDS(obj);
1566 }
1567 else {
1568 FL_SET_RAW(obj, ROBJECT_HEAP);
1569 }
1570 RBASIC_SET_SHAPE_ID(obj, shape_id);
1571 ROBJECT_SET_FIELDS_HASH(obj, table);
1572 if (old_fields) {
1573 xfree(old_fields);
1574 }
1575 }
1576 break;
1577 case T_CLASS:
1578 case T_MODULE:
1579 case T_IMEMO:
1581 break;
1582 default:
1583 {
1584 VALUE fields_obj = rb_imemo_fields_new_complex_tbl(obj, table, RB_OBJ_SHAREABLE_P(obj));
1585 RBASIC_SET_SHAPE_ID(fields_obj, shape_id);
1586 rb_obj_replace_fields(obj, fields_obj);
1587 }
1588 }
1589
1590 return shape_id;
1591}
1592
1593// Copy all object fields, including ivars and internal object_id, etc
1594static shape_id_t
1595rb_evict_fields_to_hash(VALUE obj)
1596{
1597 RUBY_ASSERT(!rb_shape_obj_too_complex_p(obj));
1598
1599 st_table *table = st_init_numtable_with_size(RSHAPE_LEN(RBASIC_SHAPE_ID(obj)));
1600 rb_obj_copy_fields_to_hash_table(obj, table);
1601 shape_id_t new_shape_id = obj_transition_too_complex(obj, table);
1602
1603 RUBY_ASSERT(rb_shape_obj_too_complex_p(obj));
1604 return new_shape_id;
1605}
1606
1607void
1608rb_evict_ivars_to_hash(VALUE obj)
1609{
1610 RUBY_ASSERT(!rb_shape_obj_too_complex_p(obj));
1611
1612 st_table *table = st_init_numtable_with_size(rb_ivar_count(obj));
1613
1614 // Evacuate all previous values from shape into id_table
1615 rb_obj_copy_ivs_to_hash_table(obj, table);
1616 obj_transition_too_complex(obj, table);
1617
1618 RUBY_ASSERT(rb_shape_obj_too_complex_p(obj));
1619}
1620
1621static VALUE
1622rb_ivar_delete(VALUE obj, ID id, VALUE undef)
1623{
1624 rb_check_frozen(obj);
1625
1626 VALUE val = undef;
1627 VALUE fields_obj;
1628 bool concurrent = false;
1629 int type = BUILTIN_TYPE(obj);
1630
1631 switch(type) {
1632 case T_CLASS:
1633 case T_MODULE:
1634 IVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(id);
1635
1636 fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
1637 if (rb_multi_ractor_p()) {
1638 concurrent = true;
1639 }
1640 break;
1641 case T_OBJECT:
1642 fields_obj = obj;
1643 break;
1644 default: {
1645 fields_obj = rb_obj_fields(obj, id);
1646 break;
1647 }
1648 }
1649
1650 if (!fields_obj) {
1651 return undef;
1652 }
1653
1654 const VALUE original_fields_obj = fields_obj;
1655 if (concurrent) {
1656 fields_obj = rb_imemo_fields_clone(fields_obj);
1657 }
1658
1659 shape_id_t old_shape_id = RBASIC_SHAPE_ID(fields_obj);
1660 shape_id_t removed_shape_id;
1661 shape_id_t next_shape_id = rb_shape_transition_remove_ivar(fields_obj, id, &removed_shape_id);
1662
1663 if (UNLIKELY(rb_shape_too_complex_p(next_shape_id))) {
1664 if (UNLIKELY(!rb_shape_too_complex_p(old_shape_id))) {
1665 if (type == T_OBJECT) {
1666 rb_evict_fields_to_hash(obj);
1667 }
1668 else {
1669 fields_obj = imemo_fields_complex_from_obj(obj, fields_obj, next_shape_id);
1670 }
1671 }
1672 st_data_t key = id;
1673 if (!st_delete(rb_imemo_fields_complex_tbl(fields_obj), &key, (st_data_t *)&val)) {
1674 val = undef;
1675 }
1676 }
1677 else {
1678 if (next_shape_id == old_shape_id) {
1679 return undef;
1680 }
1681
1682 RUBY_ASSERT(removed_shape_id != INVALID_SHAPE_ID);
1683 RUBY_ASSERT(RSHAPE_LEN(next_shape_id) == RSHAPE_LEN(old_shape_id) - 1);
1684
1685 VALUE *fields = rb_imemo_fields_ptr(fields_obj);
1686 attr_index_t removed_index = RSHAPE_INDEX(removed_shape_id);
1687 val = fields[removed_index];
1688
1689 attr_index_t new_fields_count = RSHAPE_LEN(next_shape_id);
1690 if (new_fields_count) {
1691 size_t trailing_fields = new_fields_count - removed_index;
1692
1693 MEMMOVE(&fields[removed_index], &fields[removed_index + 1], VALUE, trailing_fields);
1694 RBASIC_SET_SHAPE_ID(fields_obj, next_shape_id);
1695
1696 if (FL_TEST_RAW(fields_obj, OBJ_FIELD_HEAP) && rb_obj_embedded_size(new_fields_count) <= rb_gc_obj_slot_size(fields_obj)) {
1697 // Re-embed objects when instances become small enough
1698 // This is necessary because YJIT assumes that objects with the same shape
1699 // have the same embeddedness for efficiency (avoid extra checks)
1700 FL_UNSET_RAW(fields_obj, ROBJECT_HEAP);
1701 MEMCPY(rb_imemo_fields_ptr(fields_obj), fields, VALUE, new_fields_count);
1702 xfree(fields);
1703 }
1704 }
1705 else {
1706 fields_obj = 0;
1708 }
1709 }
1710
1711 RBASIC_SET_SHAPE_ID(obj, next_shape_id);
1712 if (fields_obj != original_fields_obj) {
1713 switch (type) {
1714 case T_OBJECT:
1715 break;
1716 case T_CLASS:
1717 case T_MODULE:
1718 RCLASS_WRITABLE_SET_FIELDS_OBJ(obj, fields_obj);
1719 break;
1720 default:
1721 rb_obj_set_fields(obj, fields_obj, id, original_fields_obj);
1722 break;
1723 }
1724 }
1725
1726 return val;
1727}
1728
1729VALUE
1730rb_attr_delete(VALUE obj, ID id)
1731{
1732 return rb_ivar_delete(obj, id, Qnil);
1733}
1734
1735void
1736rb_obj_init_too_complex(VALUE obj, st_table *table)
1737{
1738 // This method is meant to be called on newly allocated object.
1739 RUBY_ASSERT(!rb_shape_obj_too_complex_p(obj));
1740 RUBY_ASSERT(rb_shape_canonical_p(RBASIC_SHAPE_ID(obj)));
1741 RUBY_ASSERT(RSHAPE_LEN(RBASIC_SHAPE_ID(obj)) == 0);
1742
1743 obj_transition_too_complex(obj, table);
1744}
1745
1746static int
1747imemo_fields_complex_from_obj_i(ID key, VALUE val, st_data_t arg)
1748{
1749 VALUE fields = (VALUE)arg;
1750 st_table *table = rb_imemo_fields_complex_tbl(fields);
1751
1752 RUBY_ASSERT(!st_lookup(table, (st_data_t)key, NULL));
1753 st_add_direct(table, (st_data_t)key, (st_data_t)val);
1754 RB_OBJ_WRITTEN(fields, Qundef, val);
1755
1756 return ST_CONTINUE;
1757}
1758
1759static VALUE
1760imemo_fields_complex_from_obj(VALUE owner, VALUE source_fields_obj, shape_id_t shape_id)
1761{
1762 attr_index_t len = source_fields_obj ? RSHAPE_LEN(RBASIC_SHAPE_ID(source_fields_obj)) : 0;
1763 VALUE fields_obj = rb_imemo_fields_new_complex(owner, len + 1, RB_OBJ_SHAREABLE_P(owner));
1764
1765 rb_field_foreach(source_fields_obj, imemo_fields_complex_from_obj_i, (st_data_t)fields_obj, false);
1766 RBASIC_SET_SHAPE_ID(fields_obj, shape_id);
1767
1768 return fields_obj;
1769}
1770
1771static VALUE
1772imemo_fields_copy_capa(VALUE owner, VALUE source_fields_obj, attr_index_t new_size)
1773{
1774 VALUE fields_obj = rb_imemo_fields_new(owner, new_size, RB_OBJ_SHAREABLE_P(owner));
1775 if (source_fields_obj) {
1776 attr_index_t fields_count = RSHAPE_LEN(RBASIC_SHAPE_ID(source_fields_obj));
1777 VALUE *fields = rb_imemo_fields_ptr(fields_obj);
1778 MEMCPY(fields, rb_imemo_fields_ptr(source_fields_obj), VALUE, fields_count);
1779 RBASIC_SET_SHAPE_ID(fields_obj, RBASIC_SHAPE_ID(source_fields_obj));
1780 for (attr_index_t i = 0; i < fields_count; i++) {
1781 RB_OBJ_WRITTEN(fields_obj, Qundef, fields[i]);
1782 }
1783 }
1784 return fields_obj;
1785}
1786
1787static VALUE
1788imemo_fields_set(VALUE owner, VALUE fields_obj, shape_id_t target_shape_id, ID field_name, VALUE val, bool concurrent)
1789{
1790 const VALUE original_fields_obj = fields_obj;
1791 shape_id_t current_shape_id = fields_obj ? RBASIC_SHAPE_ID(fields_obj) : ROOT_SHAPE_ID;
1792
1793 if (UNLIKELY(rb_shape_too_complex_p(target_shape_id))) {
1794 if (rb_shape_too_complex_p(current_shape_id)) {
1795 if (concurrent) {
1796 // In multi-ractor case, we must always work on a copy because
1797 // even if the field already exist, inserting in a st_table may
1798 // cause a rebuild.
1799 fields_obj = rb_imemo_fields_clone(fields_obj);
1800 }
1801 }
1802 else {
1803 fields_obj = imemo_fields_complex_from_obj(owner, original_fields_obj, target_shape_id);
1804 current_shape_id = target_shape_id;
1805 }
1806
1807 st_table *table = rb_imemo_fields_complex_tbl(fields_obj);
1808
1809 RUBY_ASSERT(field_name);
1810 st_insert(table, (st_data_t)field_name, (st_data_t)val);
1811 RB_OBJ_WRITTEN(fields_obj, Qundef, val);
1812 RBASIC_SET_SHAPE_ID(fields_obj, target_shape_id);
1813 }
1814 else {
1815 attr_index_t index = RSHAPE_INDEX(target_shape_id);
1816 if (concurrent || index >= RSHAPE_CAPACITY(current_shape_id)) {
1817 fields_obj = imemo_fields_copy_capa(owner, original_fields_obj, RSHAPE_CAPACITY(target_shape_id));
1818 }
1819
1820 VALUE *table = rb_imemo_fields_ptr(fields_obj);
1821 RB_OBJ_WRITE(fields_obj, &table[index], val);
1822
1823 if (RSHAPE_LEN(target_shape_id) > RSHAPE_LEN(current_shape_id)) {
1824 RBASIC_SET_SHAPE_ID(fields_obj, target_shape_id);
1825 }
1826 }
1827
1828 return fields_obj;
1829}
1830
1831static attr_index_t
1832generic_field_set(VALUE obj, shape_id_t target_shape_id, ID field_name, VALUE val)
1833{
1834 if (!field_name) {
1835 field_name = RSHAPE_EDGE_NAME(target_shape_id);
1836 RUBY_ASSERT(field_name);
1837 }
1838
1839 const VALUE original_fields_obj = rb_obj_fields(obj, field_name);
1840 VALUE fields_obj = imemo_fields_set(obj, original_fields_obj, target_shape_id, field_name, val, false);
1841
1842 rb_obj_set_fields(obj, fields_obj, field_name, original_fields_obj);
1843 return rb_shape_too_complex_p(target_shape_id) ? ATTR_INDEX_NOT_SET : RSHAPE_INDEX(target_shape_id);
1844}
1845
1846static shape_id_t
1847generic_shape_ivar(VALUE obj, ID id, bool *new_ivar_out)
1848{
1849 bool new_ivar = false;
1850 shape_id_t current_shape_id = RBASIC_SHAPE_ID(obj);
1851 shape_id_t target_shape_id = current_shape_id;
1852
1853 if (!rb_shape_too_complex_p(current_shape_id)) {
1854 if (!rb_shape_find_ivar(current_shape_id, id, &target_shape_id)) {
1855 if (RSHAPE_LEN(current_shape_id) >= SHAPE_MAX_FIELDS) {
1856 rb_raise(rb_eArgError, "too many instance variables");
1857 }
1858
1859 new_ivar = true;
1860 target_shape_id = rb_shape_transition_add_ivar(obj, id);
1861 }
1862 }
1863
1864 *new_ivar_out = new_ivar;
1865 return target_shape_id;
1866}
1867
1868static attr_index_t
1869generic_ivar_set(VALUE obj, ID id, VALUE val)
1870{
1871 bool dontcare;
1872 shape_id_t target_shape_id = generic_shape_ivar(obj, id, &dontcare);
1873 return generic_field_set(obj, target_shape_id, id, val);
1874}
1875
1876void
1877rb_ensure_iv_list_size(VALUE obj, uint32_t current_len, uint32_t new_capacity)
1878{
1879 RUBY_ASSERT(!rb_shape_obj_too_complex_p(obj));
1880
1881 if (FL_TEST_RAW(obj, ROBJECT_HEAP)) {
1882 REALLOC_N(ROBJECT(obj)->as.heap.fields, VALUE, new_capacity);
1883 }
1884 else {
1885 VALUE *ptr = ROBJECT_FIELDS(obj);
1886 VALUE *newptr = ALLOC_N(VALUE, new_capacity);
1887 MEMCPY(newptr, ptr, VALUE, current_len);
1888 FL_SET_RAW(obj, ROBJECT_HEAP);
1889 ROBJECT(obj)->as.heap.fields = newptr;
1890 }
1891}
1892
1893static int
1894rb_obj_copy_ivs_to_hash_table_i(ID key, VALUE val, st_data_t arg)
1895{
1896 RUBY_ASSERT(!st_lookup((st_table *)arg, (st_data_t)key, NULL));
1897
1898 st_add_direct((st_table *)arg, (st_data_t)key, (st_data_t)val);
1899 return ST_CONTINUE;
1900}
1901
1902void
1903rb_obj_copy_ivs_to_hash_table(VALUE obj, st_table *table)
1904{
1905 rb_ivar_foreach(obj, rb_obj_copy_ivs_to_hash_table_i, (st_data_t)table);
1906}
1907
1908void
1909rb_obj_copy_fields_to_hash_table(VALUE obj, st_table *table)
1910{
1911 rb_field_foreach(obj, rb_obj_copy_ivs_to_hash_table_i, (st_data_t)table, false);
1912}
1913
1914static attr_index_t
1915obj_field_set(VALUE obj, shape_id_t target_shape_id, ID field_name, VALUE val)
1916{
1917 shape_id_t current_shape_id = RBASIC_SHAPE_ID(obj);
1918
1919 if (UNLIKELY(rb_shape_too_complex_p(target_shape_id))) {
1920 if (UNLIKELY(!rb_shape_too_complex_p(current_shape_id))) {
1921 current_shape_id = rb_evict_fields_to_hash(obj);
1922 }
1923
1924 if (RSHAPE_LEN(target_shape_id) > RSHAPE_LEN(current_shape_id)) {
1925 RBASIC_SET_SHAPE_ID(obj, target_shape_id);
1926 }
1927
1928 if (!field_name) {
1929 field_name = RSHAPE_EDGE_NAME(target_shape_id);
1930 RUBY_ASSERT(field_name);
1931 }
1932
1933 st_insert(ROBJECT_FIELDS_HASH(obj), (st_data_t)field_name, (st_data_t)val);
1934 RB_OBJ_WRITTEN(obj, Qundef, val);
1935
1936 return ATTR_INDEX_NOT_SET;
1937 }
1938 else {
1939 attr_index_t index = RSHAPE_INDEX(target_shape_id);
1940
1941 if (index >= RSHAPE_LEN(current_shape_id)) {
1942 if (UNLIKELY(index >= RSHAPE_CAPACITY(current_shape_id))) {
1943 rb_ensure_iv_list_size(obj, RSHAPE_CAPACITY(current_shape_id), RSHAPE_CAPACITY(target_shape_id));
1944 }
1945 RBASIC_SET_SHAPE_ID(obj, target_shape_id);
1946 }
1947
1948 RB_OBJ_WRITE(obj, &ROBJECT_FIELDS(obj)[index], val);
1949
1950 return index;
1951 }
1952}
1953
1954static attr_index_t
1955obj_ivar_set(VALUE obj, ID id, VALUE val)
1956{
1957 bool dontcare;
1958 shape_id_t target_shape_id = generic_shape_ivar(obj, id, &dontcare);
1959 return obj_field_set(obj, target_shape_id, id, val);
1960}
1961
1962/* Set the instance variable +val+ on object +obj+ at ivar name +id+.
1963 * This function only works with T_OBJECT objects, so make sure
1964 * +obj+ is of type T_OBJECT before using this function.
1965 */
1966VALUE
1967rb_vm_set_ivar_id(VALUE obj, ID id, VALUE val)
1968{
1969 rb_check_frozen(obj);
1970 obj_ivar_set(obj, id, val);
1971 return val;
1972}
1973
1975{
1976 if (RB_FL_ABLE(x)) {
1978 if (TYPE(x) == T_STRING) {
1979 RB_FL_UNSET_RAW(x, FL_USER2 | FL_USER3); // STR_CHILLED
1980 }
1981
1982 RB_SET_SHAPE_ID(x, rb_shape_transition_frozen(x));
1983
1984 if (RBASIC_CLASS(x)) {
1986 }
1987 }
1988}
1989
1990static attr_index_t class_ivar_set(VALUE obj, ID id, VALUE val, bool *new_ivar);
1991
1992static attr_index_t
1993ivar_set(VALUE obj, ID id, VALUE val)
1994{
1995 RB_DEBUG_COUNTER_INC(ivar_set_base);
1996
1997 switch (BUILTIN_TYPE(obj)) {
1998 case T_OBJECT:
1999 return obj_ivar_set(obj, id, val);
2000 case T_CLASS:
2001 case T_MODULE:
2002 {
2003 IVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(id);
2004 bool dontcare;
2005 return class_ivar_set(obj, id, val, &dontcare);
2006 }
2007 default:
2008 return generic_ivar_set(obj, id, val);
2009 }
2010}
2011
2012VALUE
2014{
2015 rb_check_frozen(obj);
2016 ivar_set(obj, id, val);
2017 return val;
2018}
2019
2020attr_index_t
2021rb_ivar_set_index(VALUE obj, ID id, VALUE val)
2022{
2023 return ivar_set(obj, id, val);
2024}
2025
2026void
2027rb_ivar_set_internal(VALUE obj, ID id, VALUE val)
2028{
2029 // should be internal instance variable name (no @ prefix)
2030 VM_ASSERT(!rb_is_instance_id(id));
2031
2032 ivar_set(obj, id, val);
2033}
2034
2035attr_index_t
2036rb_obj_field_set(VALUE obj, shape_id_t target_shape_id, ID field_name, VALUE val)
2037{
2038 switch (BUILTIN_TYPE(obj)) {
2039 case T_OBJECT:
2040 return obj_field_set(obj, target_shape_id, field_name, val);
2041 case T_CLASS:
2042 case T_MODULE:
2043 // The only field is object_id and T_CLASS handle it differently.
2044 rb_bug("Unreachable");
2045 break;
2046 default:
2047 return generic_field_set(obj, target_shape_id, field_name, val);
2048 }
2049}
2050
2051static VALUE
2052ivar_defined0(VALUE obj, ID id)
2053{
2054 attr_index_t index;
2055
2056 if (rb_shape_obj_too_complex_p(obj)) {
2057 VALUE idx;
2058 st_table *table = NULL;
2059 switch (BUILTIN_TYPE(obj)) {
2060 case T_CLASS:
2061 case T_MODULE:
2062 rb_bug("Unreachable");
2063 break;
2064
2065 case T_IMEMO:
2066 RUBY_ASSERT(IMEMO_TYPE_P(obj, imemo_fields));
2067 table = rb_imemo_fields_complex_tbl(obj);
2068 break;
2069
2070 case T_OBJECT:
2071 table = ROBJECT_FIELDS_HASH(obj);
2072 break;
2073
2074 default: {
2075 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj); // defined? doesn't require ractor checks
2076 table = rb_imemo_fields_complex_tbl(fields_obj);
2077 }
2078 }
2079
2080 if (!table || !rb_st_lookup(table, id, &idx)) {
2081 return Qfalse;
2082 }
2083
2084 return Qtrue;
2085 }
2086 else {
2087 return RBOOL(rb_shape_get_iv_index(RBASIC_SHAPE_ID(obj), id, &index));
2088 }
2089}
2090
2091VALUE
2093{
2094 if (SPECIAL_CONST_P(obj)) return Qfalse;
2095
2096 VALUE defined = Qfalse;
2097 switch (BUILTIN_TYPE(obj)) {
2098 case T_CLASS:
2099 case T_MODULE:
2100 {
2101 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
2102 if (fields_obj) {
2103 defined = ivar_defined0(fields_obj, id);
2104 }
2105 }
2106 break;
2107 default:
2108 defined = ivar_defined0(obj, id);
2109 break;
2110 }
2111 return defined;
2112}
2113
2115 VALUE obj;
2116 struct gen_fields_tbl *fields_tbl;
2117 st_data_t arg;
2118 rb_ivar_foreach_callback_func *func;
2119 VALUE *fields;
2120 bool ivar_only;
2121};
2122
2123static int
2124iterate_over_shapes_callback(shape_id_t shape_id, void *data)
2125{
2126 struct iv_itr_data *itr_data = data;
2127
2128 if (itr_data->ivar_only && !RSHAPE_TYPE_P(shape_id, SHAPE_IVAR)) {
2129 return ST_CONTINUE;
2130 }
2131
2132 VALUE *fields;
2133 switch (BUILTIN_TYPE(itr_data->obj)) {
2134 case T_OBJECT:
2135 RUBY_ASSERT(!rb_shape_obj_too_complex_p(itr_data->obj));
2136 fields = ROBJECT_FIELDS(itr_data->obj);
2137 break;
2138 case T_IMEMO:
2139 RUBY_ASSERT(IMEMO_TYPE_P(itr_data->obj, imemo_fields));
2140 RUBY_ASSERT(!rb_shape_obj_too_complex_p(itr_data->obj));
2141
2142 fields = rb_imemo_fields_ptr(itr_data->obj);
2143 break;
2144 default:
2145 rb_bug("Unreachable");
2146 }
2147
2148 VALUE val = fields[RSHAPE_INDEX(shape_id)];
2149 return itr_data->func(RSHAPE_EDGE_NAME(shape_id), val, itr_data->arg);
2150}
2151
2152/*
2153 * Returns a flag to stop iterating depending on the result of +callback+.
2154 */
2155static void
2156iterate_over_shapes(shape_id_t shape_id, rb_ivar_foreach_callback_func *callback, struct iv_itr_data *itr_data)
2157{
2158 rb_shape_foreach_field(shape_id, iterate_over_shapes_callback, itr_data);
2159}
2160
2161static int
2162each_hash_iv(st_data_t id, st_data_t val, st_data_t data)
2163{
2164 struct iv_itr_data * itr_data = (struct iv_itr_data *)data;
2165 rb_ivar_foreach_callback_func *callback = itr_data->func;
2166 if (is_internal_id((ID)id)) {
2167 return ST_CONTINUE;
2168 }
2169 return callback((ID)id, (VALUE)val, itr_data->arg);
2170}
2171
2172static void
2173obj_fields_each(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg, bool ivar_only)
2174{
2175 struct iv_itr_data itr_data = {
2176 .obj = obj,
2177 .arg = arg,
2178 .func = func,
2179 .ivar_only = ivar_only,
2180 };
2181
2182 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
2183 if (rb_shape_too_complex_p(shape_id)) {
2184 rb_st_foreach(ROBJECT_FIELDS_HASH(obj), each_hash_iv, (st_data_t)&itr_data);
2185 }
2186 else {
2187 itr_data.fields = ROBJECT_FIELDS(obj);
2188 iterate_over_shapes(shape_id, func, &itr_data);
2189 }
2190}
2191
2192static void
2193imemo_fields_each(VALUE fields_obj, rb_ivar_foreach_callback_func *func, st_data_t arg, bool ivar_only)
2194{
2195 IMEMO_TYPE_P(fields_obj, imemo_fields);
2196
2197 struct iv_itr_data itr_data = {
2198 .obj = fields_obj,
2199 .arg = arg,
2200 .func = func,
2201 .ivar_only = ivar_only,
2202 };
2203
2204 shape_id_t shape_id = RBASIC_SHAPE_ID(fields_obj);
2205 if (rb_shape_too_complex_p(shape_id)) {
2206 rb_st_foreach(rb_imemo_fields_complex_tbl(fields_obj), each_hash_iv, (st_data_t)&itr_data);
2207 }
2208 else {
2209 itr_data.fields = rb_imemo_fields_ptr(fields_obj);
2210 iterate_over_shapes(shape_id, func, &itr_data);
2211 }
2212}
2213
2214void
2216{
2217 VALUE new_fields_obj;
2218
2219 rb_check_frozen(dest);
2220
2221 if (!rb_obj_gen_fields_p(obj)) {
2222 return;
2223 }
2224
2225 shape_id_t src_shape_id = rb_obj_shape_id(obj);
2226
2227 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
2228 if (fields_obj) {
2229 unsigned long src_num_ivs = rb_ivar_count(fields_obj);
2230 if (!src_num_ivs) {
2231 goto clear;
2232 }
2233
2234 if (rb_shape_too_complex_p(src_shape_id)) {
2235 rb_shape_copy_complex_ivars(dest, obj, src_shape_id, rb_imemo_fields_complex_tbl(fields_obj));
2236 return;
2237 }
2238
2239 shape_id_t dest_shape_id = src_shape_id;
2240 shape_id_t initial_shape_id = rb_obj_shape_id(dest);
2241
2242 if (!rb_shape_canonical_p(src_shape_id)) {
2243 RUBY_ASSERT(RSHAPE_TYPE_P(initial_shape_id, SHAPE_ROOT));
2244
2245 dest_shape_id = rb_shape_rebuild(initial_shape_id, src_shape_id);
2246 if (UNLIKELY(rb_shape_too_complex_p(dest_shape_id))) {
2247 st_table *table = rb_st_init_numtable_with_size(src_num_ivs);
2248 rb_obj_copy_ivs_to_hash_table(obj, table);
2249 rb_obj_init_too_complex(dest, table);
2250 return;
2251 }
2252 }
2253
2254 if (!RSHAPE_LEN(dest_shape_id)) {
2255 RBASIC_SET_SHAPE_ID(dest, dest_shape_id);
2256 return;
2257 }
2258
2259 new_fields_obj = rb_imemo_fields_new(dest, RSHAPE_CAPACITY(dest_shape_id), RB_OBJ_SHAREABLE_P(dest));
2260 VALUE *src_buf = rb_imemo_fields_ptr(fields_obj);
2261 VALUE *dest_buf = rb_imemo_fields_ptr(new_fields_obj);
2262 rb_shape_copy_fields(new_fields_obj, dest_buf, dest_shape_id, src_buf, src_shape_id);
2263 RBASIC_SET_SHAPE_ID(new_fields_obj, dest_shape_id);
2264
2265 rb_obj_replace_fields(dest, new_fields_obj);
2266 }
2267 return;
2268
2269 clear:
2271}
2272
2273void
2274rb_replace_generic_ivar(VALUE clone, VALUE obj)
2275{
2276 RB_VM_LOCKING() {
2277 st_data_t fields_tbl, obj_data = (st_data_t)obj;
2278 if (st_delete(generic_fields_tbl_, &obj_data, &fields_tbl)) {
2279 st_insert(generic_fields_tbl_, (st_data_t)clone, fields_tbl);
2280 RB_OBJ_WRITTEN(clone, Qundef, fields_tbl);
2281 }
2282 else {
2283 rb_bug("unreachable");
2284 }
2285 }
2286}
2287
2288void
2289rb_field_foreach(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg, bool ivar_only)
2290{
2291 if (SPECIAL_CONST_P(obj)) return;
2292 switch (BUILTIN_TYPE(obj)) {
2293 case T_IMEMO:
2294 if (IMEMO_TYPE_P(obj, imemo_fields)) {
2295 imemo_fields_each(obj, func, arg, ivar_only);
2296 }
2297 break;
2298 case T_OBJECT:
2299 obj_fields_each(obj, func, arg, ivar_only);
2300 break;
2301 case T_CLASS:
2302 case T_MODULE:
2303 {
2304 IVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(0);
2305 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
2306 if (fields_obj) {
2307 imemo_fields_each(fields_obj, func, arg, ivar_only);
2308 }
2309 }
2310 break;
2311 default:
2312 {
2313 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
2314 if (fields_obj) {
2315 imemo_fields_each(fields_obj, func, arg, ivar_only);
2316 }
2317 }
2318 break;
2319 }
2320}
2321
2322void
2323rb_ivar_foreach(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg)
2324{
2325 rb_field_foreach(obj, func, arg, true);
2326}
2327
2328st_index_t
2330{
2331 if (SPECIAL_CONST_P(obj)) return 0;
2332
2333 st_index_t iv_count = 0;
2334 switch (BUILTIN_TYPE(obj)) {
2335 case T_OBJECT:
2336 iv_count = ROBJECT_FIELDS_COUNT(obj);
2337 break;
2338
2339 case T_CLASS:
2340 case T_MODULE:
2341 {
2342 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
2343 if (!fields_obj) {
2344 return 0;
2345 }
2346 if (rb_shape_obj_too_complex_p(fields_obj)) {
2347 iv_count = rb_st_table_size(rb_imemo_fields_complex_tbl(fields_obj));
2348 }
2349 else {
2350 iv_count = RBASIC_FIELDS_COUNT(fields_obj);
2351 }
2352 }
2353 break;
2354
2355 case T_IMEMO:
2356 RUBY_ASSERT(IMEMO_TYPE_P(obj, imemo_fields));
2357
2358 if (rb_shape_obj_too_complex_p(obj)) {
2359 iv_count = rb_st_table_size(rb_imemo_fields_complex_tbl(obj));
2360 }
2361 else {
2362 iv_count = RBASIC_FIELDS_COUNT(obj);
2363 }
2364 break;
2365
2366 default:
2367 {
2368 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
2369 if (fields_obj) {
2370 if (rb_shape_obj_too_complex_p(fields_obj)) {
2371 rb_st_table_size(rb_imemo_fields_complex_tbl(fields_obj));
2372 }
2373 else {
2374 iv_count = RBASIC_FIELDS_COUNT(obj);
2375 }
2376 }
2377 }
2378 break;
2379 }
2380
2381 if (rb_shape_obj_has_id(obj)) {
2382 iv_count--;
2383 }
2384
2385 return iv_count;
2386}
2387
2388static int
2389ivar_i(ID key, VALUE v, st_data_t a)
2390{
2391 VALUE ary = (VALUE)a;
2392
2393 if (rb_is_instance_id(key)) {
2394 rb_ary_push(ary, ID2SYM(key));
2395 }
2396 return ST_CONTINUE;
2397}
2398
2399/*
2400 * call-seq:
2401 * obj.instance_variables -> array
2402 *
2403 * Returns an array of instance variable names for the receiver. Note
2404 * that simply defining an accessor does not create the corresponding
2405 * instance variable.
2406 *
2407 * class Fred
2408 * attr_accessor :a1
2409 * def initialize
2410 * @iv = 3
2411 * end
2412 * end
2413 * Fred.new.instance_variables #=> [:@iv]
2414 */
2415
2416VALUE
2418{
2419 VALUE ary;
2420
2421 ary = rb_ary_new();
2422 rb_ivar_foreach(obj, ivar_i, ary);
2423 return ary;
2424}
2425
2426#define rb_is_constant_id rb_is_const_id
2427#define rb_is_constant_name rb_is_const_name
2428#define id_for_var(obj, name, part, type) \
2429 id_for_var_message(obj, name, type, "'%1$s' is not allowed as "#part" "#type" variable name")
2430#define id_for_var_message(obj, name, type, message) \
2431 check_id_type(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message))
2432static ID
2433check_id_type(VALUE obj, VALUE *pname,
2434 int (*valid_id_p)(ID), int (*valid_name_p)(VALUE),
2435 const char *message, size_t message_len)
2436{
2437 ID id = rb_check_id(pname);
2438 VALUE name = *pname;
2439
2440 if (id ? !valid_id_p(id) : !valid_name_p(name)) {
2441 rb_name_err_raise_str(rb_fstring_new(message, message_len),
2442 obj, name);
2443 }
2444 return id;
2445}
2446
2447/*
2448 * call-seq:
2449 * obj.remove_instance_variable(symbol) -> obj
2450 * obj.remove_instance_variable(string) -> obj
2451 *
2452 * Removes the named instance variable from <i>obj</i>, returning that
2453 * variable's value. The name can be passed as a symbol or as a string.
2454 *
2455 * class Dummy
2456 * attr_reader :var
2457 * def initialize
2458 * @var = 99
2459 * end
2460 * def remove
2461 * remove_instance_variable(:@var)
2462 * end
2463 * end
2464 * d = Dummy.new
2465 * d.var #=> 99
2466 * d.remove #=> 99
2467 * d.var #=> nil
2468 */
2469
2470VALUE
2472{
2473 const ID id = id_for_var(obj, name, an, instance);
2474
2475 // Frozen check comes here because it's expected that we raise a
2476 // NameError (from the id_for_var check) before we raise a FrozenError
2477 rb_check_frozen(obj);
2478
2479 if (id) {
2480 VALUE val = rb_ivar_delete(obj, id, Qundef);
2481
2482 if (!UNDEF_P(val)) return val;
2483 }
2484
2485 rb_name_err_raise("instance variable %1$s not defined",
2486 obj, name);
2488}
2489
2490NORETURN(static void uninitialized_constant(VALUE, VALUE));
2491static void
2492uninitialized_constant(VALUE klass, VALUE name)
2493{
2494 if (klass && rb_class_real(klass) != rb_cObject)
2495 rb_name_err_raise("uninitialized constant %2$s::%1$s",
2496 klass, name);
2497 else
2498 rb_name_err_raise("uninitialized constant %1$s",
2499 klass, name);
2500}
2501
2502VALUE
2503rb_const_missing(VALUE klass, VALUE name)
2504{
2505 VALUE value = rb_funcallv(klass, idConst_missing, 1, &name);
2506 rb_vm_inc_const_missing_count();
2507 return value;
2508}
2509
2510
2511/*
2512 * call-seq:
2513 * mod.const_missing(sym) -> obj
2514 *
2515 * Invoked when a reference is made to an undefined constant in
2516 * <i>mod</i>. It is passed a symbol for the undefined constant, and
2517 * returns a value to be used for that constant. For example, consider:
2518 *
2519 * def Foo.const_missing(name)
2520 * name # return the constant name as Symbol
2521 * end
2522 *
2523 * Foo::UNDEFINED_CONST #=> :UNDEFINED_CONST: symbol returned
2524 *
2525 * As the example above shows, +const_missing+ is not required to create the
2526 * missing constant in <i>mod</i>, though that is often a side-effect. The
2527 * caller gets its return value when triggered. If the constant is also defined,
2528 * further lookups won't hit +const_missing+ and will return the value stored in
2529 * the constant as usual. Otherwise, +const_missing+ will be invoked again.
2530 *
2531 * In the next example, when a reference is made to an undefined constant,
2532 * +const_missing+ attempts to load a file whose path is the lowercase version
2533 * of the constant name (thus class <code>Fred</code> is assumed to be in file
2534 * <code>fred.rb</code>). If defined as a side-effect of loading the file, the
2535 * method returns the value stored in the constant. This implements an autoload
2536 * feature similar to Kernel#autoload and Module#autoload, though it differs in
2537 * important ways.
2538 *
2539 * def Object.const_missing(name)
2540 * @looked_for ||= {}
2541 * str_name = name.to_s
2542 * raise "Constant not found: #{name}" if @looked_for[str_name]
2543 * @looked_for[str_name] = 1
2544 * file = str_name.downcase
2545 * require file
2546 * const_get(name, false)
2547 * end
2548 *
2549 */
2550
2551VALUE
2552rb_mod_const_missing(VALUE klass, VALUE name)
2553{
2554 rb_execution_context_t *ec = GET_EC();
2555 VALUE ref = ec->private_const_reference;
2556 rb_vm_pop_cfunc_frame();
2557 if (ref) {
2558 ec->private_const_reference = 0;
2559 rb_name_err_raise("private constant %2$s::%1$s referenced", ref, name);
2560 }
2561 uninitialized_constant(klass, name);
2562
2564}
2565
2566static void
2567autoload_table_mark(void *ptr)
2568{
2569 rb_mark_tbl_no_pin((st_table *)ptr);
2570}
2571
2572static void
2573autoload_table_free(void *ptr)
2574{
2575 st_free_table((st_table *)ptr);
2576}
2577
2578static size_t
2579autoload_table_memsize(const void *ptr)
2580{
2581 const st_table *tbl = ptr;
2582 return st_memsize(tbl);
2583}
2584
2585static void
2586autoload_table_compact(void *ptr)
2587{
2588 rb_gc_ref_update_table_values_only((st_table *)ptr);
2589}
2590
2591static const rb_data_type_t autoload_table_type = {
2592 "autoload_table",
2593 {autoload_table_mark, autoload_table_free, autoload_table_memsize, autoload_table_compact,},
2594 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
2595};
2596
2597#define check_autoload_table(av) \
2598 (struct st_table *)rb_check_typeddata((av), &autoload_table_type)
2599
2600static VALUE
2601autoload_data(VALUE mod, ID id)
2602{
2603 struct st_table *tbl;
2604 st_data_t val;
2605
2606 // If we are called with a non-origin ICLASS, fetch the autoload data from
2607 // the original module.
2608 if (RB_TYPE_P(mod, T_ICLASS)) {
2609 if (RICLASS_IS_ORIGIN_P(mod)) {
2610 return 0;
2611 }
2612 else {
2613 mod = RBASIC(mod)->klass;
2614 }
2615 }
2616
2618
2619 // Look up the instance variable table for `autoload`, then index into that table with the given constant name `id`.
2620
2621 VALUE tbl_value = rb_ivar_lookup(mod, autoload, Qfalse);
2622 if (!RTEST(tbl_value) || !(tbl = check_autoload_table(tbl_value)) || !st_lookup(tbl, (st_data_t)id, &val)) {
2623 return 0;
2624 }
2625
2626 return (VALUE)val;
2627}
2628
2629// Every autoload constant has exactly one instance of autoload_const, stored in `autoload_features`. Since multiple autoload constants can refer to the same file, every `autoload_const` refers to a de-duplicated `autoload_data`.
2631 // The linked list node of all constants which are loaded by the related autoload feature.
2632 struct ccan_list_node cnode; /* <=> autoload_data.constants */
2633
2634 // The shared "autoload_data" if multiple constants are defined from the same feature.
2635 VALUE autoload_data_value;
2636
2637 // The box object when the autoload is called in a user box
2638 // Otherwise, Qnil means the root box
2639 VALUE box_value;
2640
2641 // The module we are loading a constant into.
2642 VALUE module;
2643
2644 // The name of the constant we are loading.
2645 ID name;
2646
2647 // The value of the constant (after it's loaded).
2648 VALUE value;
2649
2650 // The constant entry flags which need to be re-applied after autoloading the feature.
2651 rb_const_flag_t flag;
2652
2653 // The source file and line number that defined this constant (different from feature path).
2654 VALUE file;
2655 int line;
2656};
2657
2658// Each `autoload_data` uniquely represents a specific feature which can be loaded, and a list of constants which it is able to define. We use a mutex to coordinate multiple threads trying to load the same feature.
2660 // The feature path to require to load this constant.
2661 VALUE feature;
2662
2663 // The mutex which is protecting autoloading this feature.
2664 VALUE mutex;
2665
2666 // The process fork serial number since the autoload mutex will become invalid on fork.
2667 rb_serial_t fork_gen;
2668
2669 // The linked list of all constants that are going to be loaded by this autoload.
2670 struct ccan_list_head constants; /* <=> autoload_const.cnode */
2671};
2672
2673static void
2674autoload_data_mark_and_move(void *ptr)
2675{
2676 struct autoload_data *p = ptr;
2677
2678 rb_gc_mark_and_move(&p->feature);
2679 rb_gc_mark_and_move(&p->mutex);
2680}
2681
2682static void
2683autoload_data_free(void *ptr)
2684{
2685 struct autoload_data *p = ptr;
2686
2687 struct autoload_const *autoload_const, *next;
2688 ccan_list_for_each_safe(&p->constants, autoload_const, next, cnode) {
2689 ccan_list_del_init(&autoload_const->cnode);
2690 }
2691
2692 ruby_xfree(p);
2693}
2694
2695static size_t
2696autoload_data_memsize(const void *ptr)
2697{
2698 return sizeof(struct autoload_data);
2699}
2700
2701static const rb_data_type_t autoload_data_type = {
2702 "autoload_data",
2703 {autoload_data_mark_and_move, autoload_data_free, autoload_data_memsize, autoload_data_mark_and_move},
2704 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
2705};
2706
2707static void
2708autoload_const_mark_and_move(void *ptr)
2709{
2710 struct autoload_const *ac = ptr;
2711
2712 rb_gc_mark_and_move(&ac->module);
2713 rb_gc_mark_and_move(&ac->autoload_data_value);
2714 rb_gc_mark_and_move(&ac->value);
2715 rb_gc_mark_and_move(&ac->file);
2716 rb_gc_mark_and_move(&ac->box_value);
2717}
2718
2719static size_t
2720autoload_const_memsize(const void *ptr)
2721{
2722 return sizeof(struct autoload_const);
2723}
2724
2725static void
2726autoload_const_free(void *ptr)
2727{
2728 struct autoload_const *autoload_const = ptr;
2729
2730 ccan_list_del(&autoload_const->cnode);
2731 ruby_xfree(ptr);
2732}
2733
2734static const rb_data_type_t autoload_const_type = {
2735 "autoload_const",
2736 {autoload_const_mark_and_move, autoload_const_free, autoload_const_memsize, autoload_const_mark_and_move,},
2737 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
2738};
2739
2740static struct autoload_data *
2741get_autoload_data(VALUE autoload_const_value, struct autoload_const **autoload_const_pointer)
2742{
2743 struct autoload_const *autoload_const = rb_check_typeddata(autoload_const_value, &autoload_const_type);
2744
2745 VALUE autoload_data_value = autoload_const->autoload_data_value;
2746 struct autoload_data *autoload_data = rb_check_typeddata(autoload_data_value, &autoload_data_type);
2747
2748 /* do not reach across stack for ->state after forking: */
2749 if (autoload_data && autoload_data->fork_gen != GET_VM()->fork_gen) {
2750 RB_OBJ_WRITE(autoload_data_value, &autoload_data->mutex, Qnil);
2751 autoload_data->fork_gen = 0;
2752 }
2753
2754 if (autoload_const_pointer) *autoload_const_pointer = autoload_const;
2755
2756 return autoload_data;
2757}
2758
2760 VALUE dst_tbl_value;
2761 struct st_table *dst_tbl;
2762 const rb_box_t *box;
2763};
2764
2765static int
2766autoload_copy_table_for_box_i(st_data_t key, st_data_t value, st_data_t arg)
2767{
2769 struct autoload_copy_table_data *data = (struct autoload_copy_table_data *)arg;
2770 struct st_table *tbl = data->dst_tbl;
2771 VALUE tbl_value = data->dst_tbl_value;
2772 const rb_box_t *box = data->box;
2773
2774 VALUE src_value = (VALUE)value;
2775 struct autoload_const *src_const = rb_check_typeddata(src_value, &autoload_const_type);
2776 // autoload_data can be shared between copies because the feature is equal between copies.
2777 VALUE autoload_data_value = src_const->autoload_data_value;
2778 struct autoload_data *autoload_data = rb_check_typeddata(autoload_data_value, &autoload_data_type);
2779
2780 VALUE new_value = TypedData_Make_Struct(0, struct autoload_const, &autoload_const_type, autoload_const);
2781 RB_OBJ_WRITE(new_value, &autoload_const->box_value, rb_get_box_object((rb_box_t *)box));
2782 RB_OBJ_WRITE(new_value, &autoload_const->module, src_const->module);
2783 autoload_const->name = src_const->name;
2784 RB_OBJ_WRITE(new_value, &autoload_const->value, src_const->value);
2785 autoload_const->flag = src_const->flag;
2786 RB_OBJ_WRITE(new_value, &autoload_const->autoload_data_value, autoload_data_value);
2787 ccan_list_add_tail(&autoload_data->constants, &autoload_const->cnode);
2788
2789 st_insert(tbl, (st_data_t)autoload_const->name, (st_data_t)new_value);
2790 RB_OBJ_WRITTEN(tbl_value, Qundef, new_value);
2791
2792 return ST_CONTINUE;
2793}
2794
2795void
2796rb_autoload_copy_table_for_box(st_table *iv_ptr, const rb_box_t *box)
2797{
2798 struct st_table *src_tbl, *dst_tbl;
2799 VALUE src_tbl_value, dst_tbl_value;
2800 if (!rb_st_lookup(iv_ptr, (st_data_t)autoload, (st_data_t *)&src_tbl_value)) {
2801 // the class has no autoload table yet.
2802 return;
2803 }
2804 if (!RTEST(src_tbl_value) || !(src_tbl = check_autoload_table(src_tbl_value))) {
2805 // the __autoload__ ivar value isn't autoload table value.
2806 return;
2807 }
2808 src_tbl = check_autoload_table(src_tbl_value);
2809
2810 dst_tbl_value = TypedData_Wrap_Struct(0, &autoload_table_type, NULL);
2811 RTYPEDDATA_DATA(dst_tbl_value) = dst_tbl = st_init_numtable();
2812
2813 struct autoload_copy_table_data data = {
2814 .dst_tbl_value = dst_tbl_value,
2815 .dst_tbl = dst_tbl,
2816 .box = box,
2817 };
2818
2819 st_foreach(src_tbl, autoload_copy_table_for_box_i, (st_data_t)&data);
2820 st_insert(iv_ptr, (st_data_t)autoload, (st_data_t)dst_tbl_value);
2821}
2822
2823void
2824rb_autoload(VALUE module, ID name, const char *feature)
2825{
2826 if (!feature || !*feature) {
2827 rb_raise(rb_eArgError, "empty feature name");
2828 }
2829
2830 rb_autoload_str(module, name, rb_fstring_cstr(feature));
2831}
2832
2833static void const_set(VALUE klass, ID id, VALUE val);
2834static void const_added(VALUE klass, ID const_name);
2835
2837 VALUE module;
2838 ID name;
2839 VALUE feature;
2840 VALUE box_value;
2841};
2842
2843static VALUE
2844autoload_feature_lookup_or_create(VALUE feature, struct autoload_data **autoload_data_pointer)
2845{
2846 RUBY_ASSERT_MUTEX_OWNED(autoload_mutex);
2847 RUBY_ASSERT_CRITICAL_SECTION_ENTER();
2848
2849 VALUE autoload_data_value = rb_hash_aref(autoload_features, feature);
2851
2852 if (NIL_P(autoload_data_value)) {
2853 autoload_data_value = TypedData_Make_Struct(0, struct autoload_data, &autoload_data_type, autoload_data);
2854 RB_OBJ_WRITE(autoload_data_value, &autoload_data->feature, feature);
2855 RB_OBJ_WRITE(autoload_data_value, &autoload_data->mutex, Qnil);
2856 ccan_list_head_init(&autoload_data->constants);
2857
2858 if (autoload_data_pointer) *autoload_data_pointer = autoload_data;
2859
2860 rb_hash_aset(autoload_features, feature, autoload_data_value);
2861 }
2862 else if (autoload_data_pointer) {
2863 *autoload_data_pointer = rb_check_typeddata(autoload_data_value, &autoload_data_type);
2864 }
2865
2866 RUBY_ASSERT_CRITICAL_SECTION_LEAVE();
2867 return autoload_data_value;
2868}
2869
2870static VALUE
2871autoload_table_lookup_or_create(VALUE module)
2872{
2873 VALUE autoload_table_value = rb_ivar_lookup(module, autoload, Qfalse);
2874 if (RTEST(autoload_table_value)) {
2875 return autoload_table_value;
2876 }
2877 else {
2878 autoload_table_value = TypedData_Wrap_Struct(0, &autoload_table_type, NULL);
2879 rb_class_ivar_set(module, autoload, autoload_table_value);
2880 RTYPEDDATA_DATA(autoload_table_value) = st_init_numtable();
2881 return autoload_table_value;
2882 }
2883}
2884
2885static VALUE
2886autoload_synchronized(VALUE _arguments)
2887{
2888 struct autoload_arguments *arguments = (struct autoload_arguments *)_arguments;
2889
2890 rb_const_entry_t *constant_entry = rb_const_lookup(arguments->module, arguments->name);
2891 if (constant_entry && !UNDEF_P(constant_entry->value)) {
2892 return Qfalse;
2893 }
2894
2895 // Reset any state associated with any previous constant:
2896 const_set(arguments->module, arguments->name, Qundef);
2897
2898 VALUE autoload_table_value = autoload_table_lookup_or_create(arguments->module);
2899 struct st_table *autoload_table = check_autoload_table(autoload_table_value);
2900
2901 // Ensure the string is uniqued since we use an identity lookup:
2902 VALUE feature = rb_fstring(arguments->feature);
2903
2905 VALUE autoload_data_value = autoload_feature_lookup_or_create(feature, &autoload_data);
2906
2907 {
2909 VALUE autoload_const_value = TypedData_Make_Struct(0, struct autoload_const, &autoload_const_type, autoload_const);
2910 RB_OBJ_WRITE(autoload_const_value, &autoload_const->box_value, arguments->box_value);
2911 RB_OBJ_WRITE(autoload_const_value, &autoload_const->module, arguments->module);
2912 autoload_const->name = arguments->name;
2913 autoload_const->value = Qundef;
2914 autoload_const->flag = CONST_PUBLIC;
2915 RB_OBJ_WRITE(autoload_const_value, &autoload_const->autoload_data_value, autoload_data_value);
2916 ccan_list_add_tail(&autoload_data->constants, &autoload_const->cnode);
2917 st_insert(autoload_table, (st_data_t)arguments->name, (st_data_t)autoload_const_value);
2918 RB_OBJ_WRITTEN(autoload_table_value, Qundef, autoload_const_value);
2919 }
2920
2921 return Qtrue;
2922}
2923
2924void
2925rb_autoload_str(VALUE module, ID name, VALUE feature)
2926{
2927 const rb_box_t *box = rb_current_box();
2928 VALUE current_box_value = rb_get_box_object((rb_box_t *)box);
2929
2930 if (!rb_is_const_id(name)) {
2931 rb_raise(rb_eNameError, "autoload must be constant name: %"PRIsVALUE"", QUOTE_ID(name));
2932 }
2933
2934 Check_Type(feature, T_STRING);
2935 if (!RSTRING_LEN(feature)) {
2936 rb_raise(rb_eArgError, "empty feature name");
2937 }
2938
2939 struct autoload_arguments arguments = {
2940 .module = module,
2941 .name = name,
2942 .feature = feature,
2943 .box_value = current_box_value,
2944 };
2945
2946 VALUE result = rb_mutex_synchronize(autoload_mutex, autoload_synchronized, (VALUE)&arguments);
2947
2948 if (result == Qtrue) {
2949 const_added(module, name);
2950 }
2951}
2952
2953static void
2954autoload_delete(VALUE module, ID name)
2955{
2956 RUBY_ASSERT_CRITICAL_SECTION_ENTER();
2957
2958 st_data_t load = 0, key = name;
2959
2960 RUBY_ASSERT(RB_TYPE_P(module, T_CLASS) || RB_TYPE_P(module, T_MODULE));
2961
2962 VALUE table_value = rb_ivar_lookup(module, autoload, Qfalse);
2963 if (RTEST(table_value)) {
2964 struct st_table *table = check_autoload_table(table_value);
2965
2966 st_delete(table, &key, &load);
2967 RB_OBJ_WRITTEN(table_value, load, Qundef);
2968
2969 /* Qfalse can indicate already deleted */
2970 if (load != Qfalse) {
2972 struct autoload_data *autoload_data = get_autoload_data((VALUE)load, &autoload_const);
2973
2974 VM_ASSERT(autoload_data);
2975 VM_ASSERT(!ccan_list_empty(&autoload_data->constants));
2976
2977 /*
2978 * we must delete here to avoid "already initialized" warnings
2979 * with parallel autoload. Using list_del_init here so list_del
2980 * works in autoload_const_free
2981 */
2982 ccan_list_del_init(&autoload_const->cnode);
2983
2984 if (ccan_list_empty(&autoload_data->constants)) {
2985 rb_hash_delete(autoload_features, autoload_data->feature);
2986 }
2987
2988 // If the autoload table is empty, we can delete it.
2989 if (table->num_entries == 0) {
2990 rb_attr_delete(module, autoload);
2991 }
2992 }
2993 }
2994
2995 RUBY_ASSERT_CRITICAL_SECTION_LEAVE();
2996}
2997
2998static int
2999autoload_by_someone_else(struct autoload_data *ele)
3000{
3001 return ele->mutex != Qnil && !rb_mutex_owned_p(ele->mutex);
3002}
3003
3004static VALUE
3005check_autoload_required(VALUE mod, ID id, const char **loadingpath)
3006{
3007 VALUE autoload_const_value = autoload_data(mod, id);
3009 const char *loading;
3010
3011 if (!autoload_const_value || !(autoload_data = get_autoload_data(autoload_const_value, 0))) {
3012 return 0;
3013 }
3014
3015 VALUE feature = autoload_data->feature;
3016
3017 /*
3018 * if somebody else is autoloading, we MUST wait for them, since
3019 * rb_provide_feature can provide a feature before autoload_const_set
3020 * completes. We must wait until autoload_const_set finishes in
3021 * the other thread.
3022 */
3023 if (autoload_by_someone_else(autoload_data)) {
3024 return autoload_const_value;
3025 }
3026
3027 loading = RSTRING_PTR(feature);
3028
3029 if (!rb_feature_provided(loading, &loading)) {
3030 return autoload_const_value;
3031 }
3032
3033 if (loadingpath && loading) {
3034 *loadingpath = loading;
3035 return autoload_const_value;
3036 }
3037
3038 return 0;
3039}
3040
3041static struct autoload_const *autoloading_const_entry(VALUE mod, ID id);
3042
3043int
3044rb_autoloading_value(VALUE mod, ID id, VALUE* value, rb_const_flag_t *flag)
3045{
3046 struct autoload_const *ac = autoloading_const_entry(mod, id);
3047 if (!ac) return FALSE;
3048
3049 if (value) {
3050 *value = ac->value;
3051 }
3052
3053 if (flag) {
3054 *flag = ac->flag;
3055 }
3056
3057 return TRUE;
3058}
3059
3060static int
3061autoload_by_current(struct autoload_data *ele)
3062{
3063 return ele->mutex != Qnil && rb_mutex_owned_p(ele->mutex);
3064}
3065
3066// If there is an autoloading constant and it has been set by the current
3067// execution context, return it. This allows threads which are loading code to
3068// refer to their own autoloaded constants.
3069struct autoload_const *
3070autoloading_const_entry(VALUE mod, ID id)
3071{
3072 VALUE load = autoload_data(mod, id);
3073 struct autoload_data *ele;
3074 struct autoload_const *ac;
3075
3076 // Find the autoloading state:
3077 if (!load || !(ele = get_autoload_data(load, &ac))) {
3078 // Couldn't be found:
3079 return 0;
3080 }
3081
3082 // Check if it's being loaded by the current thread/fiber:
3083 if (autoload_by_current(ele)) {
3084 if (!UNDEF_P(ac->value)) {
3085 return ac;
3086 }
3087 }
3088
3089 return 0;
3090}
3091
3092static int
3093autoload_defined_p(VALUE mod, ID id)
3094{
3095 rb_const_entry_t *ce = rb_const_lookup(mod, id);
3096
3097 // If there is no constant or the constant is not undefined (special marker for autoloading):
3098 if (!ce || !UNDEF_P(ce->value)) {
3099 // We are not autoloading:
3100 return 0;
3101 }
3102
3103 // Otherwise check if there is an autoload in flight right now:
3104 return !rb_autoloading_value(mod, id, NULL, NULL);
3105}
3106
3107static void const_tbl_update(struct autoload_const *, int);
3108
3110 VALUE module;
3111 ID name;
3112 int flag;
3113
3114 VALUE mutex;
3115
3116 // The specific constant which triggered the autoload code to fire:
3118
3119 // The parent autoload data which is shared between multiple constants:
3121};
3122
3123static VALUE
3124autoload_const_set(struct autoload_const *ac)
3125{
3126 check_before_mod_set(ac->module, ac->name, ac->value, "constant");
3127
3128 RB_VM_LOCKING() {
3129 const_tbl_update(ac, true);
3130 }
3131
3132 return 0; /* ignored */
3133}
3134
3135static VALUE
3136autoload_load_needed(VALUE _arguments)
3137{
3138 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3139
3140 const char *loading = 0, *src;
3141
3142 if (!autoload_defined_p(arguments->module, arguments->name)) {
3143 return Qfalse;
3144 }
3145
3146 VALUE autoload_const_value = check_autoload_required(arguments->module, arguments->name, &loading);
3147 if (!autoload_const_value) {
3148 return Qfalse;
3149 }
3150
3151 src = rb_sourcefile();
3152 if (src && loading && strcmp(src, loading) == 0) {
3153 return Qfalse;
3154 }
3155
3158 if (!(autoload_data = get_autoload_data(autoload_const_value, &autoload_const))) {
3159 return Qfalse;
3160 }
3161
3162 if (NIL_P(autoload_data->mutex)) {
3163 RB_OBJ_WRITE(autoload_const->autoload_data_value, &autoload_data->mutex, rb_mutex_new());
3164 autoload_data->fork_gen = GET_VM()->fork_gen;
3165 }
3166 else if (rb_mutex_owned_p(autoload_data->mutex)) {
3167 return Qfalse;
3168 }
3169
3170 arguments->mutex = autoload_data->mutex;
3171 arguments->autoload_const = autoload_const;
3172
3173 return autoload_const_value;
3174}
3175
3176static VALUE
3177autoload_apply_constants(VALUE _arguments)
3178{
3179 RUBY_ASSERT_CRITICAL_SECTION_ENTER();
3180
3181 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3182
3183 struct autoload_const *autoload_const = 0; // for ccan_container_off_var()
3184 struct autoload_const *next;
3185
3186 // We use safe iteration here because `autoload_const_set` will eventually invoke
3187 // `autoload_delete` which will remove the constant from the linked list. In theory, once
3188 // the `autoload_data->constants` linked list is empty, we can remove it.
3189
3190 // Iterate over all constants and assign them:
3191 ccan_list_for_each_safe(&arguments->autoload_data->constants, autoload_const, next, cnode) {
3192 if (!UNDEF_P(autoload_const->value)) {
3193 autoload_const_set(autoload_const);
3194 }
3195 }
3196
3197 RUBY_ASSERT_CRITICAL_SECTION_LEAVE();
3198
3199 return Qtrue;
3200}
3201
3202static VALUE
3203autoload_feature_require(VALUE _arguments)
3204{
3205 VALUE receiver = rb_vm_top_self();
3206
3207 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3208
3209 struct autoload_const *autoload_const = arguments->autoload_const;
3210 VALUE autoload_box_value = autoload_const->box_value;
3211
3212 // We save this for later use in autoload_apply_constants:
3213 arguments->autoload_data = rb_check_typeddata(autoload_const->autoload_data_value, &autoload_data_type);
3214
3215 if (rb_box_available() && BOX_OBJ_P(autoload_box_value))
3216 receiver = autoload_box_value;
3217
3218 /*
3219 * Clear the global cc cache table because the require method can be different from the current
3220 * box's one and it may cause inconsistent cc-cme states.
3221 * For example, the assertion below may fail in gccct_method_search();
3222 * VM_ASSERT(vm_cc_check_cme(cc, rb_callable_method_entry(klass, mid)))
3223 */
3224 rb_gccct_clear_table(Qnil);
3225
3226 VALUE result = rb_funcall(receiver, rb_intern("require"), 1, arguments->autoload_data->feature);
3227
3228 if (RTEST(result)) {
3229 return rb_mutex_synchronize(autoload_mutex, autoload_apply_constants, _arguments);
3230 }
3231 return result;
3232}
3233
3234static VALUE
3235autoload_try_load(VALUE _arguments)
3236{
3237 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3238
3239 VALUE result = autoload_feature_require(_arguments);
3240
3241 // After we loaded the feature, if the constant is not defined, we remove it completely:
3242 rb_const_entry_t *ce = rb_const_lookup(arguments->module, arguments->name);
3243
3244 if (!ce || UNDEF_P(ce->value)) {
3245 result = Qfalse;
3246
3247 rb_const_remove(arguments->module, arguments->name);
3248
3249 if (arguments->module == rb_cObject) {
3250 rb_warning(
3251 "Expected %"PRIsVALUE" to define %"PRIsVALUE" but it didn't",
3252 arguments->autoload_data->feature,
3253 ID2SYM(arguments->name)
3254 );
3255 }
3256 else {
3257 rb_warning(
3258 "Expected %"PRIsVALUE" to define %"PRIsVALUE"::%"PRIsVALUE" but it didn't",
3259 arguments->autoload_data->feature,
3260 arguments->module,
3261 ID2SYM(arguments->name)
3262 );
3263 }
3264 }
3265 else {
3266 // Otherwise, it was loaded, copy the flags from the autoload constant:
3267 ce->flag |= arguments->flag;
3268 }
3269
3270 return result;
3271}
3272
3273VALUE
3275{
3276 rb_const_entry_t *ce = rb_const_lookup(module, name);
3277
3278 // We bail out as early as possible without any synchronisation:
3279 if (!ce || !UNDEF_P(ce->value)) {
3280 return Qfalse;
3281 }
3282
3283 // At this point, we assume there might be autoloading, so fail if it's ractor:
3284 if (UNLIKELY(!rb_ractor_main_p())) {
3285 return rb_ractor_autoload_load(module, name);
3286 }
3287
3288 // This state is stored on the stack and is used during the autoload process.
3289 struct autoload_load_arguments arguments = {.module = module, .name = name, .mutex = Qnil};
3290
3291 // Figure out whether we can autoload the named constant:
3292 VALUE autoload_const_value = rb_mutex_synchronize(autoload_mutex, autoload_load_needed, (VALUE)&arguments);
3293
3294 // This confirms whether autoloading is required or not:
3295 if (autoload_const_value == Qfalse) return autoload_const_value;
3296
3297 arguments.flag = ce->flag & (CONST_DEPRECATED | CONST_VISIBILITY_MASK);
3298
3299 // Only one thread will enter here at a time:
3300 VALUE result = rb_mutex_synchronize(arguments.mutex, autoload_try_load, (VALUE)&arguments);
3301
3302 // If you don't guard this value, it's possible for the autoload constant to
3303 // be freed by another thread which loads multiple constants, one of which
3304 // resolves to the constant this thread is trying to load, so proteect this
3305 // so that it is not freed until we are done with it in `autoload_try_load`:
3306 RB_GC_GUARD(autoload_const_value);
3307
3308 return result;
3309}
3310
3311VALUE
3313{
3314 return rb_autoload_at_p(mod, id, TRUE);
3315}
3316
3317VALUE
3318rb_autoload_at_p(VALUE mod, ID id, int recur)
3319{
3320 VALUE load;
3321 struct autoload_data *ele;
3322
3323 while (!autoload_defined_p(mod, id)) {
3324 if (!recur) return Qnil;
3325 mod = RCLASS_SUPER(mod);
3326 if (!mod) return Qnil;
3327 }
3328 load = check_autoload_required(mod, id, 0);
3329 if (!load) return Qnil;
3330 return (ele = get_autoload_data(load, 0)) ? ele->feature : Qnil;
3331}
3332
3333void
3334rb_const_warn_if_deprecated(const rb_const_entry_t *ce, VALUE klass, ID id)
3335{
3336 if (RB_CONST_DEPRECATED_P(ce) &&
3337 rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) {
3338 if (klass == rb_cObject) {
3339 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "constant ::%"PRIsVALUE" is deprecated", QUOTE_ID(id));
3340 }
3341 else {
3342 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "constant %"PRIsVALUE"::%"PRIsVALUE" is deprecated",
3343 rb_class_name(klass), QUOTE_ID(id));
3344 }
3345 }
3346}
3347
3348static VALUE
3349rb_const_get_0(VALUE klass, ID id, int exclude, int recurse, int visibility)
3350{
3351 VALUE c = rb_const_search(klass, id, exclude, recurse, visibility);
3352 if (!UNDEF_P(c)) {
3353 if (UNLIKELY(!rb_ractor_main_p())) {
3354 if (!rb_ractor_shareable_p(c)) {
3355 rb_raise(rb_eRactorIsolationError, "can not access non-shareable objects in constant %"PRIsVALUE"::%s by non-main Ractor.", rb_class_path(klass), rb_id2name(id));
3356 }
3357 }
3358 return c;
3359 }
3360 return rb_const_missing(klass, ID2SYM(id));
3361}
3362
3363static VALUE
3364rb_const_search_from(VALUE klass, ID id, int exclude, int recurse, int visibility)
3365{
3366 VALUE value, current;
3367 bool first_iteration = true;
3368
3369 for (current = klass;
3370 RTEST(current);
3371 current = RCLASS_SUPER(current), first_iteration = false) {
3372 VALUE tmp;
3373 VALUE am = 0;
3374 rb_const_entry_t *ce;
3375
3376 if (!first_iteration && RCLASS_ORIGIN(current) != current) {
3377 // This item in the super chain has an origin iclass
3378 // that comes later in the chain. Skip this item so
3379 // prepended modules take precedence.
3380 continue;
3381 }
3382
3383 // Do lookup in original class or module in case we are at an origin
3384 // iclass in the chain.
3385 tmp = current;
3386 if (BUILTIN_TYPE(tmp) == T_ICLASS) tmp = RBASIC(tmp)->klass;
3387
3388 // Do the lookup. Loop in case of autoload.
3389 while ((ce = rb_const_lookup(tmp, id))) {
3390 if (visibility && RB_CONST_PRIVATE_P(ce)) {
3391 GET_EC()->private_const_reference = tmp;
3392 return Qundef;
3393 }
3394 rb_const_warn_if_deprecated(ce, tmp, id);
3395 value = ce->value;
3396 if (UNDEF_P(value)) {
3397 struct autoload_const *ac;
3398 if (am == tmp) break;
3399 am = tmp;
3400 ac = autoloading_const_entry(tmp, id);
3401 if (ac) return ac->value;
3402 rb_autoload_load(tmp, id);
3403 continue;
3404 }
3405 if (exclude && tmp == rb_cObject) {
3406 goto not_found;
3407 }
3408 return value;
3409 }
3410 if (!recurse) break;
3411 }
3412
3413 not_found:
3414 GET_EC()->private_const_reference = 0;
3415 return Qundef;
3416}
3417
3418static VALUE
3419rb_const_search(VALUE klass, ID id, int exclude, int recurse, int visibility)
3420{
3421 VALUE value;
3422
3423 if (klass == rb_cObject) exclude = FALSE;
3424 value = rb_const_search_from(klass, id, exclude, recurse, visibility);
3425 if (!UNDEF_P(value)) return value;
3426 if (exclude) return value;
3427 if (BUILTIN_TYPE(klass) != T_MODULE) return value;
3428 /* search global const too, if klass is a module */
3429 return rb_const_search_from(rb_cObject, id, FALSE, recurse, visibility);
3430}
3431
3432VALUE
3434{
3435 return rb_const_get_0(klass, id, TRUE, TRUE, FALSE);
3436}
3437
3438VALUE
3440{
3441 return rb_const_get_0(klass, id, FALSE, TRUE, FALSE);
3442}
3443
3444VALUE
3446{
3447 return rb_const_get_0(klass, id, TRUE, FALSE, FALSE);
3448}
3449
3450VALUE
3451rb_public_const_get_from(VALUE klass, ID id)
3452{
3453 return rb_const_get_0(klass, id, TRUE, TRUE, TRUE);
3454}
3455
3456VALUE
3457rb_public_const_get_at(VALUE klass, ID id)
3458{
3459 return rb_const_get_0(klass, id, TRUE, FALSE, TRUE);
3460}
3461
3462NORETURN(static void undefined_constant(VALUE mod, VALUE name));
3463static void
3464undefined_constant(VALUE mod, VALUE name)
3465{
3466 rb_name_err_raise("constant %2$s::%1$s not defined",
3467 mod, name);
3468}
3469
3470static VALUE
3471rb_const_location_from(VALUE klass, ID id, int exclude, int recurse, int visibility)
3472{
3473 while (RTEST(klass)) {
3474 rb_const_entry_t *ce;
3475
3476 while ((ce = rb_const_lookup(klass, id))) {
3477 if (visibility && RB_CONST_PRIVATE_P(ce)) {
3478 return Qnil;
3479 }
3480 if (exclude && klass == rb_cObject) {
3481 goto not_found;
3482 }
3483
3484 if (UNDEF_P(ce->value)) { // autoload
3485 VALUE autoload_const_value = autoload_data(klass, id);
3486 if (RTEST(autoload_const_value)) {
3488 struct autoload_data *autoload_data = get_autoload_data(autoload_const_value, &autoload_const);
3489
3490 if (!UNDEF_P(autoload_const->value) && RTEST(rb_mutex_owned_p(autoload_data->mutex))) {
3491 return rb_assoc_new(autoload_const->file, INT2NUM(autoload_const->line));
3492 }
3493 }
3494 }
3495
3496 if (NIL_P(ce->file)) return rb_ary_new();
3497 return rb_assoc_new(ce->file, INT2NUM(ce->line));
3498 }
3499 if (!recurse) break;
3500 klass = RCLASS_SUPER(klass);
3501 }
3502
3503 not_found:
3504 return Qnil;
3505}
3506
3507static VALUE
3508rb_const_location(VALUE klass, ID id, int exclude, int recurse, int visibility)
3509{
3510 VALUE loc;
3511
3512 if (klass == rb_cObject) exclude = FALSE;
3513 loc = rb_const_location_from(klass, id, exclude, recurse, visibility);
3514 if (!NIL_P(loc)) return loc;
3515 if (exclude) return loc;
3516 if (BUILTIN_TYPE(klass) != T_MODULE) return loc;
3517 /* search global const too, if klass is a module */
3518 return rb_const_location_from(rb_cObject, id, FALSE, recurse, visibility);
3519}
3520
3521VALUE
3522rb_const_source_location(VALUE klass, ID id)
3523{
3524 return rb_const_location(klass, id, FALSE, TRUE, FALSE);
3525}
3526
3527VALUE
3528rb_const_source_location_at(VALUE klass, ID id)
3529{
3530 return rb_const_location(klass, id, TRUE, FALSE, FALSE);
3531}
3532
3533/*
3534 * call-seq:
3535 * remove_const(sym) -> obj
3536 *
3537 * Removes the definition of the given constant, returning that
3538 * constant's previous value. If that constant referred to
3539 * a module, this will not change that module's name and can lead
3540 * to confusion.
3541 */
3542
3543VALUE
3545{
3546 const ID id = id_for_var(mod, name, a, constant);
3547
3548 if (!id) {
3549 undefined_constant(mod, name);
3550 }
3551 return rb_const_remove(mod, id);
3552}
3553
3554static rb_const_entry_t * const_lookup(struct rb_id_table *tbl, ID id);
3555
3556VALUE
3558{
3559 VALUE val;
3560 rb_const_entry_t *ce;
3561
3562 rb_check_frozen(mod);
3563
3564 ce = rb_const_lookup(mod, id);
3565
3566 if (!ce) {
3567 if (rb_const_defined_at(mod, id)) {
3568 rb_name_err_raise("cannot remove %2$s::%1$s", mod, ID2SYM(id));
3569 }
3570
3571 undefined_constant(mod, ID2SYM(id));
3572 }
3573
3574 VALUE writable_ce = 0;
3575 if (rb_id_table_lookup(RCLASS_WRITABLE_CONST_TBL(mod), id, &writable_ce)) {
3576 rb_id_table_delete(RCLASS_WRITABLE_CONST_TBL(mod), id);
3577 if ((rb_const_entry_t *)writable_ce != ce) {
3578 xfree((rb_const_entry_t *)writable_ce);
3579 }
3580 }
3581
3582 rb_const_warn_if_deprecated(ce, mod, id);
3584
3585 val = ce->value;
3586
3587 if (UNDEF_P(val)) {
3588 autoload_delete(mod, id);
3589 val = Qnil;
3590 }
3591
3592 if (ce != const_lookup(RCLASS_PRIME_CONST_TBL(mod), id)) {
3593 ruby_xfree(ce);
3594 }
3595 // else - skip free'ing the ce because it still exists in the prime classext
3596
3597 return val;
3598}
3599
3600static int
3601cv_i_update(st_data_t *k, st_data_t *v, st_data_t a, int existing)
3602{
3603 if (existing) return ST_STOP;
3604 *v = a;
3605 return ST_CONTINUE;
3606}
3607
3608static enum rb_id_table_iterator_result
3609sv_i(ID key, VALUE v, void *a)
3610{
3612 st_table *tbl = a;
3613
3614 if (rb_is_const_id(key)) {
3615 st_update(tbl, (st_data_t)key, cv_i_update, (st_data_t)ce);
3616 }
3617 return ID_TABLE_CONTINUE;
3618}
3619
3620static enum rb_id_table_iterator_result
3621rb_local_constants_i(ID const_name, VALUE const_value, void *ary)
3622{
3623 if (rb_is_const_id(const_name) && !RB_CONST_PRIVATE_P((rb_const_entry_t *)const_value)) {
3624 rb_ary_push((VALUE)ary, ID2SYM(const_name));
3625 }
3626 return ID_TABLE_CONTINUE;
3627}
3628
3629static VALUE
3630rb_local_constants(VALUE mod)
3631{
3632 struct rb_id_table *tbl = RCLASS_CONST_TBL(mod);
3633 VALUE ary;
3634
3635 if (!tbl) return rb_ary_new2(0);
3636
3637 RB_VM_LOCKING() {
3638 ary = rb_ary_new2(rb_id_table_size(tbl));
3639 rb_id_table_foreach(tbl, rb_local_constants_i, (void *)ary);
3640 }
3641
3642 return ary;
3643}
3644
3645void*
3646rb_mod_const_at(VALUE mod, void *data)
3647{
3648 st_table *tbl = data;
3649 if (!tbl) {
3650 tbl = st_init_numtable();
3651 }
3652 if (RCLASS_CONST_TBL(mod)) {
3653 RB_VM_LOCKING() {
3654 rb_id_table_foreach(RCLASS_CONST_TBL(mod), sv_i, tbl);
3655 }
3656 }
3657 return tbl;
3658}
3659
3660void*
3661rb_mod_const_of(VALUE mod, void *data)
3662{
3663 VALUE tmp = mod;
3664 for (;;) {
3665 data = rb_mod_const_at(tmp, data);
3666 tmp = RCLASS_SUPER(tmp);
3667 if (!tmp) break;
3668 if (tmp == rb_cObject && mod != rb_cObject) break;
3669 }
3670 return data;
3671}
3672
3673static int
3674list_i(st_data_t key, st_data_t value, VALUE ary)
3675{
3676 ID sym = (ID)key;
3677 rb_const_entry_t *ce = (rb_const_entry_t *)value;
3678 if (RB_CONST_PUBLIC_P(ce)) rb_ary_push(ary, ID2SYM(sym));
3679 return ST_CONTINUE;
3680}
3681
3682VALUE
3683rb_const_list(void *data)
3684{
3685 st_table *tbl = data;
3686 VALUE ary;
3687
3688 if (!tbl) return rb_ary_new2(0);
3689 ary = rb_ary_new2(tbl->num_entries);
3690 st_foreach_safe(tbl, list_i, ary);
3691 st_free_table(tbl);
3692
3693 return ary;
3694}
3695
3696/*
3697 * call-seq:
3698 * mod.constants(inherit=true) -> array
3699 *
3700 * Returns an array of the names of the constants accessible in
3701 * <i>mod</i>. This includes the names of constants in any included
3702 * modules (example at start of section), unless the <i>inherit</i>
3703 * parameter is set to <code>false</code>.
3704 *
3705 * The implementation makes no guarantees about the order in which the
3706 * constants are yielded.
3707 *
3708 * IO.constants.include?(:SYNC) #=> true
3709 * IO.constants(false).include?(:SYNC) #=> false
3710 *
3711 * Also see Module#const_defined?.
3712 */
3713
3714VALUE
3715rb_mod_constants(int argc, const VALUE *argv, VALUE mod)
3716{
3717 bool inherit = true;
3718
3719 if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]);
3720
3721 if (inherit) {
3722 return rb_const_list(rb_mod_const_of(mod, 0));
3723 }
3724 else {
3725 return rb_local_constants(mod);
3726 }
3727}
3728
3729static int
3730rb_const_defined_0(VALUE klass, ID id, int exclude, int recurse, int visibility)
3731{
3732 VALUE tmp;
3733 int mod_retry = 0;
3734 rb_const_entry_t *ce;
3735
3736 tmp = klass;
3737 retry:
3738 while (tmp) {
3739 if ((ce = rb_const_lookup(tmp, id))) {
3740 if (visibility && RB_CONST_PRIVATE_P(ce)) {
3741 return (int)Qfalse;
3742 }
3743 if (UNDEF_P(ce->value) && !check_autoload_required(tmp, id, 0) &&
3744 !rb_autoloading_value(tmp, id, NULL, NULL))
3745 return (int)Qfalse;
3746
3747 if (exclude && tmp == rb_cObject && klass != rb_cObject) {
3748 return (int)Qfalse;
3749 }
3750
3751 return (int)Qtrue;
3752 }
3753 if (!recurse) break;
3754 tmp = RCLASS_SUPER(tmp);
3755 }
3756 if (!exclude && !mod_retry && BUILTIN_TYPE(klass) == T_MODULE) {
3757 mod_retry = 1;
3758 tmp = rb_cObject;
3759 goto retry;
3760 }
3761 return (int)Qfalse;
3762}
3763
3764int
3766{
3767 return rb_const_defined_0(klass, id, TRUE, TRUE, FALSE);
3768}
3769
3770int
3772{
3773 return rb_const_defined_0(klass, id, FALSE, TRUE, FALSE);
3774}
3775
3776int
3778{
3779 return rb_const_defined_0(klass, id, TRUE, FALSE, FALSE);
3780}
3781
3782int
3783rb_public_const_defined_from(VALUE klass, ID id)
3784{
3785 return rb_const_defined_0(klass, id, TRUE, TRUE, TRUE);
3786}
3787
3788static void
3789check_before_mod_set(VALUE klass, ID id, VALUE val, const char *dest)
3790{
3791 rb_check_frozen(klass);
3792}
3793
3794static void set_namespace_path(VALUE named_namespace, VALUE name);
3795
3796static enum rb_id_table_iterator_result
3797set_namespace_path_i(ID id, VALUE v, void *payload)
3798{
3800 VALUE value = ce->value;
3801 VALUE parental_path = *((VALUE *) payload);
3802 if (!rb_is_const_id(id) || !rb_namespace_p(value)) {
3803 return ID_TABLE_CONTINUE;
3804 }
3805
3806 bool has_permanent_classpath;
3807 classname(value, &has_permanent_classpath);
3808 if (has_permanent_classpath) {
3809 return ID_TABLE_CONTINUE;
3810 }
3811 set_namespace_path(value, build_const_path(parental_path, id));
3812
3813 if (!RCLASS_PERMANENT_CLASSPATH_P(value)) {
3814 RCLASS_WRITE_CLASSPATH(value, 0, false);
3815 }
3816
3817 return ID_TABLE_CONTINUE;
3818}
3819
3820/*
3821 * Assign permanent classpaths to all namespaces that are directly or indirectly
3822 * nested under +named_namespace+. +named_namespace+ must have a permanent
3823 * classpath.
3824 */
3825static void
3826set_namespace_path(VALUE named_namespace, VALUE namespace_path)
3827{
3828 struct rb_id_table *const_table = RCLASS_CONST_TBL(named_namespace);
3829 RB_OBJ_SET_SHAREABLE(namespace_path);
3830
3831 RB_VM_LOCKING() {
3832 RCLASS_WRITE_CLASSPATH(named_namespace, namespace_path, true);
3833
3834 if (const_table) {
3835 rb_id_table_foreach(const_table, set_namespace_path_i, &namespace_path);
3836 }
3837 }
3838}
3839
3840static void
3841const_added(VALUE klass, ID const_name)
3842{
3843 if (GET_VM()->running) {
3844 VALUE name = ID2SYM(const_name);
3845 rb_funcallv(klass, idConst_added, 1, &name);
3846 }
3847}
3848
3849static void
3850const_set(VALUE klass, ID id, VALUE val)
3851{
3852 rb_const_entry_t *ce;
3853
3854 if (NIL_P(klass)) {
3855 rb_raise(rb_eTypeError, "no class/module to define constant %"PRIsVALUE"",
3856 QUOTE_ID(id));
3857 }
3858
3859 if (!rb_ractor_main_p() && !rb_ractor_shareable_p(val)) {
3860 rb_raise(rb_eRactorIsolationError, "can not set constants with non-shareable objects by non-main Ractors");
3861 }
3862
3863 check_before_mod_set(klass, id, val, "constant");
3864
3865 RB_VM_LOCKING() {
3866 struct rb_id_table *tbl = RCLASS_WRITABLE_CONST_TBL(klass);
3867 if (!tbl) {
3868 tbl = rb_id_table_create(0);
3869 RCLASS_WRITE_CONST_TBL(klass, tbl, false);
3872 rb_id_table_insert(tbl, id, (VALUE)ce);
3873 setup_const_entry(ce, klass, val, CONST_PUBLIC);
3874 }
3875 else {
3876 struct autoload_const ac = {
3877 .module = klass, .name = id,
3878 .value = val, .flag = CONST_PUBLIC,
3879 /* fill the rest with 0 */
3880 };
3881 ac.file = rb_source_location(&ac.line);
3882 const_tbl_update(&ac, false);
3883 }
3884 }
3885
3886 /*
3887 * Resolve and cache class name immediately to resolve ambiguity
3888 * and avoid order-dependency on const_tbl
3889 */
3890 if (rb_cObject && rb_namespace_p(val)) {
3891 bool val_path_permanent;
3892 VALUE val_path = classname(val, &val_path_permanent);
3893 if (NIL_P(val_path) || !val_path_permanent) {
3894 if (klass == rb_cObject) {
3895 set_namespace_path(val, rb_id2str(id));
3896 }
3897 else {
3898 bool parental_path_permanent;
3899 VALUE parental_path = classname(klass, &parental_path_permanent);
3900 if (NIL_P(parental_path)) {
3901 bool throwaway;
3902 parental_path = rb_tmp_class_path(klass, &throwaway, make_temporary_path);
3903 }
3904 if (parental_path_permanent && !val_path_permanent) {
3905 set_namespace_path(val, build_const_path(parental_path, id));
3906 }
3907 else if (!parental_path_permanent && NIL_P(val_path)) {
3908 VALUE path = build_const_path(parental_path, id);
3909 RCLASS_SET_CLASSPATH(val, path, false);
3910 }
3911 }
3912 }
3913 }
3914}
3915
3916void
3918{
3919 const_set(klass, id, val);
3920 const_added(klass, id);
3921}
3922
3923static VALUE
3924autoload_const_value_for_named_constant(VALUE module, ID name, struct autoload_const **autoload_const_pointer)
3925{
3926 VALUE autoload_const_value = autoload_data(module, name);
3927 if (!autoload_const_value) return Qfalse;
3928
3929 struct autoload_data *autoload_data = get_autoload_data(autoload_const_value, autoload_const_pointer);
3930 if (!autoload_data) return Qfalse;
3931
3932 /* for autoloading thread, keep the defined value to autoloading storage */
3933 if (autoload_by_current(autoload_data)) {
3934 return autoload_const_value;
3935 }
3936
3937 return Qfalse;
3938}
3939
3940static void
3941const_tbl_update(struct autoload_const *ac, int autoload_force)
3942{
3943 VALUE value;
3944 VALUE klass = ac->module;
3945 VALUE val = ac->value;
3946 ID id = ac->name;
3947 struct rb_id_table *tbl = RCLASS_CONST_TBL(klass);
3948 rb_const_flag_t visibility = ac->flag;
3949 rb_const_entry_t *ce;
3950
3951 if (rb_id_table_lookup(tbl, id, &value)) {
3952 ce = (rb_const_entry_t *)value;
3953 if (UNDEF_P(ce->value)) {
3954 RUBY_ASSERT_CRITICAL_SECTION_ENTER();
3955 VALUE file = ac->file;
3956 int line = ac->line;
3957 VALUE autoload_const_value = autoload_const_value_for_named_constant(klass, id, &ac);
3958
3959 if (!autoload_force && autoload_const_value) {
3961
3962 RB_OBJ_WRITE(autoload_const_value, &ac->value, val);
3963 RB_OBJ_WRITE(autoload_const_value, &ac->file, rb_source_location(&ac->line));
3964 }
3965 else {
3966 /* otherwise autoloaded constant, allow to override */
3967 autoload_delete(klass, id);
3968 ce->flag = visibility;
3969 RB_OBJ_WRITE(klass, &ce->value, val);
3970 RB_OBJ_WRITE(klass, &ce->file, file);
3971 ce->line = line;
3972 }
3973 RUBY_ASSERT_CRITICAL_SECTION_LEAVE();
3974 return;
3975 }
3976 else {
3977 VALUE name = QUOTE_ID(id);
3978 visibility = ce->flag;
3979 if (klass == rb_cObject)
3980 rb_warn("already initialized constant %"PRIsVALUE"", name);
3981 else
3982 rb_warn("already initialized constant %"PRIsVALUE"::%"PRIsVALUE"",
3983 rb_class_name(klass), name);
3984 if (!NIL_P(ce->file) && ce->line) {
3985 rb_compile_warn(RSTRING_PTR(ce->file), ce->line,
3986 "previous definition of %"PRIsVALUE" was here", name);
3987 }
3988 }
3990 setup_const_entry(ce, klass, val, visibility);
3991 }
3992 else {
3993 tbl = RCLASS_WRITABLE_CONST_TBL(klass);
3995
3997 rb_id_table_insert(tbl, id, (VALUE)ce);
3998 setup_const_entry(ce, klass, val, visibility);
3999 }
4000}
4001
4002static void
4003setup_const_entry(rb_const_entry_t *ce, VALUE klass, VALUE val,
4004 rb_const_flag_t visibility)
4005{
4006 ce->flag = visibility;
4007 RB_OBJ_WRITE(klass, &ce->value, val);
4008 RB_OBJ_WRITE(klass, &ce->file, rb_source_location(&ce->line));
4009}
4010
4011void
4012rb_define_const(VALUE klass, const char *name, VALUE val)
4013{
4014 ID id = rb_intern(name);
4015
4016 if (!rb_is_const_id(id)) {
4017 rb_warn("rb_define_const: invalid name '%s' for constant", name);
4018 }
4019 if (!RB_SPECIAL_CONST_P(val)) {
4020 rb_vm_register_global_object(val);
4021 }
4022 rb_const_set(klass, id, val);
4023}
4024
4025void
4026rb_define_global_const(const char *name, VALUE val)
4027{
4028 rb_define_const(rb_cObject, name, val);
4029}
4030
4031static void
4032set_const_visibility(VALUE mod, int argc, const VALUE *argv,
4033 rb_const_flag_t flag, rb_const_flag_t mask)
4034{
4035 int i;
4036 rb_const_entry_t *ce;
4037 ID id;
4038
4040 if (argc == 0) {
4041 rb_warning("%"PRIsVALUE" with no argument is just ignored",
4042 QUOTE_ID(rb_frame_callee()));
4043 return;
4044 }
4045
4046 for (i = 0; i < argc; i++) {
4047 struct autoload_const *ac;
4048 VALUE val = argv[i];
4049 id = rb_check_id(&val);
4050 if (!id) {
4051 undefined_constant(mod, val);
4052 }
4053 if ((ce = rb_const_lookup(mod, id))) {
4054 ce->flag &= ~mask;
4055 ce->flag |= flag;
4056 if (UNDEF_P(ce->value)) {
4057 if (autoload_const_value_for_named_constant(mod, id, &ac)) {
4058 ac->flag &= ~mask;
4059 ac->flag |= flag;
4060 }
4061 }
4063 }
4064 else {
4065 undefined_constant(mod, ID2SYM(id));
4066 }
4067 }
4068}
4069
4070void
4071rb_deprecate_constant(VALUE mod, const char *name)
4072{
4073 rb_const_entry_t *ce;
4074 ID id;
4075 long len = strlen(name);
4076
4078 if (!(id = rb_check_id_cstr(name, len, NULL))) {
4079 undefined_constant(mod, rb_fstring_new(name, len));
4080 }
4081 if (!(ce = rb_const_lookup(mod, id))) {
4082 undefined_constant(mod, ID2SYM(id));
4083 }
4084 ce->flag |= CONST_DEPRECATED;
4085}
4086
4087/*
4088 * call-seq:
4089 * mod.private_constant(symbol, ...) => mod
4090 *
4091 * Makes a list of existing constants private.
4092 */
4093
4094VALUE
4095rb_mod_private_constant(int argc, const VALUE *argv, VALUE obj)
4096{
4097 set_const_visibility(obj, argc, argv, CONST_PRIVATE, CONST_VISIBILITY_MASK);
4098 return obj;
4099}
4100
4101/*
4102 * call-seq:
4103 * mod.public_constant(symbol, ...) => mod
4104 *
4105 * Makes a list of existing constants public.
4106 */
4107
4108VALUE
4109rb_mod_public_constant(int argc, const VALUE *argv, VALUE obj)
4110{
4111 set_const_visibility(obj, argc, argv, CONST_PUBLIC, CONST_VISIBILITY_MASK);
4112 return obj;
4113}
4114
4115/*
4116 * call-seq:
4117 * mod.deprecate_constant(symbol, ...) => mod
4118 *
4119 * Makes a list of existing constants deprecated. Attempt
4120 * to refer to them will produce a warning.
4121 *
4122 * module HTTP
4123 * NotFound = Exception.new
4124 * NOT_FOUND = NotFound # previous version of the library used this name
4125 *
4126 * deprecate_constant :NOT_FOUND
4127 * end
4128 *
4129 * HTTP::NOT_FOUND
4130 * # warning: constant HTTP::NOT_FOUND is deprecated
4131 *
4132 */
4133
4134VALUE
4135rb_mod_deprecate_constant(int argc, const VALUE *argv, VALUE obj)
4136{
4137 set_const_visibility(obj, argc, argv, CONST_DEPRECATED, CONST_DEPRECATED);
4138 return obj;
4139}
4140
4141static VALUE
4142original_module(VALUE c)
4143{
4144 if (RB_TYPE_P(c, T_ICLASS))
4145 return RBASIC(c)->klass;
4146 return c;
4147}
4148
4149static int
4150cvar_lookup_at(VALUE klass, ID id, st_data_t *v)
4151{
4152 if (RB_TYPE_P(klass, T_ICLASS)) {
4153 if (RICLASS_IS_ORIGIN_P(klass)) {
4154 return 0;
4155 }
4156 else {
4157 // check the original module
4158 klass = RBASIC(klass)->klass;
4159 }
4160 }
4161
4162 VALUE n = rb_ivar_lookup(klass, id, Qundef);
4163 if (UNDEF_P(n)) return 0;
4164
4165 if (v) *v = n;
4166 return 1;
4167}
4168
4169static VALUE
4170cvar_front_klass(VALUE klass)
4171{
4172 if (RCLASS_SINGLETON_P(klass)) {
4173 VALUE obj = RCLASS_ATTACHED_OBJECT(klass);
4174 if (rb_namespace_p(obj)) {
4175 return obj;
4176 }
4177 }
4178 return RCLASS_SUPER(klass);
4179}
4180
4181static void
4182cvar_overtaken(VALUE front, VALUE target, ID id)
4183{
4184 if (front && target != front) {
4185 if (original_module(front) != original_module(target)) {
4186 rb_raise(rb_eRuntimeError,
4187 "class variable % "PRIsVALUE" of %"PRIsVALUE" is overtaken by %"PRIsVALUE"",
4188 ID2SYM(id), rb_class_name(original_module(front)),
4189 rb_class_name(original_module(target)));
4190 }
4191 if (BUILTIN_TYPE(front) == T_CLASS) {
4192 rb_ivar_delete(front, id, Qundef);
4193 }
4194 }
4195}
4196
4197#define CVAR_FOREACH_ANCESTORS(klass, v, r) \
4198 for (klass = cvar_front_klass(klass); klass; klass = RCLASS_SUPER(klass)) { \
4199 if (cvar_lookup_at(klass, id, (v))) { \
4200 r; \
4201 } \
4202 }
4203
4204#define CVAR_LOOKUP(v,r) do {\
4205 CVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(); \
4206 if (cvar_lookup_at(klass, id, (v))) {r;}\
4207 CVAR_FOREACH_ANCESTORS(klass, v, r);\
4208} while(0)
4209
4210static VALUE
4211find_cvar(VALUE klass, VALUE * front, VALUE * target, ID id)
4212{
4213 VALUE v = Qundef;
4214 CVAR_LOOKUP(&v, {
4215 if (!*front) {
4216 *front = klass;
4217 }
4218 *target = klass;
4219 });
4220
4221 return v;
4222}
4223
4224static void
4225check_for_cvar_table(VALUE subclass, VALUE key)
4226{
4227 // Must not check ivar on ICLASS
4228 if (!RB_TYPE_P(subclass, T_ICLASS) && RTEST(rb_ivar_defined(subclass, key))) {
4229 RB_DEBUG_COUNTER_INC(cvar_class_invalidate);
4230 ruby_vm_global_cvar_state++;
4231 return;
4232 }
4233
4234 rb_class_foreach_subclass(subclass, check_for_cvar_table, key);
4235}
4236
4237void
4238rb_cvar_set(VALUE klass, ID id, VALUE val)
4239{
4240 VALUE tmp, front = 0, target = 0;
4241
4242 tmp = klass;
4243 CVAR_LOOKUP(0, {if (!front) front = klass; target = klass;});
4244 if (target) {
4245 cvar_overtaken(front, target, id);
4246 }
4247 else {
4248 target = tmp;
4249 }
4250
4251 if (RB_TYPE_P(target, T_ICLASS)) {
4252 target = RBASIC(target)->klass;
4253 }
4254 check_before_mod_set(target, id, val, "class variable");
4255
4256 bool new_cvar = rb_class_ivar_set(target, id, val);
4257
4258 struct rb_id_table *rb_cvc_tbl = RCLASS_WRITABLE_CVC_TBL(target);
4259
4260 if (!rb_cvc_tbl) {
4261 rb_cvc_tbl = rb_id_table_create(2);
4262 RCLASS_WRITE_CVC_TBL(target, rb_cvc_tbl);
4263 }
4264
4265 struct rb_cvar_class_tbl_entry *ent;
4266 VALUE ent_data;
4267
4268 if (!rb_id_table_lookup(rb_cvc_tbl, id, &ent_data)) {
4269 ent = ALLOC(struct rb_cvar_class_tbl_entry);
4270 ent->class_value = target;
4271 ent->global_cvar_state = GET_GLOBAL_CVAR_STATE();
4272 ent->cref = 0;
4273 rb_id_table_insert(rb_cvc_tbl, id, (VALUE)ent);
4274 RB_DEBUG_COUNTER_INC(cvar_inline_miss);
4275 }
4276 else {
4277 ent = (void *)ent_data;
4278 ent->global_cvar_state = GET_GLOBAL_CVAR_STATE();
4279 }
4280
4281 // Break the cvar cache if this is a new class variable
4282 // and target is a module or a subclass with the same
4283 // cvar in this lookup.
4284 if (new_cvar) {
4285 if (RB_TYPE_P(target, T_CLASS)) {
4286 if (RCLASS_SUBCLASSES_FIRST(target)) {
4287 rb_class_foreach_subclass(target, check_for_cvar_table, id);
4288 }
4289 }
4290 }
4291}
4292
4293VALUE
4294rb_cvar_find(VALUE klass, ID id, VALUE *front)
4295{
4296 VALUE target = 0;
4297 VALUE value;
4298
4299 value = find_cvar(klass, front, &target, id);
4300 if (!target) {
4301 rb_name_err_raise("uninitialized class variable %1$s in %2$s",
4302 klass, ID2SYM(id));
4303 }
4304 cvar_overtaken(*front, target, id);
4305 return (VALUE)value;
4306}
4307
4308VALUE
4310{
4311 VALUE front = 0;
4312 return rb_cvar_find(klass, id, &front);
4313}
4314
4315VALUE
4317{
4318 if (!klass) return Qfalse;
4319 CVAR_LOOKUP(0,return Qtrue);
4320 return Qfalse;
4321}
4322
4323static ID
4324cv_intern(VALUE klass, const char *name)
4325{
4326 ID id = rb_intern(name);
4327 if (!rb_is_class_id(id)) {
4328 rb_name_err_raise("wrong class variable name %1$s",
4329 klass, rb_str_new_cstr(name));
4330 }
4331 return id;
4332}
4333
4334void
4335rb_cv_set(VALUE klass, const char *name, VALUE val)
4336{
4337 ID id = cv_intern(klass, name);
4338 rb_cvar_set(klass, id, val);
4339}
4340
4341VALUE
4342rb_cv_get(VALUE klass, const char *name)
4343{
4344 ID id = cv_intern(klass, name);
4345 return rb_cvar_get(klass, id);
4346}
4347
4348void
4349rb_define_class_variable(VALUE klass, const char *name, VALUE val)
4350{
4351 rb_cv_set(klass, name, val);
4352}
4353
4354static int
4355cv_i(ID key, VALUE v, st_data_t a)
4356{
4357 st_table *tbl = (st_table *)a;
4358
4359 if (rb_is_class_id(key)) {
4360 st_update(tbl, (st_data_t)key, cv_i_update, 0);
4361 }
4362 return ST_CONTINUE;
4363}
4364
4365static void*
4366mod_cvar_at(VALUE mod, void *data)
4367{
4368 st_table *tbl = data;
4369 if (!tbl) {
4370 tbl = st_init_numtable();
4371 }
4372 mod = original_module(mod);
4373
4374 rb_ivar_foreach(mod, cv_i, (st_data_t)tbl);
4375 return tbl;
4376}
4377
4378static void*
4379mod_cvar_of(VALUE mod, void *data)
4380{
4381 VALUE tmp = mod;
4382 if (RCLASS_SINGLETON_P(mod)) {
4383 if (rb_namespace_p(RCLASS_ATTACHED_OBJECT(mod))) {
4384 data = mod_cvar_at(tmp, data);
4385 tmp = cvar_front_klass(tmp);
4386 }
4387 }
4388 for (;;) {
4389 data = mod_cvar_at(tmp, data);
4390 tmp = RCLASS_SUPER(tmp);
4391 if (!tmp) break;
4392 }
4393 return data;
4394}
4395
4396static int
4397cv_list_i(st_data_t key, st_data_t value, VALUE ary)
4398{
4399 ID sym = (ID)key;
4400 rb_ary_push(ary, ID2SYM(sym));
4401 return ST_CONTINUE;
4402}
4403
4404static VALUE
4405cvar_list(void *data)
4406{
4407 st_table *tbl = data;
4408 VALUE ary;
4409
4410 if (!tbl) return rb_ary_new2(0);
4411 ary = rb_ary_new2(tbl->num_entries);
4412 st_foreach_safe(tbl, cv_list_i, ary);
4413 st_free_table(tbl);
4414
4415 return ary;
4416}
4417
4418/*
4419 * call-seq:
4420 * mod.class_variables(inherit=true) -> array
4421 *
4422 * Returns an array of the names of class variables in <i>mod</i>.
4423 * This includes the names of class variables in any included
4424 * modules, unless the <i>inherit</i> parameter is set to
4425 * <code>false</code>.
4426 *
4427 * class One
4428 * @@var1 = 1
4429 * end
4430 * class Two < One
4431 * @@var2 = 2
4432 * end
4433 * One.class_variables #=> [:@@var1]
4434 * Two.class_variables #=> [:@@var2, :@@var1]
4435 * Two.class_variables(false) #=> [:@@var2]
4436 */
4437
4438VALUE
4439rb_mod_class_variables(int argc, const VALUE *argv, VALUE mod)
4440{
4441 bool inherit = true;
4442 st_table *tbl;
4443
4444 if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]);
4445 if (inherit) {
4446 tbl = mod_cvar_of(mod, 0);
4447 }
4448 else {
4449 tbl = mod_cvar_at(mod, 0);
4450 }
4451 return cvar_list(tbl);
4452}
4453
4454/*
4455 * call-seq:
4456 * remove_class_variable(sym) -> obj
4457 *
4458 * Removes the named class variable from the receiver, returning that
4459 * variable's value.
4460 *
4461 * class Example
4462 * @@var = 99
4463 * puts remove_class_variable(:@@var)
4464 * p(defined? @@var)
4465 * end
4466 *
4467 * <em>produces:</em>
4468 *
4469 * 99
4470 * nil
4471 */
4472
4473VALUE
4475{
4476 const ID id = id_for_var_message(mod, name, class, "wrong class variable name %1$s");
4477 st_data_t val;
4478
4479 if (!id) {
4480 goto not_defined;
4481 }
4482 rb_check_frozen(mod);
4483 val = rb_ivar_delete(mod, id, Qundef);
4484 if (!UNDEF_P(val)) {
4485 return (VALUE)val;
4486 }
4487 if (rb_cvar_defined(mod, id)) {
4488 rb_name_err_raise("cannot remove %1$s for %2$s", mod, ID2SYM(id));
4489 }
4490 not_defined:
4491 rb_name_err_raise("class variable %1$s not defined for %2$s",
4492 mod, name);
4494}
4495
4496VALUE
4497rb_iv_get(VALUE obj, const char *name)
4498{
4499 ID id = rb_check_id_cstr(name, strlen(name), rb_usascii_encoding());
4500
4501 if (!id) {
4502 return Qnil;
4503 }
4504 return rb_ivar_get(obj, id);
4505}
4506
4507VALUE
4508rb_iv_set(VALUE obj, const char *name, VALUE val)
4509{
4510 ID id = rb_intern(name);
4511
4512 return rb_ivar_set(obj, id, val);
4513}
4514
4515static attr_index_t
4516class_fields_ivar_set(VALUE klass, VALUE fields_obj, ID id, VALUE val, bool concurrent, VALUE *new_fields_obj, bool *new_ivar_out)
4517{
4518 const VALUE original_fields_obj = fields_obj;
4519 fields_obj = original_fields_obj ? original_fields_obj : rb_imemo_fields_new(klass, 1, true);
4520
4521 shape_id_t current_shape_id = RBASIC_SHAPE_ID(fields_obj);
4522 shape_id_t next_shape_id = current_shape_id; // for too_complex
4523 if (UNLIKELY(rb_shape_too_complex_p(current_shape_id))) {
4524 goto too_complex;
4525 }
4526
4527 bool new_ivar;
4528 next_shape_id = generic_shape_ivar(fields_obj, id, &new_ivar);
4529
4530 if (UNLIKELY(rb_shape_too_complex_p(next_shape_id))) {
4531 fields_obj = imemo_fields_complex_from_obj(klass, fields_obj, next_shape_id);
4532 goto too_complex;
4533 }
4534
4535 attr_index_t index = RSHAPE_INDEX(next_shape_id);
4536 if (new_ivar) {
4537 if (index >= RSHAPE_CAPACITY(current_shape_id)) {
4538 // We allocate a new fields_obj even when concurrency isn't a concern
4539 // so that we're embedded as long as possible.
4540 fields_obj = imemo_fields_copy_capa(klass, fields_obj, RSHAPE_CAPACITY(next_shape_id));
4541 }
4542 }
4543
4544 VALUE *fields = rb_imemo_fields_ptr(fields_obj);
4545
4546 if (concurrent && original_fields_obj == fields_obj) {
4547 // In the concurrent case, if we're mutating the existing
4548 // fields_obj, we must use an atomic write, because if we're
4549 // adding a new field, the shape_id must be written after the field
4550 // and if we're updating an existing field, we at least need a relaxed
4551 // write to avoid reaping.
4552 RB_OBJ_ATOMIC_WRITE(fields_obj, &fields[index], val);
4553 }
4554 else {
4555 RB_OBJ_WRITE(fields_obj, &fields[index], val);
4556 }
4557
4558 if (new_ivar) {
4559 RBASIC_SET_SHAPE_ID(fields_obj, next_shape_id);
4560 }
4561
4562 *new_fields_obj = fields_obj;
4563 *new_ivar_out = new_ivar;
4564 return index;
4565
4566too_complex:
4567 {
4568 if (concurrent && fields_obj == original_fields_obj) {
4569 // In multi-ractor case, we must always work on a copy because
4570 // even if the field already exist, inserting in a st_table may
4571 // cause a rebuild.
4572 fields_obj = rb_imemo_fields_clone(fields_obj);
4573 }
4574
4575 st_table *table = rb_imemo_fields_complex_tbl(fields_obj);
4576 new_ivar = !st_insert(table, (st_data_t)id, (st_data_t)val);
4577 RB_OBJ_WRITTEN(fields_obj, Qundef, val);
4578
4579 if (fields_obj != original_fields_obj) {
4580 RBASIC_SET_SHAPE_ID(fields_obj, next_shape_id);
4581 }
4582 }
4583
4584 *new_fields_obj = fields_obj;
4585 *new_ivar_out = new_ivar;
4586 return ATTR_INDEX_NOT_SET;
4587}
4588
4589static attr_index_t
4590class_ivar_set(VALUE obj, ID id, VALUE val, bool *new_ivar)
4591{
4592 rb_class_ensure_writable(obj);
4593
4594 const VALUE original_fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
4595 VALUE new_fields_obj = 0;
4596
4597 attr_index_t index = class_fields_ivar_set(obj, original_fields_obj, id, val, rb_multi_ractor_p(), &new_fields_obj, new_ivar);
4598
4599 if (new_fields_obj != original_fields_obj) {
4600 RCLASS_WRITABLE_SET_FIELDS_OBJ(obj, new_fields_obj);
4601 }
4602
4603 // TODO: What should we set as the T_CLASS shape_id?
4604 // In most case we can replicate the single `fields_obj` shape
4605 // but in namespaced case? Perhaps INVALID_SHAPE_ID?
4606 RBASIC_SET_SHAPE_ID(obj, RBASIC_SHAPE_ID(new_fields_obj));
4607 return index;
4608}
4609
4610bool
4611rb_class_ivar_set(VALUE obj, ID id, VALUE val)
4612{
4614 rb_check_frozen(obj);
4615
4616 bool new_ivar;
4617 class_ivar_set(obj, id, val, &new_ivar);
4618 return new_ivar;
4619}
4620
4621void
4622rb_fields_tbl_copy(VALUE dst, VALUE src)
4623{
4624 RUBY_ASSERT(rb_type(dst) == rb_type(src));
4626 RUBY_ASSERT(RSHAPE_TYPE_P(RBASIC_SHAPE_ID(dst), SHAPE_ROOT));
4627
4628 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(src);
4629 if (fields_obj) {
4630 RCLASS_WRITABLE_SET_FIELDS_OBJ(dst, rb_imemo_fields_clone(fields_obj));
4631 RBASIC_SET_SHAPE_ID(dst, RBASIC_SHAPE_ID(src));
4632 }
4633}
4634
4635static rb_const_entry_t *
4636const_lookup(struct rb_id_table *tbl, ID id)
4637{
4638 if (tbl) {
4639 VALUE val;
4640 bool r;
4641 RB_VM_LOCKING() {
4642 r = rb_id_table_lookup(tbl, id, &val);
4643 }
4644
4645 if (r) return (rb_const_entry_t *)val;
4646 }
4647 return NULL;
4648}
4649
4651rb_const_lookup(VALUE klass, ID id)
4652{
4653 return const_lookup(RCLASS_CONST_TBL(klass), id);
4654}
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define RUBY_EXTERN
Declaration of externally visible global variables.
Definition dllexport.h:45
static VALUE RB_OBJ_FROZEN_RAW(VALUE obj)
This is an implementation detail of RB_OBJ_FROZEN().
Definition fl_type.h:877
static bool RB_FL_ABLE(VALUE obj)
Checks if the object is flaggable.
Definition fl_type.h:440
static void RB_FL_SET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_SET().
Definition fl_type.h:600
void rb_obj_freeze_inline(VALUE obj)
Prevents further modifications to the given object.
Definition variable.c:1974
static void RB_FL_UNSET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_UNSET().
Definition fl_type.h:660
@ RUBY_FL_FREEZE
This flag has something to do with data immutability.
Definition fl_type.h:320
void rb_class_modify_check(VALUE klass)
Asserts that klass is not a frozen class.
Definition eval.c:421
void rb_freeze_singleton_class(VALUE x)
This is an implementation detail of RB_OBJ_FREEZE().
Definition class.c:2864
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:3237
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1674
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define FL_UNSET_RAW
Old name of RB_FL_UNSET_RAW.
Definition fl_type.h:133
#define FL_USER3
Old name of RUBY_FL_USER3.
Definition fl_type.h:73
#define REALLOC_N
Old name of RB_REALLOC_N.
Definition memory.h:403
#define ALLOC
Old name of RB_ALLOC.
Definition memory.h:400
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1682
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define T_IMEMO
Old name of RUBY_T_IMEMO.
Definition value_type.h:67
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#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 ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
#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 FL_USER2
Old name of RUBY_FL_USER2.
Definition fl_type.h:72
#define Qtrue
Old name of RUBY_Qtrue.
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_OBJECT
Old name of RUBY_T_OBJECT.
Definition value_type.h:75
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:405
#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 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
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:476
void rb_name_error(ID id, const char *fmt,...)
Raises an instance of rb_eNameError.
Definition error.c:2345
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
void rb_name_error_str(VALUE str, const char *fmt,...)
Identical to rb_name_error(), except it takes a VALUE instead of ID.
Definition error.c:2360
VALUE rb_eNameError
NameError exception.
Definition error.c:1436
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1429
void * rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
Identical to rb_typeddata_is_kind_of(), except it raises exceptions instead of returning false.
Definition error.c:1398
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
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_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:100
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:264
VALUE rb_cModule
Module class.
Definition object.c:62
VALUE rb_class_real(VALUE klass)
Finds a "real" class.
Definition object.c:255
size_t rb_obj_embedded_size(uint32_t fields_count)
Internal header for Object.
Definition object.c:94
#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.
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:1223
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1117
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
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
#define st_foreach_safe
Just another name of rb_st_foreach_safe.
Definition hash.h:51
int rb_feature_provided(const char *feature, const char **loading)
Identical to rb_provided(), except it additionally returns the "canonical" name of the loaded feature...
Definition load.c:676
VALUE rb_backref_get(void)
Queries the last match, or Regexp.last_match, or the $~.
Definition vm.c:2024
int rb_is_instance_id(ID id)
Classifies the given ID, then sees if it is an instance variable.
Definition symbol.c:1097
int rb_is_const_id(ID id)
Classifies the given ID, then sees if it is a constant.
Definition symbol.c:1079
int rb_is_class_id(ID id)
Classifies the given ID, then sees if it is a class variable.
Definition symbol.c:1085
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:847
VALUE rb_reg_nth_defined(int n, VALUE md)
Identical to rb_reg_nth_match(), except it just returns Boolean.
Definition re.c:1905
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:3795
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:3151
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1516
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:1994
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1513
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:937
VALUE rb_mutex_new(void)
Creates a mutex.
VALUE rb_mutex_synchronize(VALUE mutex, VALUE(*func)(VALUE arg), VALUE arg)
Obtains the lock, runs the passed function, and releases the lock when it completes.
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
VALUE rb_mod_remove_cvar(VALUE mod, VALUE name)
Resembles Module#remove_class_variable.
Definition variable.c:4474
VALUE rb_obj_instance_variables(VALUE obj)
Resembles Object#instance_variables.
Definition variable.c:2417
VALUE rb_f_untrace_var(int argc, const VALUE *argv)
Deletes the passed tracer from the passed global variable, or if omitted, deletes everything.
Definition variable.c:915
VALUE rb_const_get(VALUE space, ID name)
Identical to rb_const_defined(), except it returns the actual defined value.
Definition variable.c:3439
VALUE rb_const_list(void *)
This is another mysterious API that comes with no documents at all.
Definition variable.c:3683
VALUE rb_path2class(const char *path)
Resolves a Q::W::E::R-style path string to the actual class it points.
Definition variable.c:494
VALUE rb_autoload_p(VALUE space, ID name)
Queries if an autoload is defined at a point.
Definition variable.c:3312
void rb_set_class_path(VALUE klass, VALUE space, const char *name)
Names a class.
Definition variable.c:441
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:2013
VALUE rb_mod_remove_const(VALUE space, VALUE name)
Resembles Module#remove_const.
Definition variable.c:3544
VALUE rb_class_path_cached(VALUE mod)
Just another name of rb_mod_name.
Definition variable.c:389
VALUE rb_f_trace_var(int argc, const VALUE *argv)
Traces a global variable.
Definition variable.c:869
void rb_cvar_set(VALUE klass, ID name, VALUE val)
Assigns a value to a class variable.
Definition variable.c:4238
VALUE rb_cvar_get(VALUE klass, ID name)
Obtains a value from a class variable.
Definition variable.c:4309
VALUE rb_mod_constants(int argc, const VALUE *argv, VALUE recv)
Resembles Module#constants.
Definition variable.c:3715
VALUE rb_cvar_find(VALUE klass, ID name, VALUE *front)
Identical to rb_cvar_get(), except it takes additional "front" pointer.
Definition variable.c:4294
VALUE rb_path_to_class(VALUE path)
Identical to rb_path2class(), except it accepts the path as Ruby's string instead of C's.
Definition variable.c:449
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:1488
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:3917
VALUE rb_autoload_load(VALUE space, ID name)
Kicks the autoload procedure as if it was "touched".
Definition variable.c:3274
VALUE rb_mod_name(VALUE mod)
Queries the name of a module.
Definition variable.c:136
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:500
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:3445
void rb_set_class_path_string(VALUE klass, VALUE space, VALUE name)
Identical to rb_set_class_path(), except it accepts the name as Ruby's string instead of C's.
Definition variable.c:423
void rb_alias_variable(ID dst, ID src)
Aliases a global variable.
Definition variable.c:1153
void rb_define_class_variable(VALUE, const char *, VALUE)
Just another name of rb_cv_set.
Definition variable.c:4349
VALUE rb_obj_remove_instance_variable(VALUE obj, VALUE name)
Resembles Object#remove_instance_variable.
Definition variable.c:2471
void * rb_mod_const_of(VALUE, void *)
This is a variant of rb_mod_const_at().
Definition variable.c:3661
st_index_t rb_ivar_count(VALUE obj)
Number of instance variables defined on an object.
Definition variable.c:2329
void * rb_mod_const_at(VALUE, void *)
This API is mysterious.
Definition variable.c:3646
VALUE rb_const_remove(VALUE space, ID name)
Identical to rb_mod_remove_const(), except it takes the name as ID instead of VALUE.
Definition variable.c:3557
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:3433
VALUE rb_ivar_defined(VALUE obj, ID name)
Queries if the instance variable is defined at the object.
Definition variable.c:2092
VALUE rb_cv_get(VALUE klass, const char *name)
Identical to rb_cvar_get(), except it accepts C's string instead of ID.
Definition variable.c:4342
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:3777
void rb_cv_set(VALUE klass, const char *name, VALUE val)
Identical to rb_cvar_set(), except it accepts C's string instead of ID.
Definition variable.c:4335
VALUE rb_mod_class_variables(int argc, const VALUE *argv, VALUE recv)
Resembles Module#class_variables.
Definition variable.c:4439
VALUE rb_f_global_variables(void)
Queries the list of global variables.
Definition variable.c:1120
VALUE rb_cvar_defined(VALUE klass, ID name)
Queries if the given class has the given class variable.
Definition variable.c:4316
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:380
int rb_const_defined_from(VALUE space, ID name)
Identical to rb_const_defined(), except it returns false for private constants.
Definition variable.c:3765
int rb_const_defined(VALUE space, ID name)
Queries if the constant is defined at the namespace.
Definition variable.c:3771
void rb_free_generic_ivar(VALUE obj)
Frees the list of instance variables.
Definition variable.c:1292
const char * rb_sourcefile(void)
Resembles __FILE__.
Definition vm.c:2061
void rb_clear_constant_cache_for_id(ID id)
Clears the inline constant caches associated with a particular ID.
Definition vm_method.c:320
int rb_obj_respond_to(VALUE obj, ID mid, int private_p)
Identical to rb_respond_to(), except it additionally takes the visibility parameter.
Definition vm_method.c:3350
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:284
VALUE rb_id2sym(ID id)
Allocates an instance of rb_cSymbol that has the given id.
Definition symbol.c:974
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1133
ID rb_to_id(VALUE str)
Definition string.c:12494
rb_gvar_setter_t rb_gvar_var_setter
Definition variable.h:119
rb_gvar_marker_t rb_gvar_var_marker
Definition variable.h:128
void rb_define_global_const(const char *name, VALUE val)
Identical to rb_define_const(), except it defines that of "global", i.e.
Definition variable.c:4026
VALUE rb_gv_get(const char *name)
Obtains a global variable.
Definition variable.c:1078
void rb_define_variable(const char *name, VALUE *var)
"Shares" a global variable between Ruby and C.
Definition variable.c:840
void rb_gvar_marker_t(VALUE *var)
Type that represents a global variable marker function.
Definition variable.h:53
void rb_deprecate_constant(VALUE mod, const char *name)
Asserts that the given constant is deprecated.
Definition variable.c:4071
void rb_gvar_setter_t(VALUE val, ID id, VALUE *data)
Type that represents a global variable setter function.
Definition variable.h:46
rb_gvar_setter_t rb_gvar_val_setter
This is the setter function that backs global variables defined from a ruby script.
Definition variable.h:94
rb_gvar_marker_t rb_gvar_undef_marker
Definition variable.h:80
void rb_define_readonly_variable(const char *name, const VALUE *var)
Identical to rb_define_variable(), except it does not allow Ruby programs to assign values to such gl...
Definition variable.c:846
rb_gvar_setter_t rb_gvar_readonly_setter
This function just raises rb_eNameError.
Definition variable.h:135
rb_gvar_getter_t rb_gvar_undef_getter
Definition variable.h:62
VALUE rb_gv_set(const char *name, VALUE val)
Assigns to a global variable.
Definition variable.c:1033
rb_gvar_marker_t rb_gvar_val_marker
This is the setter function that backs global variables defined from a ruby script.
Definition variable.h:101
VALUE rb_gvar_getter_t(ID id, VALUE *data)
Type that represents a global variable getter function.
Definition variable.h:37
VALUE rb_iv_get(VALUE obj, const char *name)
Obtains an instance variable.
Definition variable.c:4497
rb_gvar_setter_t rb_gvar_undef_setter
Definition variable.h:71
rb_gvar_getter_t rb_gvar_val_getter
This is the getter function that backs global variables defined from a ruby script.
Definition variable.h:87
VALUE rb_iv_set(VALUE obj, const char *name, VALUE val)
Assigns to an instance variable.
Definition variable.c:4508
rb_gvar_getter_t rb_gvar_var_getter
Definition variable.h:110
int len
Length of the buffer.
Definition io.h:8
static bool rb_ractor_shareable_p(VALUE obj)
Queries if multiple Ractors can share the passed object or not.
Definition ractor.h:249
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:235
#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
#define MEMMOVE(p1, p2, type, n)
Handy macro to call memmove.
Definition memory.h:384
void rb_define_hooked_variable(const char *q, VALUE *w, type *e, void_type *r)
Define a function-backended global variable.
VALUE type(ANYARGS)
ANYARGS-ed function type.
void rb_define_virtual_variable(const char *q, type *w, void_type *e)
Define a function-backended global variable.
void rb_ivar_foreach(VALUE q, int_type *w, VALUE e)
Iteration over each instance variable of the object.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
void rb_copy_generic_ivar(VALUE clone, VALUE obj)
Copies the list of instance variables.
Definition variable.c:2215
#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:166
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
Definition rclass.h:44
#define ROBJECT(obj)
Convenient casting macro.
Definition robject.h:43
static VALUE * ROBJECT_FIELDS(VALUE obj)
Queries the instance variables.
Definition robject.h:128
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:409
static bool RTYPEDDATA_P(VALUE obj)
Checks whether the passed object is RTypedData or RData.
Definition rtypeddata.h:575
#define RTYPEDDATA_DATA(v)
Convenient getter macro.
Definition rtypeddata.h:103
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:461
#define RTYPEDDATA(obj)
Convenient casting macro.
Definition rtypeddata.h:95
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:508
const char * rb_class2name(VALUE klass)
Queries the name of the passed class.
Definition variable.c:506
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:515
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#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
C99 shim for <stdbool.h>
Internal header for Ruby Box.
Definition box.h:14
Definition constant.h:33
Definition class.h:72
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:208
Definition variable.c:539
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 enum ruby_value_type rb_type(VALUE obj)
Identical to RB_BUILTIN_TYPE(), except it can also accept special constants.
Definition value_type.h:225
static enum ruby_value_type RB_BUILTIN_TYPE(VALUE obj)
Queries the type of the object.
Definition value_type.h:182
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