Commit ec8f1b3e

ec8f1b3ebf46Merged

Ryan Seys <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified

Description

analyze,codegen: resolve const_get with a literal name

Module.const_get(:K) was unsupported even for a literal symbol/string name. Constants live in a flat namespace (cst_), so a literal name resolves exactly like a ConstantRead: emit the constant value, infer the constant's type.

A literal name that does not resolve now raises NameError at runtime, matching CRuby rather than rejecting at compile time: "uninitialized constant " for a valid constant name (qualified by a named module receiver, e.g. M::Missing, but not by Object), and "wrong constant name " for a name without a leading uppercase. The receiver is evaluated for its side effects first. A dynamic (non-literal) name cannot be resolved ahead of time and is diagnosed.

Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

Details

Commit
ec8f1b3ebf46
Parent
d4f52ea7d0bb

src/analyze_infer.cmodifiedView file

@@ -2194,6 +2194,16 @@
21942194 if (!strcmp(name, "!")) return TY_BOOL;
21952195 if (!strcmp(name, "respond_to?") && recv >= 0) return TY_BOOL;
21962196 if ((!strcmp(name, "method_defined?") || !strcmp(name, "const_defined?")) && recv >= 0) return TY_BOOL;
2197+ /* const_get(:K) with a literal name resolves to the constant's type (codegen
2198+ emits cst_<K>); a literal name that does not resolve raises NameError at
2199+ runtime, so its value type is poly. A dynamic name is left unresolved. */
2200+ if (!strcmp(name, "const_get") && recv >= 0 && argc >= 1) {
2201+ const char *cgt = nt_type(nt, argv[0]);
2202+ const char *cgn = NULL;
2203+ if (cgt && !strcmp(cgt, "SymbolNode")) cgn = nt_str(nt, argv[0], "value");
2204+ else if (cgt && !strcmp(cgt, "StringNode")) cgn = nt_str(nt, argv[0], "content");
2205+ if (cgn) { LocalVar *cv = comp_const(c, cgn); if (cv && cv->type != TY_UNKNOWN) return cv->type; return TY_POLY; }
2206+ }
21972207 if (!strcmp(name, "nil?") && recv >= 0 && argc == 0) return TY_BOOL;
21982208 if (!strcmp(name, "object_id") && recv >= 0 && argc == 0) return TY_INT;
21992209 if (!strcmp(name, "between?") && argc == 2 && (rt == TY_STRING || ty_is_numeric(rt))) return TY_BOOL;