Commit 6587a1ae
6587a1ae7a8fMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified
Description
Module/class-level instance variables in def self.X
An @ivar accessed inside a class method (def self.X) now reads/writes a file-scope static civ_ instead of self->iv (a class method has no instance self). One static per class ivar; struct-valued types (poly/range/time) zero-init with {0} so the initializer stays constant.
Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]
Details
- Commit
- 6587a1ae7a8f
- Parent
- 57515e7b7a61
src/codegen.cmodifiedView file
@@ -3452,7 +3452,11 @@
34523452
if (!strcmp(ty, "SelfNode")) { buf_puts(b, g_self); return; } /* self is the object reference (pointer) */34533453
if (!strcmp(ty, "InstanceVariableReadNode")) {34543454
const char *nm = nt_str(nt, id, "name"); /* "@x" */3455-
buf_printf(b, "%s->iv_%s", g_self, nm + 1);3455+
Scope *cs = comp_scope_of(c, id);3456+
if (cs && cs->is_cmethod && cs->class_id >= 0)3457+
buf_printf(b, "civ_%s_%s", c->classes[cs->class_id].name, nm + 1); /* module/class-level ivar */3458+
else3459+
buf_printf(b, "%s->iv_%s", g_self, nm + 1);34563460
return;34573461
}34583462
if (!strcmp(ty, "ClassVariableReadNode")) {@@ -4446,7 +4450,11 @@
44464450
const char *nm = nt_str(nt, id, "name");44474451
int v = nt_ref(nt, id, "value");44484452
emit_indent(b, indent);4449-
buf_printf(b, "%s->iv_%s = ", g_self, nm + 1);4453+
Scope *cws = comp_scope_of(c, id);4454+
if (cws && cws->is_cmethod && cws->class_id >= 0)4455+
buf_printf(b, "civ_%s_%s = ", c->classes[cws->class_id].name, nm + 1);4456+
else4457+
buf_printf(b, "%s->iv_%s = ", g_self, nm + 1);44504458
const char *vty = nt_type(nt, v);44514459
int sc = comp_scope_of(c, id)->class_id;44524460
TyKind ivt = TY_INT;@@ -5366,6 +5374,22 @@
53665374
}53675375
}53685376
5377+
/* module/class-level instance variables (accessed from a `def self.X`):5378+
one file-scope static per (class, @ivar). */5379+
for (int i = 0; i < c->nclasses; i++) {5380+
ClassInfo *ci = &c->classes[i];5381+
for (int j = 0; j < ci->nivars; j++) {5382+
TyKind t = ci->ivar_types[j] == TY_UNKNOWN ? TY_INT : ci->ivar_types[j];5383+
/* static initializers must be constant: struct-valued types (poly /5384+
range / time) zero-init with {0}; scalars use their default. */5385+
const char *init = (t == TY_POLY || t == TY_RANGE || t == TY_TIME) ? "{0}"5386+
: (is_scalar_ret(t) && t != TY_POLY) ? default_value(t) : "0";5387+
buf_puts(&b, "static ");5388+
emit_ctype(c, t, &b);5389+
buf_printf(&b, " civ_%s_%s = %s;\n", ci->name, ci->ivars[j] + 1, init);5390+
}5391+
}5392+
53695393
/* method prototypes (scope 0 is top-level) */53705394
for (int s = 1; s < c->nscopes; s++) { if (c->scopes[s].yields || !c->scopes[s].reachable || scope_is_shadowed(c, s)) continue; emit_method_signature(c, &c->scopes[s], &b); buf_puts(&b, ";\n"); }53715395
/* constructor prototypes + definitions (after method protos: new calls initialize) */