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