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