Commit b2d417b1

b2d417b1d521Merged

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

Description

feat(parse,codegen): support ClassVariableReadNode (@@var) + body init folding

Reads the per-(class,name) C global registered by the ClassVariableWriteNode commit. compile_expr arm:

if t == "ClassVariableReadNode"
  return "cvar_" + cvar_qname(@current_class_idx, @nd_name[nid])
end

infer_type arm classifies as the registered cvar type (or "int" fallback for unregistered reads, mirroring the InstanceVariableReadNode fallback at line 1476).

Also lands two cvar correctness fixes the expanded test surfaced:

  1. Expression-form ClassVariableWriteNode arm in compile_expr. Method bodies ending in @@x = expr route through compile_expr (the last-expression-as-return path), not compile_stmt. Without the arm, def tick; @@count = @@count + 1; end returned 0 and the write was dropped. Adds the C-comma form (cvar_X = val) so the assignment fires AND the value is the result, matching InstanceVariableWriteNode at line 14780.

  2. Compile-time const folding of class-body literal initializers. Spinel doesn't run class-body statements at startup -- main()'s loop skips ClassNode -- so class C; @@x = 42; end left cvar_C_x at type-default (0) until the first runtime write. collect_cvars now calls try_fold_cvar_init when the RHS is a simple literal (Integer/Float/String/Symbol/True/False/Nil), capturing the value into @cvar_init_values. The static decl emit pass uses the folded value as the C initializer:

    static mrb_int cvar_Counter_count = 0;     // before
    static mrb_int cvar_Other_count = 100;     // after
    static mrb_bool cvar_Config_debug = TRUE;  // after
    

Test fixture exercises five real-world cvar idioms:

  • Singleton-counter (Counter.tick / .value / instance_value): three call paths into the same slot (class method write, class method read, instance method read).
  • Per-class isolation (Counter vs Other with same @@count name): verifies cvar_qname's class-prefixing keeps the slots independent.
  • Body-level literal init (Config.@@debug / @@max_retries): exercises the const-fold path -- without it both reads return 0/false.
  • Many-call accumulator (Tally.add over multiple invocations): cvar state survives across class-method calls.
  • Cross-method-kind mutation (Registry: instance method writes, class method reads): same @current_class_idx for both, so they agree on the slot.

Out of scope (documented inline): conditional class-body rewrites (if X; @@y = ...; end -- needs a class-init-function); hierarchy-shared cvars (Spinel intentionally doesn't walk the inheritance chain); chained class-method .add(n).add(m) returning self (Spinel's class methods are static C functions with no self).

Tests: 259 pass. Bootstrap: gen2.c == gen3.c.

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

Details

Commit
b2d417b1d521
Parent
40403f434501

spinel_codegen.rbmodifiedView file

@@ -188,6 +188,12 @@
188188 # storage model better. Documented in the test fixtures.
189189 @cvar_names = "".split(",")
190190 @cvar_types = "".split(",")
191+ # Compile-time literal initializer per cvar, if the class-body
192+ # write was `@@x = <literal>`. "" means "use type-default". This
193+ # is necessary because Spinel doesn't run class-body statements
194+ # at startup, so any initializer that's not a fold-able literal
195+ # leaves the cvar at its type-default until first write.
196+ @cvar_init_values = "".split(",")
191197 @const_expr_ids = []
192198 @const_scope_names = "".split(",")
193199
@@ -1582,7 +1588,7 @@
15821588 end
15831589
15841590 # Register or update a cvar's inferred type. Called from
1585- # scan_class_vars during the pre-pass and (defensively) again from
1591+ # collect_cvars during the pre-pass and (defensively) again from
15861592 # compile_stmt when the write fires.
15871593 def register_cvar(qname, t)
15881594 ci = find_cvar_idx(qname)
@@ -1596,9 +1602,53 @@
15961602 end
15971603 @cvar_names.push(qname)
15981604 @cvar_types.push(t)
1605+ @cvar_init_values.push("")
15991606 @cvar_names.length - 1
16001607 end
16011608
1609+ # Try to compile-time fold a class-body cvar initializer. If the
1610+ # value is a simple literal (Integer/Float/String/Symbol/True/
1611+ # False/Nil), capture it as the static decl's initializer so the
1612+ # cvar enters the program with the source's value rather than the
1613+ # type default. Spinel doesn't run class-body statements at
1614+ # startup, so without this fold a `class C; @@x = 42; end` leaves
1615+ # cvar_C_x at 0 until the first write fires.
1616+ def try_fold_cvar_init(qname, value_id)
1617+ if value_id < 0
1618+ return
1619+ end
1620+ vt = @nd_type[value_id]
1621+ lit = ""
1622+ if vt == "IntegerNode"
1623+ lit = @nd_value[value_id].to_s
1624+ end
1625+ if vt == "FloatNode"
1626+ lit = @nd_content[value_id]
1627+ end
1628+ if vt == "StringNode"
1629+ lit = c_string_literal(@nd_content[value_id])
1630+ end
1631+ if vt == "SymbolNode"
1632+ lit = compile_symbol_literal(@nd_content[value_id])
1633+ end
1634+ if vt == "TrueNode"
1635+ lit = "TRUE"
1636+ end
1637+ if vt == "FalseNode"
1638+ lit = "FALSE"
1639+ end
1640+ if vt == "NilNode"
1641+ lit = "0"
1642+ end
1643+ if lit == ""
1644+ return
1645+ end
1646+ ci = find_cvar_idx(qname)
1647+ if ci >= 0
1648+ @cvar_init_values[ci] = lit
1649+ end
1650+ end
1651+
16021652 # If the constant's initializer is a simple literal, return the
16031653 # corresponding C expression. Otherwise return "" so callers fall
16041654 # back to cst_<name> lookup. Enables propagation of:
@@ -1877,6 +1927,14 @@
18771927 end
18781928 return "int"
18791929 end
1930+ if t == "ClassVariableReadNode"
1931+ qname = cvar_qname(@current_class_idx, @nd_name[nid])
1932+ ci = find_cvar_idx(qname)
1933+ if ci >= 0
1934+ return @cvar_types[ci]
1935+ end
1936+ return "int"
1937+ end
18801938 if t == "ConstantReadNode"
18811939 if @nd_name[nid] == "ARGV"
18821940 return "argv"
@@ -5822,6 +5880,7 @@
58225880 qname = cvar_qname(class_idx, @nd_name[nid])
58235881 val_t = infer_type(@nd_expression[nid])
58245882 register_cvar(qname, val_t)
5883+ try_fold_cvar_init(qname, @nd_expression[nid])
58255884 end
58265885 cs = []
58275886 push_child_ids(nid, cs)
@@ -13543,11 +13602,18 @@
1354313602 end
1354413603 # Emit file-scope class-variable declarations. One C global per
1354513604 # (class, name) pair, named `cvar_<ClassName>_<var>`; populated
13546- # by the ClassVariable*WriteNode codegen arms.
13605+ # by the ClassVariable*WriteNode codegen arms. If the class-body
13606+ # initializer was a simple literal, collect_cvars folded it into
13607+ # @cvar_init_values; otherwise we fall back to the type default
13608+ # and the cvar is undefined-acting until the first runtime write.
1354713609 i = 0
1354813610 while i < @cvar_names.length
1354913611 ctp = c_type(@cvar_types[i])
13550- emit_raw("static " + ctp + " cvar_" + @cvar_names[i] + " = " + c_default_val(@cvar_types[i]) + ";")
13612+ init = @cvar_init_values[i]
13613+ if init == ""
13614+ init = c_default_val(@cvar_types[i])
13615+ end
13616+ emit_raw("static " + ctp + " cvar_" + @cvar_names[i] + " = " + init + ";")
1355113617 i = i + 1
1355213618 end
1355313619 if @cvar_names.length > 0
@@ -17609,6 +17675,26 @@
1760917675 end
1761017676 return ivar_lhs(@nd_name[nid])
1761117677 end
17678+ if t == "ClassVariableReadNode"
17679+ # `@@var` -- reads the per-(class,name) C global registered
17680+ # by collect_cvars. @current_class_idx is set during class
17681+ # body and class/instance method compilation, so the lookup
17682+ # resolves to whichever class's body or method we're in.
17683+ return "cvar_" + cvar_qname(@current_class_idx, @nd_name[nid])
17684+ end
17685+ if t == "ClassVariableWriteNode"
17686+ # Expression-form write: `def tick; @@x = @@x + 1; end` --
17687+ # the method body's last expression is the write, and
17688+ # CRuby returns the assigned value. Emits the C-comma
17689+ # form so the assignment fires AND the value is the
17690+ # result, matching the InstanceVariableWriteNode pattern
17691+ # at line 14780.
17692+ qname = cvar_qname(@current_class_idx, @nd_name[nid])
17693+ val = compile_expr(@nd_expression[nid])
17694+ val_t = infer_type(@nd_expression[nid])
17695+ register_cvar(qname, val_t)
17696+ return "(cvar_" + qname + " = " + val + ")"
17697+ end
1761217698 if t == "InstanceVariableWriteNode"
1761317699 # Issue #130: same poly-slot boxing as the statement-form emit.
1761417700 # Expression form (`x = (@y = expr)`) is rarer but reaches the