compiler: count the number of variables correctly

This commit is contained in:
Evgenii Stratonikov 2020-05-19 16:47:43 +03:00
parent 0629479560
commit b4bad11699
3 changed files with 29 additions and 10 deletions

View file

@ -70,16 +70,16 @@ func (c *codegen) traverseGlobals(f ast.Node) {
// countGlobals counts the global variables in the program to add
// them with the stack size of the function.
func countGlobals(f ast.Node) (i int64) {
func countGlobals(f ast.Node) (i int) {
ast.Inspect(f, func(node ast.Node) bool {
switch node.(type) {
switch n := node.(type) {
// Skip all function declarations.
case *ast.FuncDecl:
return false
// After skipping all funcDecls we are sure that each value spec
// is a global declared variable or constant.
case *ast.ValueSpec:
i++
i += len(n.Names)
}
return true
})

View file

@ -102,13 +102,8 @@ func (c *funcScope) countLocals() int {
case *ast.ReturnStmt, *ast.IfStmt:
size++
// This handles the inline GenDecl like "var x = 2"
case *ast.GenDecl:
switch t := n.Specs[0].(type) {
case *ast.ValueSpec:
if len(t.Values) > 0 {
size++
}
}
case *ast.ValueSpec:
size += len(n.Names)
}
return true
})

View file

@ -19,3 +19,27 @@ func TestChangeGlobal(t *testing.T) {
eval(t, src, big.NewInt(42))
}
func TestMultiDeclaration(t *testing.T) {
src := `package foo
var a, b, c int
func Main() int {
a = 1
b = 2
c = 3
return a + b + c
}`
eval(t, src, big.NewInt(6))
}
func TestMultiDeclarationLocal(t *testing.T) {
src := `package foo
func Main() int {
var a, b, c int
a = 1
b = 2
c = 3
return a + b + c
}`
eval(t, src, big.NewInt(6))
}