compiler: count the number of variables correctly
This commit is contained in:
parent
0629479560
commit
b4bad11699
3 changed files with 29 additions and 10 deletions
|
@ -70,16 +70,16 @@ func (c *codegen) traverseGlobals(f ast.Node) {
|
||||||
|
|
||||||
// countGlobals counts the global variables in the program to add
|
// countGlobals counts the global variables in the program to add
|
||||||
// them with the stack size of the function.
|
// 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 {
|
ast.Inspect(f, func(node ast.Node) bool {
|
||||||
switch node.(type) {
|
switch n := node.(type) {
|
||||||
// Skip all function declarations.
|
// Skip all function declarations.
|
||||||
case *ast.FuncDecl:
|
case *ast.FuncDecl:
|
||||||
return false
|
return false
|
||||||
// After skipping all funcDecls we are sure that each value spec
|
// After skipping all funcDecls we are sure that each value spec
|
||||||
// is a global declared variable or constant.
|
// is a global declared variable or constant.
|
||||||
case *ast.ValueSpec:
|
case *ast.ValueSpec:
|
||||||
i++
|
i += len(n.Names)
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
|
|
|
@ -102,13 +102,8 @@ func (c *funcScope) countLocals() int {
|
||||||
case *ast.ReturnStmt, *ast.IfStmt:
|
case *ast.ReturnStmt, *ast.IfStmt:
|
||||||
size++
|
size++
|
||||||
// This handles the inline GenDecl like "var x = 2"
|
// This handles the inline GenDecl like "var x = 2"
|
||||||
case *ast.GenDecl:
|
case *ast.ValueSpec:
|
||||||
switch t := n.Specs[0].(type) {
|
size += len(n.Names)
|
||||||
case *ast.ValueSpec:
|
|
||||||
if len(t.Values) > 0 {
|
|
||||||
size++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
|
|
|
@ -19,3 +19,27 @@ func TestChangeGlobal(t *testing.T) {
|
||||||
|
|
||||||
eval(t, src, big.NewInt(42))
|
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))
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue