-
Notifications
You must be signed in to change notification settings - Fork 46
Description
Summary
When using gogen to generate Go code with an If statement that includes an initialization statement, the code generated under llgo is missing the initialization part. The same code works correctly when run with standard Go.
This issue is similar to #1604 (TypeSwitch initialization bug).
Environment
- llgo version: latest devel branch
- OS: macOS (Darwin 24.5.0)
- gogen: latest version
Reproduction
Expected Behavior (works with go run)
func main() {
if x := 3; x > 1 {
fmt.Println("OK!")
}
}Actual Behavior (when using llgo run)
func main() {
if x > 1 { // ❌ Missing "x := 3;" initialization
fmt.Println("OK!")
}
}Minimal Reproduction Code
package main
import (
"bytes"
"fmt"
"go/token"
"github.com/goplus/gogen"
"github.com/goplus/gogen/packages"
)
func ctxRef(pkg *gogen.Package, name string) gogen.Ref {
_, o := pkg.CB().Scope().LookupParent(name, token.NoPos)
return o
}
func main() {
fset := token.NewFileSet()
imp := packages.NewImporter(fset)
conf := &gogen.Config{Fset: fset, Importer: imp}
pkg := gogen.NewPackage("", "main", conf)
pkg.NewFunc(nil, "main", nil, nil, false).BodyStart(pkg).
If().DefineVarStart(0, "x").Val(3).EndInit(1).
Val(ctxRef(pkg, "x")).Val(1).BinaryOp(token.GTR).Then().
Val(pkg.Import("fmt").Ref("Println")).Val("OK!").Call(1).EndStmt().
End().
End()
var buf bytes.Buffer
pkg.WriteTo(&buf)
result := buf.String()
expected := `package main
import "fmt"
func main() {
if x := 3; x > 1 {
fmt.Println("OK!")
}
}
`
fmt.Println("Generated code:")
fmt.Println(result)
fmt.Println("\nExpected code:")
fmt.Println(expected)
if result != expected {
fmt.Println("\n❌ BUG: If statement initialization is missing!")
} else {
fmt.Println("\n✅ PASS")
}
}Steps to Reproduce
- Save the code above as
bug_if_init.go - Run with standard Go:
go run bug_if_init.go- ✅ Output: "PASS"
- Run with llgo:
llgo run bug_if_init.go- ❌ Output: "BUG: If statement initialization is missing!"
Root Cause Analysis
The initialization statement (DefineVarStart()...EndInit() call) is processed correctly by standard Go but appears to be ignored or lost when the code is executed under llgo runtime.
Impact
This bug affects any code generation that relies on If statement initialization, which is a common Go language feature (e.g., if err := foo(); err != nil { ... }).
Related Issues
- Bug: TypeSwitch initialization statement missing when running under llgo when use gogen #1604 - Similar issue with TypeSwitch initialization statement missing
- Both issues involve initialization statements being lost in control flow structures
- Suggests there may be a common root cause in how llgo handles statement initialization
Related Test
This bug was discovered while porting package_test.go tests to llgo. The test TestIf fails under llgo but passes under standard Go.