Commit 135e1a3a

135e1a3a3938Merged

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

Description

feat(parse,codegen): support GlobalVariableOrWriteNode ($x ||= val)

Mirror of LocalVariableOrWriteNode. Emits if (!(cname)) cname = val; where cname is sanitize_gvar(name).

Inherits LocalVariableOrWriteNode's pre-existing C-truthy vs Ruby-truthy divergence: numeric 0 tests falsy at the C level even though it is truthy in Ruby. This is documented in the test fixture; the nil-to-string type transition that exposes the gap most sharply ($x = nil; $x ||= "default") also doesn't compile today because Spinel's type inference keeps the variable typed as int across the ||= boundary. Both gaps exist for local variables too; fixing them is out of scope for this commit.

Test: test/global_var_or_write.rb (exercises only the agreement region). Bootstrap: gen2.c == gen3.c.

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

Details

Commit
135e1a3a3938
Parent
887d2bcb138e

spinel_codegen.rbmodifiedView file

@@ -24744,6 +24744,20 @@
2474424744 end
2474524745 return
2474624746 end
24747+ if t == "GlobalVariableOrWriteNode"
24748+ # `$x ||= val`. Short-circuit: only evaluate RHS when LHS is
24749+ # falsy. compile_expr can emit prerequisite statements; running
24750+ # it inside the C `if` block ensures those side effects only
24751+ # fire on the assign branch. Note: in Ruby, an undefined $-var
24752+ # reads as nil, which is falsy in C terms, so the `if (!cname)`
24753+ # guard fires both for never-assigned and assigned-to-falsy.
24754+ cname = sanitize_gvar(@nd_name[nid])
24755+ emit(" if (!(" + cname + ")) {")
24756+ val = compile_expr(@nd_expression[nid])
24757+ emit(" " + cname + " = " + val + ";")
24758+ emit(" }")
24759+ return
24760+ end
2474724761 if t == "LocalVariableWriteNode"
2474824762 lname = @nd_name[nid]
2474924763 # Check for method(:name) assignment