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

@@ -1123,6 +1123,21 @@
11231123 if (!strcmp(name, "is_a?") || !strcmp(name, "kind_of?") || !strcmp(name, "instance_of?") ||
11241124 !strcmp(name, "respond_to?") || !strcmp(name, "==") || !strcmp(name, "!=") ||
11251125 !strcmp(name, "nil?") || !strcmp(name, "equal?") || !strcmp(name, "frozen?")) return TY_BOOL;
1126+ /* instance_variable_get(:@x) yields @x's declared type; instance_variable_set
1127+ yields the field type too (C `lvalue = v` evaluates to the lvalue). The
1128+ codegen lowers both to a direct iv_ field access on the known layout. */
1129+ if ((!strcmp(name, "instance_variable_get") || !strcmp(name, "instance_variable_set")) && argc >= 1) {
1130+ const char *a0ty = nt_type(nt, argv[0]);
1131+ if (a0ty && (!strcmp(a0ty, "SymbolNode") || !strcmp(a0ty, "StringNode"))) {
1132+ const char *sym = !strcmp(a0ty, "SymbolNode")
1133+ ? nt_str(nt, argv[0], "value") : nt_str(nt, argv[0], "content");
1134+ /* A name in the layout yields its declared type; an undefined-but-valid
1135+ `@`-name reads as nil and a bad name (no `@`) raises NameError -- both poly. */
1136+ int iv = (sym && sym[0] == '@') ? comp_ivar_index(cls, sym) : -1;
1137+ if (iv >= 0) return cls->ivar_types[iv];
1138+ return TY_POLY;
1139+ }
1140+ }
11261141 /* attr reader (resolve alias so `alias v access_token` returns @access_token type) */
11271142 { int rdcls = -1;
11281143 if (comp_reader_in_chain(c, cid, name, &rdcls)) {