Commit 15932f0c

15932f0c2943Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 2 files · +1 added · ~1 modified

Description

fix(codegen): declare locals used in initialize bodies, close #17

`def initialize; x = 1; @a = x; end` produced C that referenced `lv_x` without declaring it. Both the inlined `_new` constructor and the standalone `_initialize` helper need the locals declared up front so that ivar-write expressions (and any non-ivar statement) can refer to them.

Two surgical changes in `emit_constructor`:

  • After the parameter declarations, call `declare_method_locals(bid, pnames)` so every local mentioned in the initialize body gets a C declaration in scope. This mirrors what `emit_instance_method` already does for ordinary methods.
  • In the standalone `_initialize` helper, replace the ivar-write-only loop with a generic `compile_stmt` dispatch (skipping SuperNode, which the `_new` path emits explicitly). The previous loop dropped `x = 1` style assignments entirely, so even after declaring `lv_x` the value would have stayed at the default `0`.

Includes `test/bm_init_locals.rb` covering simple-local, while-loop, and multi-local cases. All 81 tests pass; bench 55/55 stays green.

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

Details

Commit
15932f0c2943
Parent
8fffa9dd1d5c

spinel_codegen.rbmodifiedView file

@@ -9777,6 +9777,9 @@
97779777 declare_var(pnames[k], pt)
97789778 k = k + 1
97799779 end
9780+ # Declare any local variables used inside initialize so that
9781+ # `x = 1; @a = x` style bodies don't reference an undeclared lv_x.
9782+ declare_method_locals(bid, pnames)
97809783 stmts = get_stmts(bid)
97819784 stmts.each { |sid|
97829785 if @nd_type[sid] == "SuperNode"
@@ -9882,12 +9885,13 @@
98829885 declare_var(pnames[k], pt)
98839886 k = k + 1
98849887 end
9888+ # Declare locals so non-ivar statements (`x = 1`) and
9889+ # expressions that reference them compile.
9890+ declare_method_locals(bid, pnames)
98859891 stmts = get_stmts(bid)
98869892 stmts.each { |sid|
9887- if @nd_type[sid] == "InstanceVariableWriteNode"
9888- ivar = sanitize_ivar(@nd_name[sid])
9889- val = compile_expr(@nd_expression[sid])
9890- emit_raw(" " + self_arrow + ivar + " = " + val + ";")
9893+ if @nd_type[sid] != "SuperNode"
9894+ compile_stmt(sid)
98919895 end
98929896 }
98939897 pop_scope