Ruby 4.1.0dev (2026-04-04 revision 6ab9b22553ac802819aa1643a9ac9575e75d1286)
variable.c (6ab9b22553ac802819aa1643a9ac9575e75d1286)
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, VALUE *found_in);
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)") # => 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, NULL);
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 SIZED_FREE(trace);
554 trace = next;
555 }
556 SIZED_FREE(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 SIZED_FREE(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 SIZED_FREE(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 = NULL;
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 = NULL;
1045 struct rb_global_variable *var = NULL;
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
1198static void
1199CVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(VALUE klass, ID id)
1200{
1201 if (UNLIKELY(!rb_ractor_main_p())) {
1202 rb_raise(rb_eRactorIsolationError, "can not set class variables from non-main Ractors (%"PRIsVALUE" from %"PRIsVALUE")", rb_id2str(id), klass);
1203 }
1204}
1205
1206static void
1207cvar_read_ractor_check(VALUE klass, ID id, VALUE val)
1208{
1209 if (UNLIKELY(!rb_ractor_main_p()) && !rb_ractor_shareable_p(val)) {
1210 rb_raise(rb_eRactorIsolationError,
1211 "can not read non-shareable class variable %"PRIsVALUE" from non-main Ractors (%"PRIsVALUE")",
1212 rb_id2str(id), klass);
1213 }
1214}
1215
1216static inline void
1217ivar_ractor_check(VALUE obj, ID id)
1218{
1219 if (LIKELY(rb_is_instance_id(id)) /* not internal ID */ &&
1220 !RB_OBJ_FROZEN_RAW(obj) &&
1221 UNLIKELY(!rb_ractor_main_p()) &&
1222 UNLIKELY(rb_ractor_shareable_p(obj))) {
1223
1224 rb_raise(rb_eRactorIsolationError, "can not access instance variables of shareable objects from non-main Ractors");
1225 }
1226}
1227
1228static inline struct st_table *
1229generic_fields_tbl_no_ractor_check(void)
1230{
1231 ASSERT_vm_locking();
1232
1233 return generic_fields_tbl_;
1234}
1235
1236struct st_table *
1237rb_generic_fields_tbl_get(void)
1238{
1239 return generic_fields_tbl_;
1240}
1241
1242void
1243rb_mark_generic_ivar(VALUE obj)
1244{
1245 VALUE data;
1246 // Bypass ASSERT_vm_locking() check because marking may happen concurrently with mmtk
1247 if (st_lookup(generic_fields_tbl_, (st_data_t)obj, (st_data_t *)&data)) {
1248 rb_gc_mark_movable(data);
1249 }
1250}
1251
1252VALUE
1253rb_obj_fields_generic_uncached(VALUE obj)
1254{
1255 VALUE fields_obj = 0;
1256 RB_VM_LOCKING() {
1257 if (!st_lookup(generic_fields_tbl_, (st_data_t)obj, (st_data_t *)&fields_obj)) {
1258 rb_bug("Object is missing entry in generic_fields_tbl");
1259 }
1260 }
1261 return fields_obj;
1262}
1263
1264VALUE
1265rb_obj_fields(VALUE obj, ID field_name)
1266{
1268 ivar_ractor_check(obj, field_name);
1269
1270 VALUE fields_obj = 0;
1271 if (rb_shape_obj_has_fields(obj)) {
1272 switch (BUILTIN_TYPE(obj)) {
1273 case T_DATA:
1274 if (LIKELY(RTYPEDDATA_P(obj))) {
1275 fields_obj = RTYPEDDATA(obj)->fields_obj;
1276 break;
1277 }
1278 goto generic_fields;
1279 case T_STRUCT:
1280 if (LIKELY(!FL_TEST_RAW(obj, RSTRUCT_GEN_FIELDS))) {
1281 fields_obj = RSTRUCT_FIELDS_OBJ(obj);
1282 break;
1283 }
1284 goto generic_fields;
1285 default:
1286 generic_fields:
1287 {
1288 rb_execution_context_t *ec = GET_EC();
1289 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) {
1290 fields_obj = ec->gen_fields_cache.fields_obj;
1291 RUBY_ASSERT(fields_obj == rb_obj_fields_generic_uncached(obj));
1292 }
1293 else {
1294 fields_obj = rb_obj_fields_generic_uncached(obj);
1295 ec->gen_fields_cache.fields_obj = fields_obj;
1296 ec->gen_fields_cache.obj = obj;
1297 }
1298 }
1299 }
1300 }
1301 return fields_obj;
1302}
1303
1304void
1306{
1307 if (rb_obj_gen_fields_p(obj)) {
1308 st_data_t key = (st_data_t)obj, value;
1309 switch (BUILTIN_TYPE(obj)) {
1310 case T_DATA:
1311 if (LIKELY(RTYPEDDATA_P(obj))) {
1312 RB_OBJ_WRITE(obj, &RTYPEDDATA(obj)->fields_obj, 0);
1313 break;
1314 }
1315 goto generic_fields;
1316 case T_STRUCT:
1317 if (LIKELY(!FL_TEST_RAW(obj, RSTRUCT_GEN_FIELDS))) {
1318 RSTRUCT_SET_FIELDS_OBJ(obj, 0);
1319 break;
1320 }
1321 goto generic_fields;
1322 default:
1323 generic_fields:
1324 {
1325 // Other EC may have stale caches, so fields_obj should be
1326 // invalidated and the GC will replace with Qundef
1327 rb_execution_context_t *ec = GET_EC();
1328 if (ec->gen_fields_cache.obj == obj) {
1329 ec->gen_fields_cache.obj = Qundef;
1330 ec->gen_fields_cache.fields_obj = Qundef;
1331 }
1332 RB_VM_LOCKING() {
1333 if (!st_delete(generic_fields_tbl_no_ractor_check(), &key, &value)) {
1334 rb_bug("Object is missing entry in generic_fields_tbl");
1335 }
1336 }
1337 }
1338 }
1339 RBASIC_SET_SHAPE_ID(obj, ROOT_SHAPE_ID);
1340 }
1341}
1342
1343static void
1344rb_obj_set_fields(VALUE obj, VALUE fields_obj, ID field_name, VALUE original_fields_obj)
1345{
1346 ivar_ractor_check(obj, field_name);
1347
1348 if (!fields_obj) {
1349 RUBY_ASSERT(original_fields_obj);
1351 rb_imemo_fields_clear(original_fields_obj);
1352 return;
1353 }
1354
1355 RUBY_ASSERT(IMEMO_TYPE_P(fields_obj, imemo_fields));
1356 RUBY_ASSERT(!original_fields_obj || IMEMO_TYPE_P(original_fields_obj, imemo_fields));
1357
1358 if (fields_obj != original_fields_obj) {
1359 switch (BUILTIN_TYPE(obj)) {
1360 case T_DATA:
1361 if (LIKELY(RTYPEDDATA_P(obj))) {
1362 RB_OBJ_WRITE(obj, &RTYPEDDATA(obj)->fields_obj, fields_obj);
1363 break;
1364 }
1365 goto generic_fields;
1366 case T_STRUCT:
1367 if (LIKELY(!FL_TEST_RAW(obj, RSTRUCT_GEN_FIELDS))) {
1368 RSTRUCT_SET_FIELDS_OBJ(obj, fields_obj);
1369 break;
1370 }
1371 goto generic_fields;
1372 default:
1373 generic_fields:
1374 {
1375 RB_VM_LOCKING() {
1376 st_insert(generic_fields_tbl_, (st_data_t)obj, (st_data_t)fields_obj);
1377 }
1378 RB_OBJ_WRITTEN(obj, original_fields_obj, fields_obj);
1379
1380 rb_execution_context_t *ec = GET_EC();
1381 if (ec->gen_fields_cache.fields_obj != fields_obj) {
1382 ec->gen_fields_cache.obj = obj;
1383 ec->gen_fields_cache.fields_obj = fields_obj;
1384 }
1385 }
1386 }
1387
1388 if (original_fields_obj) {
1389 // Clear root shape to avoid triggering cleanup such as free_object_id.
1390 rb_imemo_fields_clear(original_fields_obj);
1391 }
1392 }
1393
1394 RBASIC_SET_SHAPE_ID(obj, RBASIC_SHAPE_ID(fields_obj));
1395}
1396
1397void
1398rb_obj_replace_fields(VALUE obj, VALUE fields_obj)
1399{
1400 RB_VM_LOCKING() {
1401 VALUE original_fields_obj = rb_obj_fields_no_ractor_check(obj);
1402 rb_obj_set_fields(obj, fields_obj, 0, original_fields_obj);
1403 }
1404}
1405
1406VALUE
1407rb_obj_field_get(VALUE obj, shape_id_t target_shape_id)
1408{
1410 RUBY_ASSERT(RSHAPE_TYPE_P(target_shape_id, SHAPE_IVAR) || RSHAPE_TYPE_P(target_shape_id, SHAPE_OBJ_ID));
1411
1412 VALUE fields_obj;
1413
1414 switch (BUILTIN_TYPE(obj)) {
1415 case T_CLASS:
1416 case T_MODULE:
1417 fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
1418 break;
1419 case T_OBJECT:
1420 fields_obj = obj;
1421 break;
1422 case T_IMEMO:
1423 RUBY_ASSERT(IMEMO_TYPE_P(obj, imemo_fields));
1424 fields_obj = obj;
1425 break;
1426 default:
1427 fields_obj = rb_obj_fields(obj, RSHAPE_EDGE_NAME(target_shape_id));
1428 break;
1429 }
1430
1431 if (UNLIKELY(rb_shape_too_complex_p(target_shape_id))) {
1432 st_table *fields_hash = rb_imemo_fields_complex_tbl(fields_obj);
1433 VALUE value = Qundef;
1434 st_lookup(fields_hash, RSHAPE_EDGE_NAME(target_shape_id), &value);
1435 RUBY_ASSERT(!UNDEF_P(value));
1436 return value;
1437 }
1438
1439 attr_index_t index = RSHAPE_INDEX(target_shape_id);
1440 return rb_imemo_fields_ptr(fields_obj)[index];
1441}
1442
1443VALUE
1444rb_ivar_lookup(VALUE obj, ID id, VALUE undef)
1445{
1446 if (SPECIAL_CONST_P(obj)) return undef;
1447
1448 VALUE fields_obj;
1449
1450 switch (BUILTIN_TYPE(obj)) {
1451 case T_CLASS:
1452 case T_MODULE:
1453 {
1454 VALUE val = rb_ivar_lookup(RCLASS_WRITABLE_FIELDS_OBJ(obj), id, undef);
1455 if (val != undef &&
1456 rb_is_instance_id(id) &&
1457 UNLIKELY(!rb_ractor_main_p()) &&
1458 !rb_ractor_shareable_p(val)) {
1459 rb_raise(rb_eRactorIsolationError,
1460 "can not get unshareable values from instance variables of classes/modules from non-main Ractors (%"PRIsVALUE" from %"PRIsVALUE")",
1461 rb_id2str(id), obj);
1462 }
1463 return val;
1464 }
1465 case T_IMEMO:
1466 // Handled like T_OBJECT
1467 RUBY_ASSERT(IMEMO_TYPE_P(obj, imemo_fields));
1468 fields_obj = obj;
1469 break;
1470 case T_OBJECT:
1471 fields_obj = obj;
1472 break;
1473 default:
1474 fields_obj = rb_obj_fields(obj, id);
1475 break;
1476 }
1477
1478 if (!fields_obj) {
1479 return undef;
1480 }
1481
1482 shape_id_t shape_id = RBASIC_SHAPE_ID(fields_obj);
1483
1484 if (UNLIKELY(rb_shape_too_complex_p(shape_id))) {
1485 st_table *iv_table = rb_imemo_fields_complex_tbl(fields_obj);
1486 VALUE val;
1487 if (rb_st_lookup(iv_table, (st_data_t)id, (st_data_t *)&val)) {
1488 return val;
1489 }
1490 return undef;
1491 }
1492
1493 attr_index_t index = 0;
1494 if (rb_shape_get_iv_index(shape_id, id, &index)) {
1495 return rb_imemo_fields_ptr(fields_obj)[index];
1496 }
1497
1498 return undef;
1499}
1500
1501VALUE
1503{
1504 VALUE iv = rb_ivar_lookup(obj, id, Qnil);
1505 RB_DEBUG_COUNTER_INC(ivar_get_base);
1506 return iv;
1507}
1508
1509VALUE
1510rb_ivar_get_at(VALUE obj, attr_index_t index, ID id)
1511{
1513 // Used by JITs, but never for T_OBJECT.
1514
1515 switch (BUILTIN_TYPE(obj)) {
1516 case T_OBJECT:
1518 case T_CLASS:
1519 case T_MODULE:
1520 {
1521 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
1522 VALUE val = rb_imemo_fields_ptr(fields_obj)[index];
1523
1524 if (UNLIKELY(!rb_ractor_main_p()) && !rb_ractor_shareable_p(val)) {
1525 rb_raise(rb_eRactorIsolationError,
1526 "can not get unshareable values from instance variables of classes/modules from non-main Ractors");
1527 }
1528
1529 return val;
1530 }
1531 default:
1532 {
1533 VALUE fields_obj = rb_obj_fields(obj, id);
1534 return rb_imemo_fields_ptr(fields_obj)[index];
1535 }
1536 }
1537}
1538
1539VALUE
1540rb_ivar_get_at_no_ractor_check(VALUE obj, attr_index_t index)
1541{
1542 // Used by JITs, but never for T_OBJECT.
1543
1544 VALUE fields_obj;
1545 switch (BUILTIN_TYPE(obj)) {
1546 case T_OBJECT:
1548 case T_CLASS:
1549 case T_MODULE:
1550 fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
1551 break;
1552 default:
1553 fields_obj = rb_obj_fields_no_ractor_check(obj);
1554 break;
1555 }
1556 return rb_imemo_fields_ptr(fields_obj)[index];
1557}
1558
1559VALUE
1560rb_attr_get(VALUE obj, ID id)
1561{
1562 return rb_ivar_lookup(obj, id, Qnil);
1563}
1564
1565void rb_obj_copy_fields_to_hash_table(VALUE obj, st_table *table);
1566static VALUE imemo_fields_complex_from_obj(VALUE owner, VALUE source_fields_obj, shape_id_t shape_id);
1567
1568static shape_id_t
1569obj_transition_too_complex(VALUE obj, st_table *table)
1570{
1571 RUBY_ASSERT(!rb_shape_obj_too_complex_p(obj));
1572 shape_id_t shape_id = rb_shape_transition_complex(obj);
1573
1574 switch (BUILTIN_TYPE(obj)) {
1575 case T_OBJECT:
1576 {
1577 VALUE *old_fields = NULL;
1578 uint32_t old_fields_len = 0;
1579 if (FL_TEST_RAW(obj, ROBJECT_HEAP)) {
1580 old_fields = ROBJECT_FIELDS(obj);
1581 old_fields_len = ROBJECT_FIELDS_CAPACITY(obj);
1582 }
1583 else {
1584 FL_SET_RAW(obj, ROBJECT_HEAP);
1585 }
1586 RBASIC_SET_SHAPE_ID(obj, shape_id);
1587 ROBJECT_SET_FIELDS_HASH(obj, table);
1588 if (old_fields) {
1589 SIZED_FREE_N(old_fields, old_fields_len);
1590 }
1591 }
1592 break;
1593 case T_CLASS:
1594 case T_MODULE:
1595 case T_IMEMO:
1597 break;
1598 default:
1599 {
1600 VALUE fields_obj = rb_imemo_fields_new_complex_tbl(obj, table, RB_OBJ_SHAREABLE_P(obj));
1601 RBASIC_SET_SHAPE_ID(fields_obj, shape_id);
1602 rb_obj_replace_fields(obj, fields_obj);
1603 }
1604 }
1605
1606 return shape_id;
1607}
1608
1609// Copy all object fields, including ivars and internal object_id, etc
1610static shape_id_t
1611rb_evict_fields_to_hash(VALUE obj)
1612{
1613 RUBY_ASSERT(!rb_shape_obj_too_complex_p(obj));
1614
1615 st_table *table = st_init_numtable_with_size(RSHAPE_LEN(RBASIC_SHAPE_ID(obj)));
1616 rb_obj_copy_fields_to_hash_table(obj, table);
1617 shape_id_t new_shape_id = obj_transition_too_complex(obj, table);
1618
1619 RUBY_ASSERT(rb_shape_obj_too_complex_p(obj));
1620 return new_shape_id;
1621}
1622
1623void
1624rb_evict_ivars_to_hash(VALUE obj)
1625{
1626 RUBY_ASSERT(!rb_shape_obj_too_complex_p(obj));
1627
1628 st_table *table = st_init_numtable_with_size(rb_ivar_count(obj));
1629
1630 // Evacuate all previous values from shape into id_table
1631 rb_obj_copy_ivs_to_hash_table(obj, table);
1632 obj_transition_too_complex(obj, table);
1633
1634 RUBY_ASSERT(rb_shape_obj_too_complex_p(obj));
1635}
1636
1637static VALUE
1638rb_ivar_delete(VALUE obj, ID id, VALUE undef)
1639{
1640 rb_check_frozen(obj);
1641
1642 VALUE val = undef;
1643 VALUE fields_obj;
1644 bool concurrent = false;
1645 int type = BUILTIN_TYPE(obj);
1646
1647 switch(type) {
1648 case T_CLASS:
1649 case T_MODULE:
1650 IVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(id);
1651
1652 fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
1653 if (rb_multi_ractor_p()) {
1654 concurrent = true;
1655 }
1656 break;
1657 case T_OBJECT:
1658 fields_obj = obj;
1659 break;
1660 default: {
1661 fields_obj = rb_obj_fields(obj, id);
1662 break;
1663 }
1664 }
1665
1666 if (!fields_obj) {
1667 return undef;
1668 }
1669
1670 const VALUE original_fields_obj = fields_obj;
1671 if (concurrent) {
1672 fields_obj = rb_imemo_fields_clone(fields_obj);
1673 }
1674
1675 shape_id_t old_shape_id = RBASIC_SHAPE_ID(fields_obj);
1676 shape_id_t removed_shape_id;
1677 shape_id_t next_shape_id = rb_shape_transition_remove_ivar(fields_obj, id, &removed_shape_id);
1678
1679 if (UNLIKELY(rb_shape_too_complex_p(next_shape_id))) {
1680 if (UNLIKELY(!rb_shape_too_complex_p(old_shape_id))) {
1681 if (type == T_OBJECT) {
1682 rb_evict_fields_to_hash(obj);
1683 }
1684 else {
1685 fields_obj = imemo_fields_complex_from_obj(obj, fields_obj, next_shape_id);
1686 }
1687 }
1688 st_data_t key = id;
1689 if (!st_delete(rb_imemo_fields_complex_tbl(fields_obj), &key, (st_data_t *)&val)) {
1690 val = undef;
1691 }
1692 }
1693 else {
1694 if (next_shape_id == old_shape_id) {
1695 return undef;
1696 }
1697
1698 RUBY_ASSERT(removed_shape_id != INVALID_SHAPE_ID);
1699 RUBY_ASSERT(RSHAPE_LEN(next_shape_id) == RSHAPE_LEN(old_shape_id) - 1);
1700
1701 VALUE *fields = rb_imemo_fields_ptr(fields_obj);
1702 attr_index_t removed_index = RSHAPE_INDEX(removed_shape_id);
1703 val = fields[removed_index];
1704
1705 attr_index_t new_fields_count = RSHAPE_LEN(next_shape_id);
1706 if (new_fields_count) {
1707 size_t trailing_fields = new_fields_count - removed_index;
1708
1709 MEMMOVE(&fields[removed_index], &fields[removed_index + 1], VALUE, trailing_fields);
1710 RBASIC_SET_SHAPE_ID(fields_obj, next_shape_id);
1711
1712 if (FL_TEST_RAW(fields_obj, OBJ_FIELD_HEAP)) {
1713 if (rb_obj_embedded_size(new_fields_count) <= rb_gc_obj_slot_size(fields_obj)) {
1714 // Re-embed objects when instances become small enough
1715 // This is necessary because YJIT assumes that objects with the same shape
1716 // have the same embeddedness for efficiency (avoid extra checks)
1717 FL_UNSET_RAW(fields_obj, ROBJECT_HEAP);
1718 MEMCPY(rb_imemo_fields_ptr(fields_obj), fields, VALUE, new_fields_count);
1719 SIZED_FREE_N(fields, RSHAPE_CAPACITY(old_shape_id));
1720 }
1721 else if (RSHAPE_CAPACITY(old_shape_id) != RSHAPE_CAPACITY(next_shape_id)) {
1722 IMEMO_OBJ_FIELDS(fields_obj)->as.external.ptr = ruby_xrealloc_sized(fields, RSHAPE_CAPACITY(next_shape_id) * sizeof(VALUE), RSHAPE_CAPACITY(old_shape_id) * sizeof(VALUE));
1723 }
1724 }
1725 }
1726 else {
1727 fields_obj = 0;
1729 }
1730 }
1731
1732 RBASIC_SET_SHAPE_ID(obj, next_shape_id);
1733 if (fields_obj != original_fields_obj) {
1734 switch (type) {
1735 case T_OBJECT:
1736 break;
1737 case T_CLASS:
1738 case T_MODULE:
1739 RCLASS_WRITABLE_SET_FIELDS_OBJ(obj, fields_obj);
1740 break;
1741 default:
1742 rb_obj_set_fields(obj, fields_obj, id, original_fields_obj);
1743 break;
1744 }
1745 }
1746
1747 return val;
1748}
1749
1750VALUE
1751rb_attr_delete(VALUE obj, ID id)
1752{
1753 return rb_ivar_delete(obj, id, Qnil);
1754}
1755
1756void
1757rb_obj_init_too_complex(VALUE obj, st_table *table)
1758{
1759 // This method is meant to be called on newly allocated object.
1760 RUBY_ASSERT(!rb_shape_obj_too_complex_p(obj));
1761 RUBY_ASSERT(rb_shape_canonical_p(RBASIC_SHAPE_ID(obj)));
1762 RUBY_ASSERT(RSHAPE_LEN(RBASIC_SHAPE_ID(obj)) == 0);
1763
1764 obj_transition_too_complex(obj, table);
1765}
1766
1767static int
1768imemo_fields_complex_from_obj_i(ID key, VALUE val, st_data_t arg)
1769{
1770 VALUE fields = (VALUE)arg;
1771 st_table *table = rb_imemo_fields_complex_tbl(fields);
1772
1773 RUBY_ASSERT(!st_lookup(table, (st_data_t)key, NULL));
1774 st_add_direct(table, (st_data_t)key, (st_data_t)val);
1775 RB_OBJ_WRITTEN(fields, Qundef, val);
1776
1777 return ST_CONTINUE;
1778}
1779
1780static VALUE
1781imemo_fields_complex_from_obj(VALUE owner, VALUE source_fields_obj, shape_id_t shape_id)
1782{
1783 attr_index_t len = source_fields_obj ? RSHAPE_LEN(RBASIC_SHAPE_ID(source_fields_obj)) : 0;
1784 VALUE fields_obj = rb_imemo_fields_new_complex(owner, len + 1, RB_OBJ_SHAREABLE_P(owner));
1785
1786 rb_field_foreach(source_fields_obj, imemo_fields_complex_from_obj_i, (st_data_t)fields_obj, false);
1787 RBASIC_SET_SHAPE_ID(fields_obj, shape_id);
1788
1789 return fields_obj;
1790}
1791
1792static VALUE
1793imemo_fields_copy_capa(VALUE owner, VALUE source_fields_obj, attr_index_t new_size)
1794{
1795 VALUE fields_obj = rb_imemo_fields_new(owner, new_size, RB_OBJ_SHAREABLE_P(owner));
1796 if (source_fields_obj) {
1797 attr_index_t fields_count = RSHAPE_LEN(RBASIC_SHAPE_ID(source_fields_obj));
1798 VALUE *fields = rb_imemo_fields_ptr(fields_obj);
1799 MEMCPY(fields, rb_imemo_fields_ptr(source_fields_obj), VALUE, fields_count);
1800 RBASIC_SET_SHAPE_ID(fields_obj, RBASIC_SHAPE_ID(source_fields_obj));
1801 for (attr_index_t i = 0; i < fields_count; i++) {
1802 RB_OBJ_WRITTEN(fields_obj, Qundef, fields[i]);
1803 }
1804 }
1805 return fields_obj;
1806}
1807
1808static VALUE
1809imemo_fields_set(VALUE owner, VALUE fields_obj, shape_id_t target_shape_id, ID field_name, VALUE val, bool concurrent)
1810{
1811 const VALUE original_fields_obj = fields_obj;
1812 shape_id_t current_shape_id = fields_obj ? RBASIC_SHAPE_ID(fields_obj) : ROOT_SHAPE_ID;
1813
1814 if (UNLIKELY(rb_shape_too_complex_p(target_shape_id))) {
1815 if (rb_shape_too_complex_p(current_shape_id)) {
1816 if (concurrent) {
1817 // In multi-ractor case, we must always work on a copy because
1818 // even if the field already exist, inserting in a st_table may
1819 // cause a rebuild.
1820 fields_obj = rb_imemo_fields_clone(fields_obj);
1821 }
1822 }
1823 else {
1824 fields_obj = imemo_fields_complex_from_obj(owner, original_fields_obj, target_shape_id);
1825 current_shape_id = target_shape_id;
1826 }
1827
1828 st_table *table = rb_imemo_fields_complex_tbl(fields_obj);
1829
1830 RUBY_ASSERT(field_name);
1831 st_insert(table, (st_data_t)field_name, (st_data_t)val);
1832 RB_OBJ_WRITTEN(fields_obj, Qundef, val);
1833 RBASIC_SET_SHAPE_ID(fields_obj, target_shape_id);
1834 }
1835 else {
1836 attr_index_t index = RSHAPE_INDEX(target_shape_id);
1837 if (concurrent || index >= RSHAPE_CAPACITY(current_shape_id)) {
1838 fields_obj = imemo_fields_copy_capa(owner, original_fields_obj, RSHAPE_CAPACITY(target_shape_id));
1839 }
1840
1841 VALUE *table = rb_imemo_fields_ptr(fields_obj);
1842 RB_OBJ_WRITE(fields_obj, &table[index], val);
1843
1844 if (RSHAPE_LEN(target_shape_id) > RSHAPE_LEN(current_shape_id)) {
1845 RBASIC_SET_SHAPE_ID(fields_obj, target_shape_id);
1846 }
1847 }
1848
1849 return fields_obj;
1850}
1851
1852static attr_index_t
1853generic_field_set(VALUE obj, shape_id_t target_shape_id, ID field_name, VALUE val)
1854{
1855 if (!field_name) {
1856 field_name = RSHAPE_EDGE_NAME(target_shape_id);
1857 RUBY_ASSERT(field_name);
1858 }
1859
1860 const VALUE original_fields_obj = rb_obj_fields(obj, field_name);
1861 VALUE fields_obj = imemo_fields_set(obj, original_fields_obj, target_shape_id, field_name, val, false);
1862
1863 rb_obj_set_fields(obj, fields_obj, field_name, original_fields_obj);
1864 return rb_shape_too_complex_p(target_shape_id) ? ATTR_INDEX_NOT_SET : RSHAPE_INDEX(target_shape_id);
1865}
1866
1867static shape_id_t
1868generic_shape_ivar(VALUE obj, ID id, bool *new_ivar_out)
1869{
1870 bool new_ivar = false;
1871 shape_id_t current_shape_id = RBASIC_SHAPE_ID(obj);
1872 shape_id_t target_shape_id = current_shape_id;
1873
1874 if (!rb_shape_too_complex_p(current_shape_id)) {
1875 if (!rb_shape_find_ivar(current_shape_id, id, &target_shape_id)) {
1876 if (RSHAPE_LEN(current_shape_id) >= SHAPE_MAX_FIELDS) {
1877 rb_raise(rb_eArgError, "too many instance variables");
1878 }
1879
1880 new_ivar = true;
1881 target_shape_id = rb_shape_transition_add_ivar(obj, id);
1882 }
1883 }
1884
1885 *new_ivar_out = new_ivar;
1886 return target_shape_id;
1887}
1888
1889static attr_index_t
1890generic_ivar_set(VALUE obj, ID id, VALUE val)
1891{
1892 bool dontcare;
1893 shape_id_t target_shape_id = generic_shape_ivar(obj, id, &dontcare);
1894 return generic_field_set(obj, target_shape_id, id, val);
1895}
1896
1897void
1898rb_ensure_iv_list_size(VALUE obj, uint32_t current_len, uint32_t new_capacity)
1899{
1900 RUBY_ASSERT(!rb_shape_obj_too_complex_p(obj));
1901
1902 if (FL_TEST_RAW(obj, ROBJECT_HEAP)) {
1903 SIZED_REALLOC_N(ROBJECT(obj)->as.heap.fields, VALUE, new_capacity, current_len);
1904 }
1905 else {
1906 VALUE *ptr = ROBJECT_FIELDS(obj);
1907 VALUE *newptr = ALLOC_N(VALUE, new_capacity);
1908 MEMCPY(newptr, ptr, VALUE, current_len);
1909 FL_SET_RAW(obj, ROBJECT_HEAP);
1910 ROBJECT(obj)->as.heap.fields = newptr;
1911 }
1912}
1913
1914static int
1915rb_obj_copy_ivs_to_hash_table_i(ID key, VALUE val, st_data_t arg)
1916{
1917 RUBY_ASSERT(!st_lookup((st_table *)arg, (st_data_t)key, NULL));
1918
1919 st_add_direct((st_table *)arg, (st_data_t)key, (st_data_t)val);
1920 return ST_CONTINUE;
1921}
1922
1923void
1924rb_obj_copy_ivs_to_hash_table(VALUE obj, st_table *table)
1925{
1926 rb_ivar_foreach(obj, rb_obj_copy_ivs_to_hash_table_i, (st_data_t)table);
1927}
1928
1929void
1930rb_obj_copy_fields_to_hash_table(VALUE obj, st_table *table)
1931{
1932 rb_field_foreach(obj, rb_obj_copy_ivs_to_hash_table_i, (st_data_t)table, false);
1933}
1934
1935static attr_index_t
1936obj_field_set(VALUE obj, shape_id_t target_shape_id, ID field_name, VALUE val)
1937{
1938 shape_id_t current_shape_id = RBASIC_SHAPE_ID(obj);
1939
1940 if (UNLIKELY(rb_shape_too_complex_p(target_shape_id))) {
1941 if (UNLIKELY(!rb_shape_too_complex_p(current_shape_id))) {
1942 current_shape_id = rb_evict_fields_to_hash(obj);
1943 }
1944
1945 if (RSHAPE_LEN(target_shape_id) > RSHAPE_LEN(current_shape_id)) {
1946 RBASIC_SET_SHAPE_ID(obj, target_shape_id);
1947 }
1948
1949 if (!field_name) {
1950 field_name = RSHAPE_EDGE_NAME(target_shape_id);
1951 RUBY_ASSERT(field_name);
1952 }
1953
1954 st_insert(ROBJECT_FIELDS_HASH(obj), (st_data_t)field_name, (st_data_t)val);
1955 RB_OBJ_WRITTEN(obj, Qundef, val);
1956
1957 return ATTR_INDEX_NOT_SET;
1958 }
1959 else {
1960 attr_index_t index = RSHAPE_INDEX(target_shape_id);
1961
1962 if (index >= RSHAPE_LEN(current_shape_id)) {
1963 if (UNLIKELY(index >= RSHAPE_CAPACITY(current_shape_id))) {
1964 rb_ensure_iv_list_size(obj, RSHAPE_CAPACITY(current_shape_id), RSHAPE_CAPACITY(target_shape_id));
1965 }
1966 RBASIC_SET_SHAPE_ID(obj, target_shape_id);
1967 }
1968
1969 RB_OBJ_WRITE(obj, &ROBJECT_FIELDS(obj)[index], val);
1970
1971 return index;
1972 }
1973}
1974
1975static attr_index_t
1976obj_ivar_set(VALUE obj, ID id, VALUE val)
1977{
1978 bool dontcare;
1979 shape_id_t target_shape_id = generic_shape_ivar(obj, id, &dontcare);
1980 return obj_field_set(obj, target_shape_id, id, val);
1981}
1982
1983/* Set the instance variable +val+ on object +obj+ at ivar name +id+.
1984 * This function only works with T_OBJECT objects, so make sure
1985 * +obj+ is of type T_OBJECT before using this function.
1986 */
1987VALUE
1988rb_vm_set_ivar_id(VALUE obj, ID id, VALUE val)
1989{
1990 rb_check_frozen(obj);
1991 obj_ivar_set(obj, id, val);
1992 return val;
1993}
1994
1996{
1997 if (RB_FL_ABLE(x)) {
1999 if (TYPE(x) == T_STRING) {
2000 RB_FL_UNSET_RAW(x, FL_USER2 | FL_USER3); // STR_CHILLED
2001 }
2002
2003 RB_SET_SHAPE_ID(x, rb_shape_transition_frozen(x));
2004
2005 if (RBASIC_CLASS(x)) {
2007 }
2008 }
2009}
2010
2011static attr_index_t class_ivar_set(VALUE obj, ID id, VALUE val, bool *new_ivar);
2012
2013static attr_index_t
2014ivar_set(VALUE obj, ID id, VALUE val)
2015{
2016 RB_DEBUG_COUNTER_INC(ivar_set_base);
2017
2018 switch (BUILTIN_TYPE(obj)) {
2019 case T_OBJECT:
2020 return obj_ivar_set(obj, id, val);
2021 case T_CLASS:
2022 case T_MODULE:
2023 {
2024 IVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(id);
2025 bool dontcare;
2026 return class_ivar_set(obj, id, val, &dontcare);
2027 }
2028 default:
2029 return generic_ivar_set(obj, id, val);
2030 }
2031}
2032
2033VALUE
2035{
2036 rb_check_frozen(obj);
2037 ivar_set(obj, id, val);
2038 return val;
2039}
2040
2041attr_index_t
2042rb_ivar_set_index(VALUE obj, ID id, VALUE val)
2043{
2044 return ivar_set(obj, id, val);
2045}
2046
2047void
2048rb_ivar_set_internal(VALUE obj, ID id, VALUE val)
2049{
2050 // should be internal instance variable name (no @ prefix)
2051 VM_ASSERT(!rb_is_instance_id(id));
2052
2053 ivar_set(obj, id, val);
2054}
2055
2056attr_index_t
2057rb_obj_field_set(VALUE obj, shape_id_t target_shape_id, ID field_name, VALUE val)
2058{
2059 switch (BUILTIN_TYPE(obj)) {
2060 case T_OBJECT:
2061 return obj_field_set(obj, target_shape_id, field_name, val);
2062 case T_CLASS:
2063 case T_MODULE:
2064 // The only field is object_id and T_CLASS handle it differently.
2065 rb_bug("Unreachable");
2066 break;
2067 default:
2068 return generic_field_set(obj, target_shape_id, field_name, val);
2069 }
2070}
2071
2072static VALUE
2073ivar_defined0(VALUE obj, ID id)
2074{
2075 attr_index_t index;
2076
2077 if (rb_shape_obj_too_complex_p(obj)) {
2078 VALUE idx;
2079 st_table *table = NULL;
2080 switch (BUILTIN_TYPE(obj)) {
2081 case T_CLASS:
2082 case T_MODULE:
2083 rb_bug("Unreachable");
2084 break;
2085
2086 case T_IMEMO:
2087 RUBY_ASSERT(IMEMO_TYPE_P(obj, imemo_fields));
2088 table = rb_imemo_fields_complex_tbl(obj);
2089 break;
2090
2091 case T_OBJECT:
2092 table = ROBJECT_FIELDS_HASH(obj);
2093 break;
2094
2095 default: {
2096 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj); // defined? doesn't require ractor checks
2097 table = rb_imemo_fields_complex_tbl(fields_obj);
2098 }
2099 }
2100
2101 if (!table || !rb_st_lookup(table, id, &idx)) {
2102 return Qfalse;
2103 }
2104
2105 return Qtrue;
2106 }
2107 else {
2108 return RBOOL(rb_shape_get_iv_index(RBASIC_SHAPE_ID(obj), id, &index));
2109 }
2110}
2111
2112VALUE
2114{
2115 if (SPECIAL_CONST_P(obj)) return Qfalse;
2116
2117 VALUE defined = Qfalse;
2118 switch (BUILTIN_TYPE(obj)) {
2119 case T_CLASS:
2120 case T_MODULE:
2121 {
2122 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
2123 if (fields_obj) {
2124 defined = ivar_defined0(fields_obj, id);
2125 }
2126 }
2127 break;
2128 default:
2129 defined = ivar_defined0(obj, id);
2130 break;
2131 }
2132 return defined;
2133}
2134
2136 VALUE obj;
2137 struct gen_fields_tbl *fields_tbl;
2138 st_data_t arg;
2139 rb_ivar_foreach_callback_func *func;
2140 VALUE *fields;
2141 bool ivar_only;
2142};
2143
2144static int
2145iterate_over_shapes_callback(shape_id_t shape_id, void *data)
2146{
2147 struct iv_itr_data *itr_data = data;
2148
2149 if (itr_data->ivar_only && !RSHAPE_TYPE_P(shape_id, SHAPE_IVAR)) {
2150 return ST_CONTINUE;
2151 }
2152
2153 VALUE *fields;
2154 switch (BUILTIN_TYPE(itr_data->obj)) {
2155 case T_OBJECT:
2156 RUBY_ASSERT(!rb_shape_obj_too_complex_p(itr_data->obj));
2157 fields = ROBJECT_FIELDS(itr_data->obj);
2158 break;
2159 case T_IMEMO:
2160 RUBY_ASSERT(IMEMO_TYPE_P(itr_data->obj, imemo_fields));
2161 RUBY_ASSERT(!rb_shape_obj_too_complex_p(itr_data->obj));
2162
2163 fields = rb_imemo_fields_ptr(itr_data->obj);
2164 break;
2165 default:
2166 rb_bug("Unreachable");
2167 }
2168
2169 VALUE val = fields[RSHAPE_INDEX(shape_id)];
2170 return itr_data->func(RSHAPE_EDGE_NAME(shape_id), val, itr_data->arg);
2171}
2172
2173/*
2174 * Returns a flag to stop iterating depending on the result of +callback+.
2175 */
2176static void
2177iterate_over_shapes(shape_id_t shape_id, rb_ivar_foreach_callback_func *callback, struct iv_itr_data *itr_data)
2178{
2179 rb_shape_foreach_field(shape_id, iterate_over_shapes_callback, itr_data);
2180}
2181
2182static int
2183each_hash_iv(st_data_t id, st_data_t val, st_data_t data)
2184{
2185 struct iv_itr_data * itr_data = (struct iv_itr_data *)data;
2186 rb_ivar_foreach_callback_func *callback = itr_data->func;
2187 if (is_internal_id((ID)id)) {
2188 return ST_CONTINUE;
2189 }
2190 return callback((ID)id, (VALUE)val, itr_data->arg);
2191}
2192
2193static void
2194obj_fields_each(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg, bool ivar_only)
2195{
2196 struct iv_itr_data itr_data = {
2197 .obj = obj,
2198 .arg = arg,
2199 .func = func,
2200 .ivar_only = ivar_only,
2201 };
2202
2203 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
2204 if (rb_shape_too_complex_p(shape_id)) {
2205 rb_st_foreach(ROBJECT_FIELDS_HASH(obj), each_hash_iv, (st_data_t)&itr_data);
2206 }
2207 else {
2208 itr_data.fields = ROBJECT_FIELDS(obj);
2209 iterate_over_shapes(shape_id, func, &itr_data);
2210 }
2211}
2212
2213static void
2214imemo_fields_each(VALUE fields_obj, rb_ivar_foreach_callback_func *func, st_data_t arg, bool ivar_only)
2215{
2216 IMEMO_TYPE_P(fields_obj, imemo_fields);
2217
2218 struct iv_itr_data itr_data = {
2219 .obj = fields_obj,
2220 .arg = arg,
2221 .func = func,
2222 .ivar_only = ivar_only,
2223 };
2224
2225 shape_id_t shape_id = RBASIC_SHAPE_ID(fields_obj);
2226 if (rb_shape_too_complex_p(shape_id)) {
2227 rb_st_foreach(rb_imemo_fields_complex_tbl(fields_obj), each_hash_iv, (st_data_t)&itr_data);
2228 }
2229 else {
2230 itr_data.fields = rb_imemo_fields_ptr(fields_obj);
2231 iterate_over_shapes(shape_id, func, &itr_data);
2232 }
2233}
2234
2235void
2237{
2238 VALUE new_fields_obj;
2239
2240 rb_check_frozen(dest);
2241
2242 if (!rb_obj_gen_fields_p(obj)) {
2243 return;
2244 }
2245
2246 shape_id_t src_shape_id = rb_obj_shape_id(obj);
2247
2248 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
2249 if (fields_obj) {
2250 unsigned long src_num_ivs = rb_ivar_count(fields_obj);
2251 if (!src_num_ivs) {
2252 goto clear;
2253 }
2254
2255 if (rb_shape_too_complex_p(src_shape_id)) {
2256 rb_shape_copy_complex_ivars(dest, obj, src_shape_id, rb_imemo_fields_complex_tbl(fields_obj));
2257 return;
2258 }
2259
2260 shape_id_t dest_shape_id = src_shape_id;
2261 shape_id_t initial_shape_id = rb_obj_shape_id(dest);
2262
2263 if (!rb_shape_canonical_p(src_shape_id)) {
2264 RUBY_ASSERT(RSHAPE_TYPE_P(initial_shape_id, SHAPE_ROOT));
2265
2266 dest_shape_id = rb_shape_rebuild(initial_shape_id, src_shape_id);
2267 if (UNLIKELY(rb_shape_too_complex_p(dest_shape_id))) {
2268 st_table *table = rb_st_init_numtable_with_size(src_num_ivs);
2269 rb_obj_copy_ivs_to_hash_table(obj, table);
2270 rb_obj_init_too_complex(dest, table);
2271 return;
2272 }
2273 }
2274
2275 if (!RSHAPE_LEN(dest_shape_id)) {
2276 RBASIC_SET_SHAPE_ID(dest, dest_shape_id);
2277 return;
2278 }
2279
2280 new_fields_obj = rb_imemo_fields_new(dest, RSHAPE_CAPACITY(dest_shape_id), RB_OBJ_SHAREABLE_P(dest));
2281 VALUE *src_buf = rb_imemo_fields_ptr(fields_obj);
2282 VALUE *dest_buf = rb_imemo_fields_ptr(new_fields_obj);
2283 rb_shape_copy_fields(new_fields_obj, dest_buf, dest_shape_id, src_buf, src_shape_id);
2284 RBASIC_SET_SHAPE_ID(new_fields_obj, dest_shape_id);
2285
2286 rb_obj_replace_fields(dest, new_fields_obj);
2287 }
2288 return;
2289
2290 clear:
2292}
2293
2294void
2295rb_replace_generic_ivar(VALUE clone, VALUE obj)
2296{
2297 RB_VM_LOCKING() {
2298 st_data_t fields_tbl, obj_data = (st_data_t)obj;
2299 if (st_delete(generic_fields_tbl_, &obj_data, &fields_tbl)) {
2300 st_insert(generic_fields_tbl_, (st_data_t)clone, fields_tbl);
2301 RB_OBJ_WRITTEN(clone, Qundef, fields_tbl);
2302 }
2303 else {
2304 rb_bug("unreachable");
2305 }
2306 }
2307}
2308
2309void
2310rb_field_foreach(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg, bool ivar_only)
2311{
2312 if (SPECIAL_CONST_P(obj)) return;
2313 switch (BUILTIN_TYPE(obj)) {
2314 case T_IMEMO:
2315 if (IMEMO_TYPE_P(obj, imemo_fields)) {
2316 imemo_fields_each(obj, func, arg, ivar_only);
2317 }
2318 break;
2319 case T_OBJECT:
2320 obj_fields_each(obj, func, arg, ivar_only);
2321 break;
2322 case T_CLASS:
2323 case T_MODULE:
2324 {
2325 IVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(0);
2326 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
2327 if (fields_obj) {
2328 imemo_fields_each(fields_obj, func, arg, ivar_only);
2329 }
2330 }
2331 break;
2332 default:
2333 {
2334 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
2335 if (fields_obj) {
2336 imemo_fields_each(fields_obj, func, arg, ivar_only);
2337 }
2338 }
2339 break;
2340 }
2341}
2342
2343void
2344rb_ivar_foreach(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg)
2345{
2346 rb_field_foreach(obj, func, arg, true);
2347}
2348
2349st_index_t
2351{
2352 if (SPECIAL_CONST_P(obj)) return 0;
2353
2354 st_index_t iv_count = 0;
2355 switch (BUILTIN_TYPE(obj)) {
2356 case T_OBJECT:
2357 iv_count = ROBJECT_FIELDS_COUNT(obj);
2358 break;
2359
2360 case T_CLASS:
2361 case T_MODULE:
2362 {
2363 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
2364 if (!fields_obj) {
2365 return 0;
2366 }
2367 if (rb_shape_obj_too_complex_p(fields_obj)) {
2368 iv_count = rb_st_table_size(rb_imemo_fields_complex_tbl(fields_obj));
2369 }
2370 else {
2371 iv_count = RBASIC_FIELDS_COUNT(fields_obj);
2372 }
2373 }
2374 break;
2375
2376 case T_IMEMO:
2377 RUBY_ASSERT(IMEMO_TYPE_P(obj, imemo_fields));
2378
2379 if (rb_shape_obj_too_complex_p(obj)) {
2380 iv_count = rb_st_table_size(rb_imemo_fields_complex_tbl(obj));
2381 }
2382 else {
2383 iv_count = RBASIC_FIELDS_COUNT(obj);
2384 }
2385 break;
2386
2387 default:
2388 {
2389 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
2390 if (fields_obj) {
2391 if (rb_shape_obj_too_complex_p(fields_obj)) {
2392 rb_st_table_size(rb_imemo_fields_complex_tbl(fields_obj));
2393 }
2394 else {
2395 iv_count = RBASIC_FIELDS_COUNT(obj);
2396 }
2397 }
2398 }
2399 break;
2400 }
2401
2402 if (rb_shape_obj_has_id(obj)) {
2403 iv_count--;
2404 }
2405
2406 return iv_count;
2407}
2408
2409static int
2410ivar_i(ID key, VALUE v, st_data_t a)
2411{
2412 VALUE ary = (VALUE)a;
2413
2414 if (rb_is_instance_id(key)) {
2415 rb_ary_push(ary, ID2SYM(key));
2416 }
2417 return ST_CONTINUE;
2418}
2419
2420/*
2421 * call-seq:
2422 * obj.instance_variables -> array
2423 *
2424 * Returns an array of instance variable names for the receiver. Note
2425 * that simply defining an accessor does not create the corresponding
2426 * instance variable.
2427 *
2428 * class Fred
2429 * attr_accessor :a1
2430 * def initialize
2431 * @iv = 3
2432 * end
2433 * end
2434 * Fred.new.instance_variables #=> [:@iv]
2435 */
2436
2437VALUE
2439{
2440 VALUE ary;
2441
2442 ary = rb_ary_new();
2443 rb_ivar_foreach(obj, ivar_i, ary);
2444 return ary;
2445}
2446
2447#define rb_is_constant_id rb_is_const_id
2448#define rb_is_constant_name rb_is_const_name
2449#define id_for_var(obj, name, part, type) \
2450 id_for_var_message(obj, name, type, "'%1$s' is not allowed as "#part" "#type" variable name")
2451#define id_for_var_message(obj, name, type, message) \
2452 check_id_type(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message))
2453static ID
2454check_id_type(VALUE obj, VALUE *pname,
2455 int (*valid_id_p)(ID), int (*valid_name_p)(VALUE),
2456 const char *message, size_t message_len)
2457{
2458 ID id = rb_check_id(pname);
2459 VALUE name = *pname;
2460
2461 if (id ? !valid_id_p(id) : !valid_name_p(name)) {
2462 rb_name_err_raise_str(rb_fstring_new(message, message_len),
2463 obj, name);
2464 }
2465 return id;
2466}
2467
2468/*
2469 * call-seq:
2470 * obj.remove_instance_variable(symbol) -> obj
2471 * obj.remove_instance_variable(string) -> obj
2472 *
2473 * Removes the named instance variable from <i>obj</i>, returning that
2474 * variable's value. The name can be passed as a symbol or as a string.
2475 *
2476 * class Dummy
2477 * attr_reader :var
2478 * def initialize
2479 * @var = 99
2480 * end
2481 * def remove
2482 * remove_instance_variable(:@var)
2483 * end
2484 * end
2485 * d = Dummy.new
2486 * d.var #=> 99
2487 * d.remove #=> 99
2488 * d.var #=> nil
2489 */
2490
2491VALUE
2493{
2494 const ID id = id_for_var(obj, name, an, instance);
2495
2496 // Frozen check comes here because it's expected that we raise a
2497 // NameError (from the id_for_var check) before we raise a FrozenError
2498 rb_check_frozen(obj);
2499
2500 if (id) {
2501 VALUE val = rb_ivar_delete(obj, id, Qundef);
2502
2503 if (!UNDEF_P(val)) return val;
2504 }
2505
2506 rb_name_err_raise("instance variable %1$s not defined",
2507 obj, name);
2509}
2510
2511NORETURN(static void uninitialized_constant(VALUE, VALUE));
2512static void
2513uninitialized_constant(VALUE klass, VALUE name)
2514{
2515 if (klass && rb_class_real(klass) != rb_cObject)
2516 rb_name_err_raise("uninitialized constant %2$s::%1$s",
2517 klass, name);
2518 else
2519 rb_name_err_raise("uninitialized constant %1$s",
2520 klass, name);
2521}
2522
2523VALUE
2524rb_const_missing(VALUE klass, VALUE name)
2525{
2526 VALUE value = rb_funcallv(klass, idConst_missing, 1, &name);
2527 rb_vm_inc_const_missing_count();
2528 return value;
2529}
2530
2531
2532/*
2533 * call-seq:
2534 * mod.const_missing(sym) -> obj
2535 *
2536 * Invoked when a reference is made to an undefined constant in
2537 * <i>mod</i>. It is passed a symbol for the undefined constant, and
2538 * returns a value to be used for that constant. For example, consider:
2539 *
2540 * def Foo.const_missing(name)
2541 * name # return the constant name as Symbol
2542 * end
2543 *
2544 * Foo::UNDEFINED_CONST #=> :UNDEFINED_CONST: symbol returned
2545 *
2546 * As the example above shows, +const_missing+ is not required to create the
2547 * missing constant in <i>mod</i>, though that is often a side-effect. The
2548 * caller gets its return value when triggered. If the constant is also defined,
2549 * further lookups won't hit +const_missing+ and will return the value stored in
2550 * the constant as usual. Otherwise, +const_missing+ will be invoked again.
2551 *
2552 * In the next example, when a reference is made to an undefined constant,
2553 * +const_missing+ attempts to load a file whose path is the lowercase version
2554 * of the constant name (thus class <code>Fred</code> is assumed to be in file
2555 * <code>fred.rb</code>). If defined as a side-effect of loading the file, the
2556 * method returns the value stored in the constant. This implements an autoload
2557 * feature similar to Kernel#autoload and Module#autoload, though it differs in
2558 * important ways.
2559 *
2560 * def Object.const_missing(name)
2561 * @looked_for ||= {}
2562 * str_name = name.to_s
2563 * raise "Constant not found: #{name}" if @looked_for[str_name]
2564 * @looked_for[str_name] = 1
2565 * file = str_name.downcase
2566 * require file
2567 * const_get(name, false)
2568 * end
2569 *
2570 */
2571
2572VALUE
2573rb_mod_const_missing(VALUE klass, VALUE name)
2574{
2575 rb_execution_context_t *ec = GET_EC();
2576 VALUE ref = ec->private_const_reference;
2577 rb_vm_pop_cfunc_frame();
2578 if (ref) {
2579 ec->private_const_reference = 0;
2580 rb_name_err_raise("private constant %2$s::%1$s referenced", ref, name);
2581 }
2582 uninitialized_constant(klass, name);
2583
2585}
2586
2587static void
2588autoload_table_mark(void *ptr)
2589{
2590 rb_mark_tbl_no_pin((st_table *)ptr);
2591}
2592
2593static void
2594autoload_table_free(void *ptr)
2595{
2596 st_free_table((st_table *)ptr);
2597}
2598
2599static size_t
2600autoload_table_memsize(const void *ptr)
2601{
2602 const st_table *tbl = ptr;
2603 return st_memsize(tbl);
2604}
2605
2606static void
2607autoload_table_compact(void *ptr)
2608{
2609 rb_gc_ref_update_table_values_only((st_table *)ptr);
2610}
2611
2612static const rb_data_type_t autoload_table_type = {
2613 "autoload_table",
2614 {autoload_table_mark, autoload_table_free, autoload_table_memsize, autoload_table_compact,},
2615 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
2616};
2617
2618#define check_autoload_table(av) \
2619 (struct st_table *)rb_check_typeddata((av), &autoload_table_type)
2620
2621static VALUE
2622autoload_data(VALUE mod, ID id)
2623{
2624 struct st_table *tbl;
2625 st_data_t val;
2626
2627 // If we are called with a non-origin ICLASS, fetch the autoload data from
2628 // the original module.
2629 if (RB_TYPE_P(mod, T_ICLASS)) {
2630 if (RICLASS_IS_ORIGIN_P(mod)) {
2631 return 0;
2632 }
2633 else {
2634 mod = RBASIC(mod)->klass;
2635 }
2636 }
2637
2639
2640 // Look up the instance variable table for `autoload`, then index into that table with the given constant name `id`.
2641
2642 VALUE tbl_value = rb_ivar_lookup(mod, autoload, Qfalse);
2643 if (!RTEST(tbl_value) || !(tbl = check_autoload_table(tbl_value)) || !st_lookup(tbl, (st_data_t)id, &val)) {
2644 return 0;
2645 }
2646
2647 return (VALUE)val;
2648}
2649
2650// 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`.
2652 // The linked list node of all constants which are loaded by the related autoload feature.
2653 struct ccan_list_node cnode; /* <=> autoload_data.constants */
2654
2655 // The shared "autoload_data" if multiple constants are defined from the same feature.
2656 VALUE autoload_data_value;
2657
2658 // The box object when the autoload is called in a user box
2659 // Otherwise, Qnil means the root box
2660 VALUE box_value;
2661
2662 // The module we are loading a constant into.
2663 VALUE module;
2664
2665 // The name of the constant we are loading.
2666 ID name;
2667
2668 // The value of the constant (after it's loaded).
2669 VALUE value;
2670
2671 // The constant entry flags which need to be re-applied after autoloading the feature.
2672 rb_const_flag_t flag;
2673
2674 // The source file and line number that defined this constant (different from feature path).
2675 VALUE file;
2676 int line;
2677};
2678
2679// 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.
2681 // The feature path to require to load this constant.
2682 VALUE feature;
2683
2684 // The mutex which is protecting autoloading this feature.
2685 VALUE mutex;
2686
2687 // The process fork serial number since the autoload mutex will become invalid on fork.
2688 rb_serial_t fork_gen;
2689
2690 // The linked list of all constants that are going to be loaded by this autoload.
2691 struct ccan_list_head constants; /* <=> autoload_const.cnode */
2692};
2693
2694static void
2695autoload_data_mark_and_move(void *ptr)
2696{
2697 struct autoload_data *p = ptr;
2698
2699 rb_gc_mark_and_move(&p->feature);
2700 rb_gc_mark_and_move(&p->mutex);
2701}
2702
2703static void
2704autoload_data_free(void *ptr)
2705{
2706 struct autoload_data *p = ptr;
2707
2708 struct autoload_const *autoload_const, *next;
2709 ccan_list_for_each_safe(&p->constants, autoload_const, next, cnode) {
2710 ccan_list_del_init(&autoload_const->cnode);
2711 }
2712
2713 SIZED_FREE(p);
2714}
2715
2716static size_t
2717autoload_data_memsize(const void *ptr)
2718{
2719 return sizeof(struct autoload_data);
2720}
2721
2722static const rb_data_type_t autoload_data_type = {
2723 "autoload_data",
2724 {autoload_data_mark_and_move, autoload_data_free, autoload_data_memsize, autoload_data_mark_and_move},
2725 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
2726};
2727
2728static void
2729autoload_const_mark_and_move(void *ptr)
2730{
2731 struct autoload_const *ac = ptr;
2732
2733 rb_gc_mark_and_move(&ac->module);
2734 rb_gc_mark_and_move(&ac->autoload_data_value);
2735 rb_gc_mark_and_move(&ac->value);
2736 rb_gc_mark_and_move(&ac->file);
2737 rb_gc_mark_and_move(&ac->box_value);
2738}
2739
2740static size_t
2741autoload_const_memsize(const void *ptr)
2742{
2743 return sizeof(struct autoload_const);
2744}
2745
2746static void
2747autoload_const_free(void *ptr)
2748{
2749 struct autoload_const *autoload_const = ptr;
2750
2751 ccan_list_del(&autoload_const->cnode);
2752 SIZED_FREE(autoload_const);
2753}
2754
2755static const rb_data_type_t autoload_const_type = {
2756 "autoload_const",
2757 {autoload_const_mark_and_move, autoload_const_free, autoload_const_memsize, autoload_const_mark_and_move,},
2758 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
2759};
2760
2761static struct autoload_data *
2762get_autoload_data(VALUE autoload_const_value, struct autoload_const **autoload_const_pointer)
2763{
2764 struct autoload_const *autoload_const = rb_check_typeddata(autoload_const_value, &autoload_const_type);
2765
2766 VALUE autoload_data_value = autoload_const->autoload_data_value;
2767 struct autoload_data *autoload_data = rb_check_typeddata(autoload_data_value, &autoload_data_type);
2768
2769 /* do not reach across stack for ->state after forking: */
2770 if (autoload_data && autoload_data->fork_gen != GET_VM()->fork_gen) {
2771 RB_OBJ_WRITE(autoload_data_value, &autoload_data->mutex, Qnil);
2772 autoload_data->fork_gen = 0;
2773 }
2774
2775 if (autoload_const_pointer) *autoload_const_pointer = autoload_const;
2776
2777 return autoload_data;
2778}
2779
2781 VALUE dst_tbl_value;
2782 struct st_table *dst_tbl;
2783 const rb_box_t *box;
2784};
2785
2786static int
2787autoload_copy_table_for_box_i(st_data_t key, st_data_t value, st_data_t arg)
2788{
2790 struct autoload_copy_table_data *data = (struct autoload_copy_table_data *)arg;
2791 struct st_table *tbl = data->dst_tbl;
2792 VALUE tbl_value = data->dst_tbl_value;
2793 const rb_box_t *box = data->box;
2794
2795 VALUE src_value = (VALUE)value;
2796 struct autoload_const *src_const = rb_check_typeddata(src_value, &autoload_const_type);
2797 // autoload_data can be shared between copies because the feature is equal between copies.
2798 VALUE autoload_data_value = src_const->autoload_data_value;
2799 struct autoload_data *autoload_data = rb_check_typeddata(autoload_data_value, &autoload_data_type);
2800
2801 VALUE new_value = TypedData_Make_Struct(0, struct autoload_const, &autoload_const_type, autoload_const);
2802 RB_OBJ_WRITE(new_value, &autoload_const->box_value, rb_get_box_object((rb_box_t *)box));
2803 RB_OBJ_WRITE(new_value, &autoload_const->module, src_const->module);
2804 autoload_const->name = src_const->name;
2805 RB_OBJ_WRITE(new_value, &autoload_const->value, src_const->value);
2806 autoload_const->flag = src_const->flag;
2807 RB_OBJ_WRITE(new_value, &autoload_const->autoload_data_value, autoload_data_value);
2808 ccan_list_add_tail(&autoload_data->constants, &autoload_const->cnode);
2809
2810 st_insert(tbl, (st_data_t)autoload_const->name, (st_data_t)new_value);
2811 RB_OBJ_WRITTEN(tbl_value, Qundef, new_value);
2812
2813 return ST_CONTINUE;
2814}
2815
2816void
2817rb_autoload_copy_table_for_box(st_table *iv_ptr, const rb_box_t *box)
2818{
2819 struct st_table *src_tbl, *dst_tbl;
2820 VALUE src_tbl_value, dst_tbl_value;
2821 if (!rb_st_lookup(iv_ptr, (st_data_t)autoload, (st_data_t *)&src_tbl_value)) {
2822 // the class has no autoload table yet.
2823 return;
2824 }
2825 if (!RTEST(src_tbl_value) || !(src_tbl = check_autoload_table(src_tbl_value))) {
2826 // the __autoload__ ivar value isn't autoload table value.
2827 return;
2828 }
2829 src_tbl = check_autoload_table(src_tbl_value);
2830
2831 dst_tbl_value = TypedData_Wrap_Struct(0, &autoload_table_type, NULL);
2832 RTYPEDDATA_DATA(dst_tbl_value) = dst_tbl = st_init_numtable();
2833
2834 struct autoload_copy_table_data data = {
2835 .dst_tbl_value = dst_tbl_value,
2836 .dst_tbl = dst_tbl,
2837 .box = box,
2838 };
2839
2840 st_foreach(src_tbl, autoload_copy_table_for_box_i, (st_data_t)&data);
2841 st_insert(iv_ptr, (st_data_t)autoload, (st_data_t)dst_tbl_value);
2842}
2843
2844void
2845rb_autoload(VALUE module, ID name, const char *feature)
2846{
2847 if (!feature || !*feature) {
2848 rb_raise(rb_eArgError, "empty feature name");
2849 }
2850
2851 rb_autoload_str(module, name, rb_fstring_cstr(feature));
2852}
2853
2854static void const_set(VALUE klass, ID id, VALUE val);
2855static void const_added(VALUE klass, ID const_name);
2856
2858 VALUE module;
2859 ID name;
2860 VALUE feature;
2861 VALUE box_value;
2862};
2863
2864static VALUE
2865autoload_feature_lookup_or_create(VALUE feature, struct autoload_data **autoload_data_pointer)
2866{
2867 RUBY_ASSERT_MUTEX_OWNED(autoload_mutex);
2868 RUBY_ASSERT_CRITICAL_SECTION_ENTER();
2869
2870 VALUE autoload_data_value = rb_hash_aref(autoload_features, feature);
2872
2873 if (NIL_P(autoload_data_value)) {
2874 autoload_data_value = TypedData_Make_Struct(0, struct autoload_data, &autoload_data_type, autoload_data);
2875 RB_OBJ_WRITE(autoload_data_value, &autoload_data->feature, feature);
2876 RB_OBJ_WRITE(autoload_data_value, &autoload_data->mutex, Qnil);
2877 ccan_list_head_init(&autoload_data->constants);
2878
2879 if (autoload_data_pointer) *autoload_data_pointer = autoload_data;
2880
2881 rb_hash_aset(autoload_features, feature, autoload_data_value);
2882 }
2883 else if (autoload_data_pointer) {
2884 *autoload_data_pointer = rb_check_typeddata(autoload_data_value, &autoload_data_type);
2885 }
2886
2887 RUBY_ASSERT_CRITICAL_SECTION_LEAVE();
2888 return autoload_data_value;
2889}
2890
2891static VALUE
2892autoload_table_lookup_or_create(VALUE module)
2893{
2894 VALUE autoload_table_value = rb_ivar_lookup(module, autoload, Qfalse);
2895 if (RTEST(autoload_table_value)) {
2896 return autoload_table_value;
2897 }
2898 else {
2899 autoload_table_value = TypedData_Wrap_Struct(0, &autoload_table_type, NULL);
2900 rb_class_ivar_set(module, autoload, autoload_table_value);
2901 RTYPEDDATA_DATA(autoload_table_value) = st_init_numtable();
2902 return autoload_table_value;
2903 }
2904}
2905
2906static VALUE
2907autoload_synchronized(VALUE _arguments)
2908{
2909 struct autoload_arguments *arguments = (struct autoload_arguments *)_arguments;
2910
2911 rb_const_entry_t *constant_entry = rb_const_lookup(arguments->module, arguments->name);
2912 if (constant_entry && !UNDEF_P(constant_entry->value)) {
2913 return Qfalse;
2914 }
2915
2916 // Reset any state associated with any previous constant:
2917 const_set(arguments->module, arguments->name, Qundef);
2918
2919 VALUE autoload_table_value = autoload_table_lookup_or_create(arguments->module);
2920 struct st_table *autoload_table = check_autoload_table(autoload_table_value);
2921
2922 // Ensure the string is uniqued since we use an identity lookup:
2923 VALUE feature = rb_fstring(arguments->feature);
2924
2926 VALUE autoload_data_value = autoload_feature_lookup_or_create(feature, &autoload_data);
2927
2928 {
2930 VALUE autoload_const_value = TypedData_Make_Struct(0, struct autoload_const, &autoload_const_type, autoload_const);
2931 RB_OBJ_WRITE(autoload_const_value, &autoload_const->box_value, arguments->box_value);
2932 RB_OBJ_WRITE(autoload_const_value, &autoload_const->module, arguments->module);
2933 autoload_const->name = arguments->name;
2934 autoload_const->value = Qundef;
2935 autoload_const->flag = CONST_PUBLIC;
2936 RB_OBJ_WRITE(autoload_const_value, &autoload_const->autoload_data_value, autoload_data_value);
2937 ccan_list_add_tail(&autoload_data->constants, &autoload_const->cnode);
2938 st_insert(autoload_table, (st_data_t)arguments->name, (st_data_t)autoload_const_value);
2939 RB_OBJ_WRITTEN(autoload_table_value, Qundef, autoload_const_value);
2940 }
2941
2942 return Qtrue;
2943}
2944
2945void
2946rb_autoload_str(VALUE module, ID name, VALUE feature)
2947{
2948 const rb_box_t *box = rb_current_box();
2949 VALUE current_box_value = rb_get_box_object((rb_box_t *)box);
2950
2951 if (!rb_is_const_id(name)) {
2952 rb_raise(rb_eNameError, "autoload must be constant name: %"PRIsVALUE"", QUOTE_ID(name));
2953 }
2954
2955 Check_Type(feature, T_STRING);
2956 if (!RSTRING_LEN(feature)) {
2957 rb_raise(rb_eArgError, "empty feature name");
2958 }
2959
2960 struct autoload_arguments arguments = {
2961 .module = module,
2962 .name = name,
2963 .feature = feature,
2964 .box_value = current_box_value,
2965 };
2966
2967 VALUE result = rb_mutex_synchronize(autoload_mutex, autoload_synchronized, (VALUE)&arguments);
2968
2969 if (result == Qtrue) {
2970 const_added(module, name);
2971 }
2972}
2973
2974static void
2975autoload_delete(VALUE module, ID name)
2976{
2977 RUBY_ASSERT_CRITICAL_SECTION_ENTER();
2978
2979 st_data_t load = 0, key = name;
2980
2981 RUBY_ASSERT(RB_TYPE_P(module, T_CLASS) || RB_TYPE_P(module, T_MODULE));
2982
2983 VALUE table_value = rb_ivar_lookup(module, autoload, Qfalse);
2984 if (RTEST(table_value)) {
2985 struct st_table *table = check_autoload_table(table_value);
2986
2987 st_delete(table, &key, &load);
2988 RB_OBJ_WRITTEN(table_value, load, Qundef);
2989
2990 /* Qfalse can indicate already deleted */
2991 if (load != Qfalse) {
2993 struct autoload_data *autoload_data = get_autoload_data((VALUE)load, &autoload_const);
2994
2995 VM_ASSERT(autoload_data);
2996 VM_ASSERT(!ccan_list_empty(&autoload_data->constants));
2997
2998 /*
2999 * we must delete here to avoid "already initialized" warnings
3000 * with parallel autoload. Using list_del_init here so list_del
3001 * works in autoload_const_free
3002 */
3003 ccan_list_del_init(&autoload_const->cnode);
3004
3005 if (ccan_list_empty(&autoload_data->constants)) {
3006 rb_hash_delete(autoload_features, autoload_data->feature);
3007 }
3008
3009 // If the autoload table is empty, we can delete it.
3010 if (table->num_entries == 0) {
3011 rb_attr_delete(module, autoload);
3012 }
3013 }
3014 }
3015
3016 RUBY_ASSERT_CRITICAL_SECTION_LEAVE();
3017}
3018
3019static int
3020autoload_by_someone_else(struct autoload_data *ele)
3021{
3022 return ele->mutex != Qnil && !rb_mutex_owned_p(ele->mutex);
3023}
3024
3025static VALUE
3026check_autoload_required(VALUE mod, ID id, const char **loadingpath)
3027{
3028 VALUE autoload_const_value = autoload_data(mod, id);
3030 const char *loading;
3031
3032 if (!autoload_const_value || !(autoload_data = get_autoload_data(autoload_const_value, 0))) {
3033 return 0;
3034 }
3035
3036 VALUE feature = autoload_data->feature;
3037
3038 /*
3039 * if somebody else is autoloading, we MUST wait for them, since
3040 * rb_provide_feature can provide a feature before autoload_const_set
3041 * completes. We must wait until autoload_const_set finishes in
3042 * the other thread.
3043 */
3044 if (autoload_by_someone_else(autoload_data)) {
3045 return autoload_const_value;
3046 }
3047
3048 loading = RSTRING_PTR(feature);
3049
3050 if (!rb_feature_provided(loading, &loading)) {
3051 return autoload_const_value;
3052 }
3053
3054 if (loadingpath && loading) {
3055 *loadingpath = loading;
3056 return autoload_const_value;
3057 }
3058
3059 return 0;
3060}
3061
3062static struct autoload_const *autoloading_const_entry(VALUE mod, ID id);
3063
3064int
3065rb_autoloading_value(VALUE mod, ID id, VALUE* value, rb_const_flag_t *flag)
3066{
3067 struct autoload_const *ac = autoloading_const_entry(mod, id);
3068 if (!ac) return FALSE;
3069
3070 if (value) {
3071 *value = ac->value;
3072 }
3073
3074 if (flag) {
3075 *flag = ac->flag;
3076 }
3077
3078 return TRUE;
3079}
3080
3081static int
3082autoload_by_current(struct autoload_data *ele)
3083{
3084 return ele->mutex != Qnil && rb_mutex_owned_p(ele->mutex);
3085}
3086
3087// If there is an autoloading constant and it has been set by the current
3088// execution context, return it. This allows threads which are loading code to
3089// refer to their own autoloaded constants.
3090struct autoload_const *
3091autoloading_const_entry(VALUE mod, ID id)
3092{
3093 VALUE load = autoload_data(mod, id);
3094 struct autoload_data *ele;
3095 struct autoload_const *ac;
3096
3097 // Find the autoloading state:
3098 if (!load || !(ele = get_autoload_data(load, &ac))) {
3099 // Couldn't be found:
3100 return 0;
3101 }
3102
3103 // Check if it's being loaded by the current thread/fiber:
3104 if (autoload_by_current(ele)) {
3105 if (!UNDEF_P(ac->value)) {
3106 return ac;
3107 }
3108 }
3109
3110 return 0;
3111}
3112
3113static int
3114autoload_defined_p(VALUE mod, ID id)
3115{
3116 rb_const_entry_t *ce = rb_const_lookup(mod, id);
3117
3118 // If there is no constant or the constant is not undefined (special marker for autoloading):
3119 if (!ce || !UNDEF_P(ce->value)) {
3120 // We are not autoloading:
3121 return 0;
3122 }
3123
3124 // Otherwise check if there is an autoload in flight right now:
3125 return !rb_autoloading_value(mod, id, NULL, NULL);
3126}
3127
3128static void const_tbl_update(struct autoload_const *, int);
3129
3131 VALUE module;
3132 ID name;
3133 int flag;
3134
3135 VALUE mutex;
3136
3137 // The specific constant which triggered the autoload code to fire:
3139
3140 // The parent autoload data which is shared between multiple constants:
3142};
3143
3144static VALUE
3145autoload_const_set(struct autoload_const *ac)
3146{
3147 check_before_mod_set(ac->module, ac->name, ac->value, "constant");
3148
3149 RB_VM_LOCKING() {
3150 const_tbl_update(ac, true);
3151 }
3152
3153 return 0; /* ignored */
3154}
3155
3156static VALUE
3157autoload_load_needed(VALUE _arguments)
3158{
3159 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3160
3161 const char *loading = 0, *src;
3162
3163 if (!autoload_defined_p(arguments->module, arguments->name)) {
3164 return Qfalse;
3165 }
3166
3167 VALUE autoload_const_value = check_autoload_required(arguments->module, arguments->name, &loading);
3168 if (!autoload_const_value) {
3169 return Qfalse;
3170 }
3171
3172 src = rb_sourcefile();
3173 if (src && loading && strcmp(src, loading) == 0) {
3174 return Qfalse;
3175 }
3176
3179 if (!(autoload_data = get_autoload_data(autoload_const_value, &autoload_const))) {
3180 return Qfalse;
3181 }
3182
3183 if (NIL_P(autoload_data->mutex)) {
3184 RB_OBJ_WRITE(autoload_const->autoload_data_value, &autoload_data->mutex, rb_mutex_new());
3185 autoload_data->fork_gen = GET_VM()->fork_gen;
3186 }
3187 else if (rb_mutex_owned_p(autoload_data->mutex)) {
3188 return Qfalse;
3189 }
3190
3191 arguments->mutex = autoload_data->mutex;
3192 arguments->autoload_const = autoload_const;
3193
3194 return autoload_const_value;
3195}
3196
3197static VALUE
3198autoload_apply_constants(VALUE _arguments)
3199{
3200 RUBY_ASSERT_CRITICAL_SECTION_ENTER();
3201
3202 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3203
3204 struct autoload_const *autoload_const = 0; // for ccan_container_off_var()
3205 struct autoload_const *next;
3206
3207 // We use safe iteration here because `autoload_const_set` will eventually invoke
3208 // `autoload_delete` which will remove the constant from the linked list. In theory, once
3209 // the `autoload_data->constants` linked list is empty, we can remove it.
3210
3211 // Iterate over all constants and assign them:
3212 ccan_list_for_each_safe(&arguments->autoload_data->constants, autoload_const, next, cnode) {
3213 if (!UNDEF_P(autoload_const->value)) {
3214 autoload_const_set(autoload_const);
3215 }
3216 }
3217
3218 RUBY_ASSERT_CRITICAL_SECTION_LEAVE();
3219
3220 return Qtrue;
3221}
3222
3223static VALUE
3224autoload_feature_require(VALUE _arguments)
3225{
3226 VALUE receiver = rb_vm_top_self();
3227
3228 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3229
3230 struct autoload_const *autoload_const = arguments->autoload_const;
3231 VALUE autoload_box_value = autoload_const->box_value;
3232
3233 // We save this for later use in autoload_apply_constants:
3234 arguments->autoload_data = rb_check_typeddata(autoload_const->autoload_data_value, &autoload_data_type);
3235
3236 if (rb_box_available() && BOX_OBJ_P(autoload_box_value))
3237 receiver = autoload_box_value;
3238
3239 /*
3240 * Clear the global cc cache table because the require method can be different from the current
3241 * box's one and it may cause inconsistent cc-cme states.
3242 * For example, the assertion below may fail in gccct_method_search();
3243 * VM_ASSERT(vm_cc_check_cme(cc, rb_callable_method_entry(klass, mid)))
3244 */
3245 rb_gccct_clear_table();
3246
3247 VALUE result = rb_funcall(receiver, rb_intern("require"), 1, arguments->autoload_data->feature);
3248
3249 if (RTEST(result)) {
3250 return rb_mutex_synchronize(autoload_mutex, autoload_apply_constants, _arguments);
3251 }
3252 return result;
3253}
3254
3255static VALUE
3256autoload_try_load(VALUE _arguments)
3257{
3258 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3259
3260 VALUE result = autoload_feature_require(_arguments);
3261
3262 // After we loaded the feature, if the constant is not defined, we remove it completely:
3263 rb_const_entry_t *ce = rb_const_lookup(arguments->module, arguments->name);
3264
3265 if (!ce || UNDEF_P(ce->value)) {
3266 result = Qfalse;
3267
3268 rb_const_remove(arguments->module, arguments->name);
3269
3270 if (arguments->module == rb_cObject) {
3271 rb_warning(
3272 "Expected %"PRIsVALUE" to define %"PRIsVALUE" but it didn't",
3273 arguments->autoload_data->feature,
3274 ID2SYM(arguments->name)
3275 );
3276 }
3277 else {
3278 rb_warning(
3279 "Expected %"PRIsVALUE" to define %"PRIsVALUE"::%"PRIsVALUE" but it didn't",
3280 arguments->autoload_data->feature,
3281 arguments->module,
3282 ID2SYM(arguments->name)
3283 );
3284 }
3285 }
3286 else {
3287 // Otherwise, it was loaded, copy the flags from the autoload constant:
3288 ce->flag |= arguments->flag;
3289 }
3290
3291 return result;
3292}
3293
3294VALUE
3296{
3297 rb_const_entry_t *ce = rb_const_lookup(module, name);
3298
3299 // We bail out as early as possible without any synchronisation:
3300 if (!ce || !UNDEF_P(ce->value)) {
3301 return Qfalse;
3302 }
3303
3304 // At this point, we assume there might be autoloading, so fail if it's ractor:
3305 if (UNLIKELY(!rb_ractor_main_p())) {
3306 return rb_ractor_autoload_load(module, name);
3307 }
3308
3309 // This state is stored on the stack and is used during the autoload process.
3310 struct autoload_load_arguments arguments = {.module = module, .name = name, .mutex = Qnil};
3311
3312 // Figure out whether we can autoload the named constant:
3313 VALUE autoload_const_value = rb_mutex_synchronize(autoload_mutex, autoload_load_needed, (VALUE)&arguments);
3314
3315 // This confirms whether autoloading is required or not:
3316 if (autoload_const_value == Qfalse) return autoload_const_value;
3317
3318 arguments.flag = ce->flag & (CONST_DEPRECATED | CONST_VISIBILITY_MASK);
3319
3320 // Only one thread will enter here at a time:
3321 VALUE result = rb_mutex_synchronize(arguments.mutex, autoload_try_load, (VALUE)&arguments);
3322
3323 // If you don't guard this value, it's possible for the autoload constant to
3324 // be freed by another thread which loads multiple constants, one of which
3325 // resolves to the constant this thread is trying to load, so proteect this
3326 // so that it is not freed until we are done with it in `autoload_try_load`:
3327 RB_GC_GUARD(autoload_const_value);
3328
3329 return result;
3330}
3331
3332VALUE
3334{
3335 return rb_autoload_at_p(mod, id, TRUE);
3336}
3337
3338VALUE
3339rb_autoload_at_p(VALUE mod, ID id, int recur)
3340{
3341 VALUE load;
3342 struct autoload_data *ele;
3343
3344 while (!autoload_defined_p(mod, id)) {
3345 if (!recur) return Qnil;
3346 mod = RCLASS_SUPER(mod);
3347 if (!mod) return Qnil;
3348 }
3349 load = check_autoload_required(mod, id, 0);
3350 if (!load) return Qnil;
3351 return (ele = get_autoload_data(load, 0)) ? ele->feature : Qnil;
3352}
3353
3354void
3355rb_const_warn_if_deprecated(const rb_const_entry_t *ce, VALUE klass, ID id)
3356{
3357 if (RB_CONST_DEPRECATED_P(ce) &&
3358 rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) {
3359 if (klass == rb_cObject) {
3360 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "constant ::%"PRIsVALUE" is deprecated", QUOTE_ID(id));
3361 }
3362 else {
3363 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "constant %"PRIsVALUE"::%"PRIsVALUE" is deprecated",
3364 rb_class_name(klass), QUOTE_ID(id));
3365 }
3366 }
3367}
3368
3369static VALUE
3370rb_const_get_0(VALUE klass, ID id, int exclude, int recurse, int visibility)
3371{
3372 VALUE found_in;
3373 VALUE c = rb_const_search(klass, id, exclude, recurse, visibility, &found_in);
3374 if (!UNDEF_P(c)) {
3375 if (UNLIKELY(!rb_ractor_main_p())) {
3376 if (!rb_ractor_shareable_p(c)) {
3377 rb_raise(rb_eRactorIsolationError, "can not access non-shareable objects in constant %"PRIsVALUE"::%"PRIsVALUE" by non-main Ractor.", rb_class_path(found_in), rb_id2str(id));
3378 }
3379 }
3380 return c;
3381 }
3382 return rb_const_missing(klass, ID2SYM(id));
3383}
3384
3385static VALUE
3386rb_const_search_from(VALUE klass, ID id, int exclude, int recurse, int visibility, VALUE *found_in)
3387{
3388 VALUE value, current;
3389 bool first_iteration = true;
3390
3391 for (current = klass;
3392 RTEST(current);
3393 current = RCLASS_SUPER(current), first_iteration = false) {
3394 VALUE tmp;
3395 VALUE am = 0;
3396 rb_const_entry_t *ce;
3397
3398 if (!first_iteration && RCLASS_ORIGIN(current) != current) {
3399 // This item in the super chain has an origin iclass
3400 // that comes later in the chain. Skip this item so
3401 // prepended modules take precedence.
3402 continue;
3403 }
3404
3405 // Do lookup in original class or module in case we are at an origin
3406 // iclass in the chain.
3407 tmp = current;
3408 if (BUILTIN_TYPE(tmp) == T_ICLASS) tmp = RBASIC(tmp)->klass;
3409
3410 // Do the lookup. Loop in case of autoload.
3411 while ((ce = rb_const_lookup(tmp, id))) {
3412 if (visibility && RB_CONST_PRIVATE_P(ce)) {
3413 GET_EC()->private_const_reference = tmp;
3414 return Qundef;
3415 }
3416 rb_const_warn_if_deprecated(ce, tmp, id);
3417 value = ce->value;
3418 if (UNDEF_P(value)) {
3419 struct autoload_const *ac;
3420 if (am == tmp) break;
3421 am = tmp;
3422 ac = autoloading_const_entry(tmp, id);
3423 if (ac) {
3424 if (found_in) { *found_in = tmp; }
3425 return ac->value;
3426 }
3427 rb_autoload_load(tmp, id);
3428 continue;
3429 }
3430 if (exclude && tmp == rb_cObject) {
3431 goto not_found;
3432 }
3433 if (found_in) { *found_in = tmp; }
3434 return value;
3435 }
3436 if (!recurse) break;
3437 }
3438
3439 not_found:
3440 GET_EC()->private_const_reference = 0;
3441 return Qundef;
3442}
3443
3444static VALUE
3445rb_const_search(VALUE klass, ID id, int exclude, int recurse, int visibility, VALUE *found_in)
3446{
3447 VALUE value;
3448
3449 if (klass == rb_cObject) exclude = FALSE;
3450 value = rb_const_search_from(klass, id, exclude, recurse, visibility, found_in);
3451 if (!UNDEF_P(value)) return value;
3452 if (exclude) return value;
3453 if (BUILTIN_TYPE(klass) != T_MODULE) return value;
3454 /* search global const too, if klass is a module */
3455 return rb_const_search_from(rb_cObject, id, FALSE, recurse, visibility, found_in);
3456}
3457
3458VALUE
3460{
3461 return rb_const_get_0(klass, id, TRUE, TRUE, FALSE);
3462}
3463
3464VALUE
3466{
3467 return rb_const_get_0(klass, id, FALSE, TRUE, FALSE);
3468}
3469
3470VALUE
3472{
3473 return rb_const_get_0(klass, id, TRUE, FALSE, FALSE);
3474}
3475
3476VALUE
3477rb_public_const_get_from(VALUE klass, ID id)
3478{
3479 return rb_const_get_0(klass, id, TRUE, TRUE, TRUE);
3480}
3481
3482VALUE
3483rb_public_const_get_at(VALUE klass, ID id)
3484{
3485 return rb_const_get_0(klass, id, TRUE, FALSE, TRUE);
3486}
3487
3488NORETURN(static void undefined_constant(VALUE mod, VALUE name));
3489static void
3490undefined_constant(VALUE mod, VALUE name)
3491{
3492 rb_name_err_raise("constant %2$s::%1$s not defined",
3493 mod, name);
3494}
3495
3496static VALUE
3497rb_const_location_from(VALUE klass, ID id, int exclude, int recurse, int visibility)
3498{
3499 while (RTEST(klass)) {
3500 rb_const_entry_t *ce;
3501
3502 while ((ce = rb_const_lookup(klass, id))) {
3503 if (visibility && RB_CONST_PRIVATE_P(ce)) {
3504 return Qnil;
3505 }
3506 if (exclude && klass == rb_cObject) {
3507 goto not_found;
3508 }
3509
3510 if (UNDEF_P(ce->value)) { // autoload
3511 VALUE autoload_const_value = autoload_data(klass, id);
3512 if (RTEST(autoload_const_value)) {
3514 struct autoload_data *autoload_data = get_autoload_data(autoload_const_value, &autoload_const);
3515
3516 if (!UNDEF_P(autoload_const->value) && RTEST(rb_mutex_owned_p(autoload_data->mutex))) {
3517 return rb_assoc_new(autoload_const->file, INT2NUM(autoload_const->line));
3518 }
3519 }
3520 }
3521
3522 if (NIL_P(ce->file)) return rb_ary_new();
3523 return rb_assoc_new(ce->file, INT2NUM(ce->line));
3524 }
3525 if (!recurse) break;
3526 klass = RCLASS_SUPER(klass);
3527 }
3528
3529 not_found:
3530 return Qnil;
3531}
3532
3533static VALUE
3534rb_const_location(VALUE klass, ID id, int exclude, int recurse, int visibility)
3535{
3536 VALUE loc;
3537
3538 if (klass == rb_cObject) exclude = FALSE;
3539 loc = rb_const_location_from(klass, id, exclude, recurse, visibility);
3540 if (!NIL_P(loc)) return loc;
3541 if (exclude) return loc;
3542 if (BUILTIN_TYPE(klass) != T_MODULE) return loc;
3543 /* search global const too, if klass is a module */
3544 return rb_const_location_from(rb_cObject, id, FALSE, recurse, visibility);
3545}
3546
3547VALUE
3548rb_const_source_location(VALUE klass, ID id)
3549{
3550 return rb_const_location(klass, id, FALSE, TRUE, FALSE);
3551}
3552
3553VALUE
3554rb_const_source_location_at(VALUE klass, ID id)
3555{
3556 return rb_const_location(klass, id, TRUE, FALSE, FALSE);
3557}
3558
3559/*
3560 * call-seq:
3561 * remove_const(sym) -> obj
3562 *
3563 * Removes the definition of the given constant, returning that
3564 * constant's previous value. If that constant referred to
3565 * a module, this will not change that module's name and can lead
3566 * to confusion.
3567 */
3568
3569VALUE
3571{
3572 const ID id = id_for_var(mod, name, a, constant);
3573
3574 if (!id) {
3575 undefined_constant(mod, name);
3576 }
3577 return rb_const_remove(mod, id);
3578}
3579
3580static rb_const_entry_t * const_lookup(struct rb_id_table *tbl, ID id);
3581
3582VALUE
3584{
3585 VALUE val;
3586 rb_const_entry_t *ce;
3587
3588 rb_check_frozen(mod);
3589
3590 ce = rb_const_lookup(mod, id);
3591
3592 if (!ce) {
3593 if (rb_const_defined_at(mod, id)) {
3594 rb_name_err_raise("cannot remove %2$s::%1$s", mod, ID2SYM(id));
3595 }
3596
3597 undefined_constant(mod, ID2SYM(id));
3598 }
3599
3600 VALUE writable_ce = 0;
3601 if (rb_id_table_lookup(RCLASS_WRITABLE_CONST_TBL(mod), id, &writable_ce)) {
3602 rb_id_table_delete(RCLASS_WRITABLE_CONST_TBL(mod), id);
3603 if ((rb_const_entry_t *)writable_ce != ce) {
3604 SIZED_FREE((rb_const_entry_t *)writable_ce);
3605 }
3606 }
3607
3608 rb_const_warn_if_deprecated(ce, mod, id);
3610
3611 val = ce->value;
3612
3613 if (UNDEF_P(val)) {
3614 autoload_delete(mod, id);
3615 val = Qnil;
3616 }
3617
3618 if (ce != const_lookup(RCLASS_PRIME_CONST_TBL(mod), id)) {
3619 SIZED_FREE(ce);
3620 }
3621 // else - skip free'ing the ce because it still exists in the prime classext
3622
3623 return val;
3624}
3625
3626static int
3627cv_i_update(st_data_t *k, st_data_t *v, st_data_t a, int existing)
3628{
3629 if (existing) return ST_STOP;
3630 *v = a;
3631 return ST_CONTINUE;
3632}
3633
3634static enum rb_id_table_iterator_result
3635sv_i(ID key, VALUE v, void *a)
3636{
3638 st_table *tbl = a;
3639
3640 if (rb_is_const_id(key)) {
3641 st_update(tbl, (st_data_t)key, cv_i_update, (st_data_t)ce);
3642 }
3643 return ID_TABLE_CONTINUE;
3644}
3645
3646static enum rb_id_table_iterator_result
3647rb_local_constants_i(ID const_name, VALUE const_value, void *ary)
3648{
3649 if (rb_is_const_id(const_name) && !RB_CONST_PRIVATE_P((rb_const_entry_t *)const_value)) {
3650 rb_ary_push((VALUE)ary, ID2SYM(const_name));
3651 }
3652 return ID_TABLE_CONTINUE;
3653}
3654
3655static VALUE
3656rb_local_constants(VALUE mod)
3657{
3658 struct rb_id_table *tbl = RCLASS_CONST_TBL(mod);
3659 VALUE ary;
3660
3661 if (!tbl) return rb_ary_new2(0);
3662
3663 RB_VM_LOCKING() {
3664 ary = rb_ary_new2(rb_id_table_size(tbl));
3665 rb_id_table_foreach(tbl, rb_local_constants_i, (void *)ary);
3666 }
3667
3668 return ary;
3669}
3670
3671void*
3672rb_mod_const_at(VALUE mod, void *data)
3673{
3674 st_table *tbl = data;
3675 if (!tbl) {
3676 tbl = st_init_numtable();
3677 }
3678 if (RCLASS_CONST_TBL(mod)) {
3679 RB_VM_LOCKING() {
3680 rb_id_table_foreach(RCLASS_CONST_TBL(mod), sv_i, tbl);
3681 }
3682 }
3683 return tbl;
3684}
3685
3686void*
3687rb_mod_const_of(VALUE mod, void *data)
3688{
3689 VALUE tmp = mod;
3690 for (;;) {
3691 data = rb_mod_const_at(tmp, data);
3692 tmp = RCLASS_SUPER(tmp);
3693 if (!tmp) break;
3694 if (tmp == rb_cObject && mod != rb_cObject) break;
3695 }
3696 return data;
3697}
3698
3699static int
3700list_i(st_data_t key, st_data_t value, VALUE ary)
3701{
3702 ID sym = (ID)key;
3703 rb_const_entry_t *ce = (rb_const_entry_t *)value;
3704 if (RB_CONST_PUBLIC_P(ce)) rb_ary_push(ary, ID2SYM(sym));
3705 return ST_CONTINUE;
3706}
3707
3708VALUE
3709rb_const_list(void *data)
3710{
3711 st_table *tbl = data;
3712 VALUE ary;
3713
3714 if (!tbl) return rb_ary_new2(0);
3715 ary = rb_ary_new2(tbl->num_entries);
3716 st_foreach_safe(tbl, list_i, ary);
3717 st_free_table(tbl);
3718
3719 return ary;
3720}
3721
3722/*
3723 * call-seq:
3724 * mod.constants(inherit=true) -> array
3725 *
3726 * Returns an array of the names of the constants accessible in
3727 * <i>mod</i>. This includes the names of constants in any included
3728 * modules (example at start of section), unless the <i>inherit</i>
3729 * parameter is set to <code>false</code>.
3730 *
3731 * The implementation makes no guarantees about the order in which the
3732 * constants are yielded.
3733 *
3734 * IO.constants.include?(:SYNC) #=> true
3735 * IO.constants(false).include?(:SYNC) #=> false
3736 *
3737 * Also see Module#const_defined?.
3738 */
3739
3740VALUE
3741rb_mod_constants(int argc, const VALUE *argv, VALUE mod)
3742{
3743 bool inherit = true;
3744
3745 if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]);
3746
3747 if (inherit) {
3748 return rb_const_list(rb_mod_const_of(mod, 0));
3749 }
3750 else {
3751 return rb_local_constants(mod);
3752 }
3753}
3754
3755static int
3756rb_const_defined_0(VALUE klass, ID id, int exclude, int recurse, int visibility)
3757{
3758 VALUE tmp;
3759 int mod_retry = 0;
3760 rb_const_entry_t *ce;
3761
3762 tmp = klass;
3763 retry:
3764 while (tmp) {
3765 if ((ce = rb_const_lookup(tmp, id))) {
3766 if (visibility && RB_CONST_PRIVATE_P(ce)) {
3767 return (int)Qfalse;
3768 }
3769 if (UNDEF_P(ce->value) && !check_autoload_required(tmp, id, 0) &&
3770 !rb_autoloading_value(tmp, id, NULL, NULL))
3771 return (int)Qfalse;
3772
3773 if (exclude && tmp == rb_cObject && klass != rb_cObject) {
3774 return (int)Qfalse;
3775 }
3776
3777 return (int)Qtrue;
3778 }
3779 if (!recurse) break;
3780 tmp = RCLASS_SUPER(tmp);
3781 }
3782 if (!exclude && !mod_retry && BUILTIN_TYPE(klass) == T_MODULE) {
3783 mod_retry = 1;
3784 tmp = rb_cObject;
3785 goto retry;
3786 }
3787 return (int)Qfalse;
3788}
3789
3790int
3792{
3793 return rb_const_defined_0(klass, id, TRUE, TRUE, FALSE);
3794}
3795
3796int
3798{
3799 return rb_const_defined_0(klass, id, FALSE, TRUE, FALSE);
3800}
3801
3802int
3804{
3805 return rb_const_defined_0(klass, id, TRUE, FALSE, FALSE);
3806}
3807
3808int
3809rb_public_const_defined_from(VALUE klass, ID id)
3810{
3811 return rb_const_defined_0(klass, id, TRUE, TRUE, TRUE);
3812}
3813
3814static void
3815check_before_mod_set(VALUE klass, ID id, VALUE val, const char *dest)
3816{
3817 rb_check_frozen(klass);
3818}
3819
3820static void set_namespace_path(VALUE named_namespace, VALUE name);
3821
3822static enum rb_id_table_iterator_result
3823set_namespace_path_i(ID id, VALUE v, void *payload)
3824{
3826 VALUE value = ce->value;
3827 VALUE parental_path = *((VALUE *) payload);
3828 if (!rb_is_const_id(id) || !rb_namespace_p(value)) {
3829 return ID_TABLE_CONTINUE;
3830 }
3831
3832 bool has_permanent_classpath;
3833 classname(value, &has_permanent_classpath);
3834 if (has_permanent_classpath) {
3835 return ID_TABLE_CONTINUE;
3836 }
3837 set_namespace_path(value, build_const_path(parental_path, id));
3838
3839 if (!RCLASS_PERMANENT_CLASSPATH_P(value)) {
3840 RCLASS_WRITE_CLASSPATH(value, 0, false);
3841 }
3842
3843 return ID_TABLE_CONTINUE;
3844}
3845
3846/*
3847 * Assign permanent classpaths to all namespaces that are directly or indirectly
3848 * nested under +named_namespace+. +named_namespace+ must have a permanent
3849 * classpath.
3850 */
3851static void
3852set_namespace_path(VALUE named_namespace, VALUE namespace_path)
3853{
3854 struct rb_id_table *const_table = RCLASS_CONST_TBL(named_namespace);
3855 RB_OBJ_SET_SHAREABLE(namespace_path);
3856
3857 RB_VM_LOCKING() {
3858 RCLASS_WRITE_CLASSPATH(named_namespace, namespace_path, true);
3859
3860 if (const_table) {
3861 rb_id_table_foreach(const_table, set_namespace_path_i, &namespace_path);
3862 }
3863 }
3864}
3865
3866static void
3867const_added(VALUE klass, ID const_name)
3868{
3869 if (GET_VM()->running) {
3870 VALUE name = ID2SYM(const_name);
3871 rb_funcallv(klass, idConst_added, 1, &name);
3872 }
3873}
3874
3875static void
3876const_set(VALUE klass, ID id, VALUE val)
3877{
3878 rb_const_entry_t *ce;
3879
3880 if (NIL_P(klass)) {
3881 rb_raise(rb_eTypeError, "no class/module to define constant %"PRIsVALUE"",
3882 QUOTE_ID(id));
3883 }
3884
3885 if (!rb_ractor_main_p() && !rb_ractor_shareable_p(val)) {
3886 rb_raise(rb_eRactorIsolationError, "can not set constants with non-shareable objects by non-main Ractors");
3887 }
3888
3889 check_before_mod_set(klass, id, val, "constant");
3890
3891 RB_VM_LOCKING() {
3892 struct rb_id_table *tbl = RCLASS_WRITABLE_CONST_TBL(klass);
3893 if (!tbl) {
3894 tbl = rb_id_table_create(0);
3895 RCLASS_WRITE_CONST_TBL(klass, tbl, false);
3898 rb_id_table_insert(tbl, id, (VALUE)ce);
3899 setup_const_entry(ce, klass, val, CONST_PUBLIC);
3900 }
3901 else {
3902 struct autoload_const ac = {
3903 .module = klass, .name = id,
3904 .value = val, .flag = CONST_PUBLIC,
3905 /* fill the rest with 0 */
3906 };
3907 ac.file = rb_source_location(&ac.line);
3908 const_tbl_update(&ac, false);
3909 }
3910 }
3911
3912 /*
3913 * Resolve and cache class name immediately to resolve ambiguity
3914 * and avoid order-dependency on const_tbl
3915 */
3916 if (rb_cObject && rb_namespace_p(val)) {
3917 bool val_path_permanent;
3918 VALUE val_path = classname(val, &val_path_permanent);
3919 if (NIL_P(val_path) || !val_path_permanent) {
3920 if (klass == rb_cObject) {
3921 set_namespace_path(val, rb_id2str(id));
3922 }
3923 else {
3924 bool parental_path_permanent;
3925 VALUE parental_path = classname(klass, &parental_path_permanent);
3926 if (NIL_P(parental_path)) {
3927 bool throwaway;
3928 parental_path = rb_tmp_class_path(klass, &throwaway, make_temporary_path);
3929 }
3930 if (parental_path_permanent && !val_path_permanent) {
3931 set_namespace_path(val, build_const_path(parental_path, id));
3932 }
3933 else if (!parental_path_permanent && NIL_P(val_path)) {
3934 VALUE path = build_const_path(parental_path, id);
3935 RCLASS_SET_CLASSPATH(val, path, false);
3936 }
3937 }
3938 }
3939 }
3940}
3941
3942void
3944{
3945 const_set(klass, id, val);
3946 const_added(klass, id);
3947}
3948
3949static VALUE
3950autoload_const_value_for_named_constant(VALUE module, ID name, struct autoload_const **autoload_const_pointer)
3951{
3952 VALUE autoload_const_value = autoload_data(module, name);
3953 if (!autoload_const_value) return Qfalse;
3954
3955 struct autoload_data *autoload_data = get_autoload_data(autoload_const_value, autoload_const_pointer);
3956 if (!autoload_data) return Qfalse;
3957
3958 /* for autoloading thread, keep the defined value to autoloading storage */
3959 if (autoload_by_current(autoload_data)) {
3960 return autoload_const_value;
3961 }
3962
3963 return Qfalse;
3964}
3965
3966static void
3967const_tbl_update(struct autoload_const *ac, int autoload_force)
3968{
3969 VALUE value;
3970 VALUE klass = ac->module;
3971 VALUE val = ac->value;
3972 ID id = ac->name;
3973 struct rb_id_table *tbl = RCLASS_CONST_TBL(klass);
3974 rb_const_flag_t visibility = ac->flag;
3975 rb_const_entry_t *ce;
3976
3977 if (rb_id_table_lookup(tbl, id, &value)) {
3978 ce = (rb_const_entry_t *)value;
3979 if (UNDEF_P(ce->value)) {
3980 RUBY_ASSERT_CRITICAL_SECTION_ENTER();
3981 VALUE file = ac->file;
3982 int line = ac->line;
3983 VALUE autoload_const_value = autoload_const_value_for_named_constant(klass, id, &ac);
3984
3985 if (!autoload_force && autoload_const_value) {
3987
3988 RB_OBJ_WRITE(autoload_const_value, &ac->value, val);
3989 RB_OBJ_WRITE(autoload_const_value, &ac->file, rb_source_location(&ac->line));
3990 }
3991 else {
3992 /* otherwise autoloaded constant, allow to override */
3993 autoload_delete(klass, id);
3994 ce->flag = visibility;
3995 RB_OBJ_WRITE(klass, &ce->value, val);
3996 RB_OBJ_WRITE(klass, &ce->file, file);
3997 ce->line = line;
3998 }
3999 RUBY_ASSERT_CRITICAL_SECTION_LEAVE();
4000 return;
4001 }
4002 else {
4003 VALUE name = QUOTE_ID(id);
4004 visibility = ce->flag;
4005 if (klass == rb_cObject)
4006 rb_warn("already initialized constant %"PRIsVALUE"", name);
4007 else
4008 rb_warn("already initialized constant %"PRIsVALUE"::%"PRIsVALUE"",
4009 rb_class_name(klass), name);
4010 if (!NIL_P(ce->file) && ce->line) {
4011 rb_compile_warn(RSTRING_PTR(ce->file), ce->line,
4012 "previous definition of %"PRIsVALUE" was here", name);
4013 }
4014 }
4016 setup_const_entry(ce, klass, val, visibility);
4017 }
4018 else {
4019 tbl = RCLASS_WRITABLE_CONST_TBL(klass);
4021
4023 rb_id_table_insert(tbl, id, (VALUE)ce);
4024 setup_const_entry(ce, klass, val, visibility);
4025 }
4026}
4027
4028static void
4029setup_const_entry(rb_const_entry_t *ce, VALUE klass, VALUE val,
4030 rb_const_flag_t visibility)
4031{
4032 ce->flag = visibility;
4033 RB_OBJ_WRITE(klass, &ce->value, val);
4034 RB_OBJ_WRITE(klass, &ce->file, rb_source_location(&ce->line));
4035}
4036
4037void
4038rb_define_const(VALUE klass, const char *name, VALUE val)
4039{
4040 ID id = rb_intern(name);
4041
4042 if (!rb_is_const_id(id)) {
4043 rb_warn("rb_define_const: invalid name '%s' for constant", name);
4044 }
4045 if (!RB_SPECIAL_CONST_P(val)) {
4046 rb_vm_register_global_object(val);
4047 }
4048 rb_const_set(klass, id, val);
4049}
4050
4051void
4052rb_define_global_const(const char *name, VALUE val)
4053{
4054 rb_define_const(rb_cObject, name, val);
4055}
4056
4057static void
4058set_const_visibility(VALUE mod, int argc, const VALUE *argv,
4059 rb_const_flag_t flag, rb_const_flag_t mask)
4060{
4061 int i;
4062 rb_const_entry_t *ce;
4063 ID id;
4064
4066 if (argc == 0) {
4067 rb_warning("%"PRIsVALUE" with no argument is just ignored",
4068 QUOTE_ID(rb_frame_callee()));
4069 return;
4070 }
4071
4072 for (i = 0; i < argc; i++) {
4073 struct autoload_const *ac;
4074 VALUE val = argv[i];
4075 id = rb_check_id(&val);
4076 if (!id) {
4077 undefined_constant(mod, val);
4078 }
4079 if ((ce = rb_const_lookup(mod, id))) {
4080 ce->flag &= ~mask;
4081 ce->flag |= flag;
4082 if (UNDEF_P(ce->value)) {
4083 if (autoload_const_value_for_named_constant(mod, id, &ac)) {
4084 ac->flag &= ~mask;
4085 ac->flag |= flag;
4086 }
4087 }
4089 }
4090 else {
4091 undefined_constant(mod, ID2SYM(id));
4092 }
4093 }
4094}
4095
4096void
4097rb_deprecate_constant(VALUE mod, const char *name)
4098{
4099 rb_const_entry_t *ce;
4100 ID id;
4101 long len = strlen(name);
4102
4104 if (!(id = rb_check_id_cstr(name, len, NULL))) {
4105 undefined_constant(mod, rb_fstring_new(name, len));
4106 }
4107 if (!(ce = rb_const_lookup(mod, id))) {
4108 undefined_constant(mod, ID2SYM(id));
4109 }
4110 ce->flag |= CONST_DEPRECATED;
4111}
4112
4113/*
4114 * call-seq:
4115 * mod.private_constant(symbol, ...) => mod
4116 *
4117 * Makes a list of existing constants private.
4118 */
4119
4120VALUE
4121rb_mod_private_constant(int argc, const VALUE *argv, VALUE obj)
4122{
4123 set_const_visibility(obj, argc, argv, CONST_PRIVATE, CONST_VISIBILITY_MASK);
4124 return obj;
4125}
4126
4127/*
4128 * call-seq:
4129 * mod.public_constant(symbol, ...) => mod
4130 *
4131 * Makes a list of existing constants public.
4132 */
4133
4134VALUE
4135rb_mod_public_constant(int argc, const VALUE *argv, VALUE obj)
4136{
4137 set_const_visibility(obj, argc, argv, CONST_PUBLIC, CONST_VISIBILITY_MASK);
4138 return obj;
4139}
4140
4141/*
4142 * call-seq:
4143 * mod.deprecate_constant(symbol, ...) => mod
4144 *
4145 * Makes a list of existing constants deprecated. Attempt
4146 * to refer to them will produce a warning.
4147 *
4148 * module HTTP
4149 * NotFound = Exception.new
4150 * NOT_FOUND = NotFound # previous version of the library used this name
4151 *
4152 * deprecate_constant :NOT_FOUND
4153 * end
4154 *
4155 * HTTP::NOT_FOUND
4156 * # warning: constant HTTP::NOT_FOUND is deprecated
4157 *
4158 */
4159
4160VALUE
4161rb_mod_deprecate_constant(int argc, const VALUE *argv, VALUE obj)
4162{
4163 set_const_visibility(obj, argc, argv, CONST_DEPRECATED, CONST_DEPRECATED);
4164 return obj;
4165}
4166
4167static VALUE
4168original_module(VALUE c)
4169{
4170 if (RB_TYPE_P(c, T_ICLASS))
4171 return RBASIC(c)->klass;
4172 return c;
4173}
4174
4175static int
4176cvar_lookup_at(VALUE klass, ID id, st_data_t *v)
4177{
4178 if (RB_TYPE_P(klass, T_ICLASS)) {
4179 if (RICLASS_IS_ORIGIN_P(klass)) {
4180 return 0;
4181 }
4182 else {
4183 // check the original module
4184 klass = RBASIC(klass)->klass;
4185 }
4186 }
4187
4188 VALUE n = rb_ivar_lookup(klass, id, Qundef);
4189 if (UNDEF_P(n)) return 0;
4190
4191 if (v) *v = n;
4192 return 1;
4193}
4194
4195static VALUE
4196cvar_front_klass(VALUE klass)
4197{
4198 if (RCLASS_SINGLETON_P(klass)) {
4199 VALUE obj = RCLASS_ATTACHED_OBJECT(klass);
4200 if (rb_namespace_p(obj)) {
4201 return obj;
4202 }
4203 }
4204 return RCLASS_SUPER(klass);
4205}
4206
4207static void
4208cvar_overtaken(VALUE front, VALUE target, ID id)
4209{
4210 if (front && target != front) {
4211 if (original_module(front) != original_module(target)) {
4212 rb_raise(rb_eRuntimeError,
4213 "class variable % "PRIsVALUE" of %"PRIsVALUE" is overtaken by %"PRIsVALUE"",
4214 ID2SYM(id), rb_class_name(original_module(front)),
4215 rb_class_name(original_module(target)));
4216 }
4217 if (BUILTIN_TYPE(front) == T_CLASS) {
4218 rb_ivar_delete(front, id, Qundef);
4219 }
4220 }
4221}
4222
4223#define CVAR_FOREACH_ANCESTORS(klass, v, r) \
4224 for (klass = cvar_front_klass(klass); klass; klass = RCLASS_SUPER(klass)) { \
4225 if (cvar_lookup_at(klass, id, (v))) { \
4226 r; \
4227 } \
4228 }
4229
4230#define CVAR_LOOKUP(v,r) do {\
4231 if (cvar_lookup_at(klass, id, (v))) {r;}\
4232 CVAR_FOREACH_ANCESTORS(klass, v, r);\
4233} while(0)
4234
4235static VALUE
4236find_cvar(VALUE klass, VALUE * front, VALUE * target, ID id)
4237{
4238 VALUE v = Qundef;
4239 CVAR_LOOKUP(&v, {
4240 if (!*front) {
4241 *front = klass;
4242 }
4243 *target = klass;
4244 });
4245
4246 return v;
4247}
4248
4249void
4250rb_cvar_set(VALUE klass, ID id, VALUE val)
4251{
4252 CVAR_ACCESSOR_SHOULD_BE_MAIN_RACTOR(klass, id);
4253
4254 VALUE tmp, front = 0, target = 0;
4255
4256 tmp = klass;
4257 CVAR_LOOKUP(0, {if (!front) front = klass; target = klass;});
4258 if (target) {
4259 cvar_overtaken(front, target, id);
4260 }
4261 else {
4262 target = tmp;
4263 }
4264
4265 if (RB_TYPE_P(target, T_ICLASS)) {
4266 target = RBASIC(target)->klass;
4267 }
4268 check_before_mod_set(target, id, val, "class variable");
4269
4270 bool new_cvar = rb_class_ivar_set(target, id, val);
4271
4272 struct rb_id_table *rb_cvc_tbl = RCLASS_WRITABLE_CVC_TBL(target);
4273
4274 if (!rb_cvc_tbl) {
4275 rb_cvc_tbl = rb_id_table_create(2);
4276 RCLASS_WRITE_CVC_TBL(target, rb_cvc_tbl);
4277 }
4278
4279 struct rb_cvar_class_tbl_entry *ent;
4280 VALUE ent_data;
4281
4282 if (!rb_id_table_lookup(rb_cvc_tbl, id, &ent_data)) {
4283 ent = ALLOC(struct rb_cvar_class_tbl_entry);
4284 ent->class_value = target;
4285 ent->global_cvar_state = GET_GLOBAL_CVAR_STATE();
4286 ent->cref = 0;
4287 rb_id_table_insert(rb_cvc_tbl, id, (VALUE)ent);
4288 RB_DEBUG_COUNTER_INC(cvar_inline_miss);
4289 }
4290 else {
4291 ent = (void *)ent_data;
4292 ent->global_cvar_state = GET_GLOBAL_CVAR_STATE();
4293 }
4294
4295 // Break the cvar cache if this is a new class variable.
4296 // Existing caches may have resolved this name to a different
4297 // location in the hierarchy, so we must invalidate globally.
4298 if (new_cvar) {
4299 ruby_vm_global_cvar_state++;
4300 }
4301}
4302
4303VALUE
4304rb_cvar_find(VALUE klass, ID id, VALUE *front)
4305{
4306 VALUE target = 0;
4307 VALUE value;
4308
4309 value = find_cvar(klass, front, &target, id);
4310 if (!target) {
4311 rb_name_err_raise("uninitialized class variable %1$s in %2$s",
4312 klass, ID2SYM(id));
4313 }
4314 cvar_overtaken(*front, target, id);
4315 cvar_read_ractor_check(klass, id, value);
4316 return (VALUE)value;
4317}
4318
4319VALUE
4321{
4322 VALUE front = 0;
4323 return rb_cvar_find(klass, id, &front);
4324}
4325
4326VALUE
4328{
4329 if (!klass) return Qfalse;
4330 CVAR_LOOKUP(0,return Qtrue);
4331 return Qfalse;
4332}
4333
4334static ID
4335cv_intern(VALUE klass, const char *name)
4336{
4337 ID id = rb_intern(name);
4338 if (!rb_is_class_id(id)) {
4339 rb_name_err_raise("wrong class variable name %1$s",
4340 klass, rb_str_new_cstr(name));
4341 }
4342 return id;
4343}
4344
4345void
4346rb_cv_set(VALUE klass, const char *name, VALUE val)
4347{
4348 ID id = cv_intern(klass, name);
4349 rb_cvar_set(klass, id, val);
4350}
4351
4352VALUE
4353rb_cv_get(VALUE klass, const char *name)
4354{
4355 ID id = cv_intern(klass, name);
4356 return rb_cvar_get(klass, id);
4357}
4358
4359void
4360rb_define_class_variable(VALUE klass, const char *name, VALUE val)
4361{
4362 rb_cv_set(klass, name, val);
4363}
4364
4365static int
4366cv_i(ID key, VALUE v, st_data_t a)
4367{
4368 st_table *tbl = (st_table *)a;
4369
4370 if (rb_is_class_id(key)) {
4371 st_update(tbl, (st_data_t)key, cv_i_update, 0);
4372 }
4373 return ST_CONTINUE;
4374}
4375
4376static void*
4377mod_cvar_at(VALUE mod, void *data)
4378{
4379 st_table *tbl = data;
4380 if (!tbl) {
4381 tbl = st_init_numtable();
4382 }
4383 mod = original_module(mod);
4384
4385 rb_ivar_foreach(mod, cv_i, (st_data_t)tbl);
4386 return tbl;
4387}
4388
4389static void*
4390mod_cvar_of(VALUE mod, void *data)
4391{
4392 VALUE tmp = mod;
4393 if (RCLASS_SINGLETON_P(mod)) {
4394 if (rb_namespace_p(RCLASS_ATTACHED_OBJECT(mod))) {
4395 data = mod_cvar_at(tmp, data);
4396 tmp = cvar_front_klass(tmp);
4397 }
4398 }
4399 for (;;) {
4400 data = mod_cvar_at(tmp, data);
4401 tmp = RCLASS_SUPER(tmp);
4402 if (!tmp) break;
4403 }
4404 return data;
4405}
4406
4407static int
4408cv_list_i(st_data_t key, st_data_t value, VALUE ary)
4409{
4410 ID sym = (ID)key;
4411 rb_ary_push(ary, ID2SYM(sym));
4412 return ST_CONTINUE;
4413}
4414
4415static VALUE
4416cvar_list(void *data)
4417{
4418 st_table *tbl = data;
4419 VALUE ary;
4420
4421 if (!tbl) return rb_ary_new2(0);
4422 ary = rb_ary_new2(tbl->num_entries);
4423 st_foreach_safe(tbl, cv_list_i, ary);
4424 st_free_table(tbl);
4425
4426 return ary;
4427}
4428
4429/*
4430 * call-seq:
4431 * mod.class_variables(inherit=true) -> array
4432 *
4433 * Returns an array of the names of class variables in <i>mod</i>.
4434 * This includes the names of class variables in any included
4435 * modules, unless the <i>inherit</i> parameter is set to
4436 * <code>false</code>.
4437 *
4438 * class One
4439 * @@var1 = 1
4440 * end
4441 * class Two < One
4442 * @@var2 = 2
4443 * end
4444 * One.class_variables #=> [:@@var1]
4445 * Two.class_variables #=> [:@@var2, :@@var1]
4446 * Two.class_variables(false) #=> [:@@var2]
4447 */
4448
4449VALUE
4450rb_mod_class_variables(int argc, const VALUE *argv, VALUE mod)
4451{
4452 bool inherit = true;
4453 st_table *tbl;
4454
4455 if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]);
4456 if (inherit) {
4457 tbl = mod_cvar_of(mod, 0);
4458 }
4459 else {
4460 tbl = mod_cvar_at(mod, 0);
4461 }
4462 return cvar_list(tbl);
4463}
4464
4465/*
4466 * call-seq:
4467 * remove_class_variable(sym) -> obj
4468 *
4469 * Removes the named class variable from the receiver, returning that
4470 * variable's value.
4471 *
4472 * class Example
4473 * @@var = 99
4474 * puts remove_class_variable(:@@var)
4475 * p(defined? @@var)
4476 * end
4477 *
4478 * <em>produces:</em>
4479 *
4480 * 99
4481 * nil
4482 */
4483
4484VALUE
4486{
4487 const ID id = id_for_var_message(mod, name, class, "wrong class variable name %1$s");
4488 st_data_t val;
4489
4490 if (!id) {
4491 goto not_defined;
4492 }
4493 rb_check_frozen(mod);
4494 val = rb_ivar_delete(mod, id, Qundef);
4495 if (!UNDEF_P(val)) {
4496 return (VALUE)val;
4497 }
4498 if (rb_cvar_defined(mod, id)) {
4499 rb_name_err_raise("cannot remove %1$s for %2$s", mod, ID2SYM(id));
4500 }
4501 not_defined:
4502 rb_name_err_raise("class variable %1$s not defined for %2$s",
4503 mod, name);
4505}
4506
4507VALUE
4508rb_iv_get(VALUE obj, const char *name)
4509{
4510 ID id = rb_check_id_cstr(name, strlen(name), rb_usascii_encoding());
4511
4512 if (!id) {
4513 return Qnil;
4514 }
4515 return rb_ivar_get(obj, id);
4516}
4517
4518VALUE
4519rb_iv_set(VALUE obj, const char *name, VALUE val)
4520{
4521 ID id = rb_intern(name);
4522
4523 return rb_ivar_set(obj, id, val);
4524}
4525
4526static attr_index_t
4527class_fields_ivar_set(VALUE klass, VALUE fields_obj, ID id, VALUE val, bool concurrent, VALUE *new_fields_obj, bool *new_ivar_out)
4528{
4529 const VALUE original_fields_obj = fields_obj;
4530 fields_obj = original_fields_obj ? original_fields_obj : rb_imemo_fields_new(klass, 1, true);
4531
4532 shape_id_t current_shape_id = RBASIC_SHAPE_ID(fields_obj);
4533 shape_id_t next_shape_id = current_shape_id; // for too_complex
4534 if (UNLIKELY(rb_shape_too_complex_p(current_shape_id))) {
4535 goto too_complex;
4536 }
4537
4538 bool new_ivar;
4539 next_shape_id = generic_shape_ivar(fields_obj, id, &new_ivar);
4540
4541 if (UNLIKELY(rb_shape_too_complex_p(next_shape_id))) {
4542 fields_obj = imemo_fields_complex_from_obj(klass, fields_obj, next_shape_id);
4543 goto too_complex;
4544 }
4545
4546 attr_index_t index = RSHAPE_INDEX(next_shape_id);
4547 if (new_ivar) {
4548 if (index >= RSHAPE_CAPACITY(current_shape_id)) {
4549 // We allocate a new fields_obj even when concurrency isn't a concern
4550 // so that we're embedded as long as possible.
4551 fields_obj = imemo_fields_copy_capa(klass, fields_obj, RSHAPE_CAPACITY(next_shape_id));
4552 }
4553 }
4554
4555 VALUE *fields = rb_imemo_fields_ptr(fields_obj);
4556
4557 if (concurrent && original_fields_obj == fields_obj) {
4558 // In the concurrent case, if we're mutating the existing
4559 // fields_obj, we must use an atomic write, because if we're
4560 // adding a new field, the shape_id must be written after the field
4561 // and if we're updating an existing field, we at least need a relaxed
4562 // write to avoid reaping.
4563 RB_OBJ_ATOMIC_WRITE(fields_obj, &fields[index], val);
4564 }
4565 else {
4566 RB_OBJ_WRITE(fields_obj, &fields[index], val);
4567 }
4568
4569 if (new_ivar) {
4570 RBASIC_SET_SHAPE_ID(fields_obj, next_shape_id);
4571 }
4572
4573 *new_fields_obj = fields_obj;
4574 *new_ivar_out = new_ivar;
4575 return index;
4576
4577too_complex:
4578 {
4579 if (concurrent && fields_obj == original_fields_obj) {
4580 // In multi-ractor case, we must always work on a copy because
4581 // even if the field already exist, inserting in a st_table may
4582 // cause a rebuild.
4583 fields_obj = rb_imemo_fields_clone(fields_obj);
4584 }
4585
4586 st_table *table = rb_imemo_fields_complex_tbl(fields_obj);
4587 new_ivar = !st_insert(table, (st_data_t)id, (st_data_t)val);
4588 RB_OBJ_WRITTEN(fields_obj, Qundef, val);
4589
4590 if (fields_obj != original_fields_obj) {
4591 RBASIC_SET_SHAPE_ID(fields_obj, next_shape_id);
4592 }
4593 }
4594
4595 *new_fields_obj = fields_obj;
4596 *new_ivar_out = new_ivar;
4597 return ATTR_INDEX_NOT_SET;
4598}
4599
4600static attr_index_t
4601class_ivar_set(VALUE obj, ID id, VALUE val, bool *new_ivar)
4602{
4603 rb_class_ensure_writable(obj);
4604
4605 const VALUE original_fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
4606 VALUE new_fields_obj = 0;
4607
4608 attr_index_t index = class_fields_ivar_set(obj, original_fields_obj, id, val, rb_multi_ractor_p(), &new_fields_obj, new_ivar);
4609
4610 if (new_fields_obj != original_fields_obj) {
4611 RCLASS_WRITABLE_SET_FIELDS_OBJ(obj, new_fields_obj);
4612 }
4613
4614 // TODO: What should we set as the T_CLASS shape_id?
4615 // In most case we can replicate the single `fields_obj` shape
4616 // but in namespaced case? Perhaps INVALID_SHAPE_ID?
4617 RBASIC_SET_SHAPE_ID(obj, RBASIC_SHAPE_ID(new_fields_obj));
4618 return index;
4619}
4620
4621bool
4622rb_class_ivar_set(VALUE obj, ID id, VALUE val)
4623{
4625 rb_check_frozen(obj);
4626
4627 bool new_ivar;
4628 class_ivar_set(obj, id, val, &new_ivar);
4629 return new_ivar;
4630}
4631
4632void
4633rb_fields_tbl_copy(VALUE dst, VALUE src)
4634{
4635 RUBY_ASSERT(rb_type(dst) == rb_type(src));
4637 RUBY_ASSERT(RSHAPE_TYPE_P(RBASIC_SHAPE_ID(dst), SHAPE_ROOT));
4638
4639 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(src);
4640 if (fields_obj) {
4641 RCLASS_WRITABLE_SET_FIELDS_OBJ(dst, rb_imemo_fields_clone(fields_obj));
4642 RBASIC_SET_SHAPE_ID(dst, RBASIC_SHAPE_ID(src));
4643 }
4644}
4645
4646static rb_const_entry_t *
4647const_lookup(struct rb_id_table *tbl, ID id)
4648{
4649 if (tbl) {
4650 VALUE val;
4651 bool r;
4652 RB_VM_LOCKING() {
4653 r = rb_id_table_lookup(tbl, id, &val);
4654 }
4655
4656 if (r) return (rb_const_entry_t *)val;
4657 }
4658 return NULL;
4659}
4660
4662rb_const_lookup(VALUE klass, ID id)
4663{
4664 return const_lookup(RCLASS_CONST_TBL(klass), id);
4665}
#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:696
static bool RB_FL_ABLE(VALUE obj)
Checks if the object is flaggable.
Definition fl_type.h:381
static void RB_FL_SET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_SET().
Definition fl_type.h:541
void rb_obj_freeze_inline(VALUE obj)
Prevents further modifications to the given object.
Definition variable.c:1995
static void RB_FL_UNSET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_UNSET().
Definition fl_type.h:601
@ RUBY_FL_FREEZE
This flag has something to do with data immutability.
Definition fl_type.h:278
void rb_class_modify_check(VALUE klass)
Asserts that klass is not a frozen class.
Definition eval.c:429
void rb_freeze_singleton_class(VALUE attached_object)
This is an implementation detail of RB_OBJ_FREEZE().
Definition class.c:2810
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:3180
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1676
#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:130
#define FL_USER3
Old name of RUBY_FL_USER3.
Definition fl_type.h:72
#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 Qundef
Old name of RUBY_Qundef.
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1684
#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:131
#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:128
#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:71
#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:126
#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:477
void rb_name_error(ID id, const char *fmt,...)
Raises an instance of rb_eNameError.
Definition error.c:2341
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1427
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:2356
VALUE rb_eNameError
NameError exception.
Definition error.c:1432
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1425
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:1413
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:467
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:498
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition error.h:48
VALUE rb_cObject
Object class.
Definition object.c:61
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:95
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:229
VALUE rb_cModule
Module class.
Definition object.c:62
VALUE rb_class_real(VALUE klass)
Finds a "real" class.
Definition object.c:220
#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:1254
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1120
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:666
VALUE rb_backref_get(void)
Queries the last match, or Regexp.last_match, or the $~.
Definition vm.c:2042
int rb_is_instance_id(ID id)
Classifies the given ID, then sees if it is an instance variable.
Definition symbol.c:1128
int rb_is_const_id(ID id)
Classifies the given ID, then sees if it is a constant.
Definition symbol.c:1110
int rb_is_class_id(ID id)
Classifies the given ID, then sees if it is a class variable.
Definition symbol.c:1116
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:988
VALUE rb_reg_nth_defined(int n, VALUE md)
Identical to rb_reg_nth_match(), except it just returns Boolean.
Definition re.c:1910
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:3818
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:3171
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1501
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:1979
#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:1515
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:968
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:4485
VALUE rb_obj_instance_variables(VALUE obj)
Resembles Object#instance_variables.
Definition variable.c:2438
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:3465
VALUE rb_const_list(void *)
This is another mysterious API that comes with no documents at all.
Definition variable.c:3709
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:3333
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:2034
VALUE rb_mod_remove_const(VALUE space, VALUE name)
Resembles Module#remove_const.
Definition variable.c:3570
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:4250
VALUE rb_cvar_get(VALUE klass, ID name)
Obtains a value from a class variable.
Definition variable.c:4320
VALUE rb_mod_constants(int argc, const VALUE *argv, VALUE recv)
Resembles Module#constants.
Definition variable.c:3741
VALUE rb_cvar_find(VALUE klass, ID name, VALUE *front)
Identical to rb_cvar_get(), except it takes additional "front" pointer.
Definition variable.c:4304
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:1502
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:3943
VALUE rb_autoload_load(VALUE space, ID name)
Kicks the autoload procedure as if it was "touched".
Definition variable.c:3295
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:3471
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:4360
VALUE rb_obj_remove_instance_variable(VALUE obj, VALUE name)
Resembles Object#remove_instance_variable.
Definition variable.c:2492
void * rb_mod_const_of(VALUE, void *)
This is a variant of rb_mod_const_at().
Definition variable.c:3687
st_index_t rb_ivar_count(VALUE obj)
Number of instance variables defined on an object.
Definition variable.c:2350
void * rb_mod_const_at(VALUE, void *)
This API is mysterious.
Definition variable.c:3672
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:3583
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:3459
VALUE rb_ivar_defined(VALUE obj, ID name)
Queries if the instance variable is defined at the object.
Definition variable.c:2113
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:4353
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:3803
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:4346
VALUE rb_mod_class_variables(int argc, const VALUE *argv, VALUE recv)
Resembles Module#class_variables.
Definition variable.c:4450
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:4327
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:3791
int rb_const_defined(VALUE space, ID name)
Queries if the constant is defined at the namespace.
Definition variable.c:3797
void rb_free_generic_ivar(VALUE obj)
Frees the list of instance variables.
Definition variable.c:1305
const char * rb_sourcefile(void)
Resembles __FILE__.
Definition vm.c:2079
void rb_clear_constant_cache_for_id(ID id)
Clears the inline constant caches associated with a particular ID.
Definition vm_method.c:329
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:3458
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
VALUE rb_id2sym(ID id)
Allocates an instance of rb_cSymbol that has the given id.
Definition symbol.c:1005
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1164
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:12693
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:4052
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:4097
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:4508
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:4519
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:2236
#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:669
#define RTYPEDDATA_DATA(v)
Convenient getter macro.
Definition rtypeddata.h:106
#define RUBY_TYPED_FREE_IMMEDIATELY
Macros to see if each corresponding flag is defined.
Definition rtypeddata.h:122
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:531
#define RTYPEDDATA(obj)
Convenient casting macro.
Definition rtypeddata.h:96
#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:578
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:37
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:229
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