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