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