Commit c23e4b23

c23e4b232537Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 3 files · ~3 modified

Description

Class#name/to_s on a class literal or .class; NameError on self-referential const init

SomeClass.name / .to_s / .inspect and X.class.name / .to_s render the class-name string (X.class is already lowered to that string).

A CONST = SomeClass.new(...) whose initialize (or anything it calls) reads CONST must raise NameError, since CONST is not yet bound (#646). analyze marks such consts init_guarded; codegen emits an in-progress flag set around the assignment, and guards each read with a NameError raise while the flag is set.

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
c23e4b232537
Parent
12f482dbeb09

src/analyze.cmodifiedView file

@@ -262,6 +262,19 @@
262262 ty_is_array(rt) || ty_is_hash(rt) || ty_is_object(rt)))
263263 return TY_STRING;
264264
265+ /* X.class.name / .to_s -> the class-name string (X.class is already that) */
266+ if (recv >= 0 && argc == 0 && (!strcmp(name, "name") || !strcmp(name, "to_s")) &&
267+ nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "CallNode") &&
268+ nt_str(nt, recv, "name") && !strcmp(nt_str(nt, recv, "name"), "class"))
269+ return TY_STRING;
270+
271+ /* SomeClass.name / .to_s / .inspect -> the class-name string */
272+ if (recv >= 0 && argc == 0 &&
273+ (!strcmp(name, "name") || !strcmp(name, "to_s") || !strcmp(name, "inspect")) &&
274+ nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "ConstantReadNode") &&
275+ nt_str(nt, recv, "name") && comp_class_index(c, nt_str(nt, recv, "name")) >= 0)
276+ return TY_STRING;
277+
265278 /* Class.new(...) -> an instance of that class; built-in .new constructors */
266279 if (recv >= 0 && !strcmp(name, "new")) {
267280 const char *rty = nt_type(nt, recv);
@@ -1173,7 +1186,21 @@
11731186 else if (!strcmp(ty, "ConstantWriteNode")) {
11741187 const char *nm = nt_str(nt, id, "name");
11751188 /* a Struct/Data const names a class, not a value constant */
1176- if (nm && is_c_ident(nm) && comp_class_index(c, nm) < 0) comp_const_intern(c, nm);
1189+ if (nm && is_c_ident(nm) && comp_class_index(c, nm) < 0) {
1190+ LocalVar *cv = comp_const_intern(c, nm);
1191+ /* `CONST = SomeClass.new(...)`: reads of CONST during the new()
1192+ (i.e. inside initialize or anything it calls) must raise
1193+ NameError, since CONST is not yet bound. */
1194+ int v = nt_ref(nt, id, "value");
1195+ const char *vty = v >= 0 ? nt_type(nt, v) : NULL;
1196+ if (vty && !strcmp(vty, "CallNode") && nt_str(nt, v, "name") &&
1197+ !strcmp(nt_str(nt, v, "name"), "new")) {
1198+ int vr = nt_ref(nt, v, "receiver");
1199+ if (vr >= 0 && nt_type(nt, vr) && !strcmp(nt_type(nt, vr), "ConstantReadNode") &&
1200+ nt_str(nt, vr, "name") && comp_class_index(c, nt_str(nt, vr, "name")) >= 0)
1201+ cv->init_guarded = 1;
1202+ }
1203+ }
11771204 }
11781205 }
11791206 }