Commit ffd7802c
ffd7802c32b8Merged
Ryan Seys <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified
Description
analyze,codegen: lower instance_variable_get/set on a literal name
instance_variable_get(:@x) / instance_variable_set(:@x, v) were
unsupported. With a literal symbol or string naming an ivar in the class's
known layout, lower them to a direct field access: get reads iv_x, set
assigns it (and, per C lvalue = v, evaluates to the field, matching the
value Ruby returns). A value-object receiver is mutated only when it is an
lvalue (a local / ivar / self); a pointer object through any reference.
Inference returns the ivar's declared type.
The remaining cases match CRuby rather than rejecting:
- an undefined but valid
@-name reads as nil for get, since CRuby returns nil for an unset ivar (the receiver is still evaluated for side effects); - a String argument resolves the same as a symbol;
- a name without a leading
@raises NameError at runtime ("'' is not allowed as an instance variable name").
A dynamic (non-literal) name -- or instance_variable_set to a valid name absent from the fixed object layout, which has no field to write -- cannot be represented and is diagnosed.
Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]
Details
- Commit
- ffd7802c32b8
- Parent
- 913a83318df6
src/analyze_infer.cmodifiedView file
if (!strcmp(name, "is_a?") || !strcmp(name, "kind_of?") || !strcmp(name, "instance_of?") || !strcmp(name, "respond_to?") || !strcmp(name, "==") || !strcmp(name, "!=") || !strcmp(name, "nil?") || !strcmp(name, "equal?") || !strcmp(name, "frozen?")) return TY_BOOL; /* instance_variable_get(:@x) yields @x's declared type; instance_variable_set yields the field type too (C `lvalue = v` evaluates to the lvalue). The codegen lowers both to a direct iv_ field access on the known layout. */ if ((!strcmp(name, "instance_variable_get") || !strcmp(name, "instance_variable_set")) && argc >= 1) { const char *a0ty = nt_type(nt, argv[0]); if (a0ty && (!strcmp(a0ty, "SymbolNode") || !strcmp(a0ty, "StringNode"))) { const char *sym = !strcmp(a0ty, "SymbolNode") ? nt_str(nt, argv[0], "value") : nt_str(nt, argv[0], "content"); /* A name in the layout yields its declared type; an undefined-but-valid `@`-name reads as nil and a bad name (no `@`) raises NameError -- both poly. */ int iv = (sym && sym[0] == '@') ? comp_ivar_index(cls, sym) : -1; if (iv >= 0) return cls->ivar_types[iv]; return TY_POLY; } } /* attr reader (resolve alias so `alias v access_token` returns @access_token type) */ { int rdcls = -1; if (comp_reader_in_chain(c, cid, name, &rdcls)) {src/codegen_call.cmodifiedView file
Loading diff…
test/ivar_get_set_literal.rbaddedView file
Loading diff…
test/ivar_get_set_literal.rb.expectedaddedView file
Loading diff…