Skip to content

Commit

Permalink
interp: fix handling of redeclared variables in short declaration.
Browse files Browse the repository at this point in the history
Fixes #1640.
  • Loading branch information
mvertes authored Jul 18, 2024
1 parent 77c1ce0 commit 94de0aa
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 1 deletion.
23 changes: 23 additions & 0 deletions _test/issue-1640.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package main

import (
"errors"
)

func ShortVariableDeclarations() (i int, err error) {
r, err := 1, errors.New("test")
i = r
return
}

func main() {
_, er := ShortVariableDeclarations()
if er != nil {
println("ShortVariableDeclarations ok")
} else {
println("ShortVariableDeclarations not ok")
}
}

// Output:
// ShortVariableDeclarations ok
2 changes: 1 addition & 1 deletion interp/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,7 @@ func (interp *Interpreter) cfg(root *node, sc *scope, importPath, pkgName string
if dest.typ.incomplete {
return
}
if sc.global {
if sc.global || sc.isRedeclared(dest) {
// Do not overload existing symbols (defined in GTA) in global scope.
sym, _, _ = sc.lookup(dest.ident)
}
Expand Down
7 changes: 7 additions & 0 deletions interp/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -1400,6 +1400,13 @@ func call(n *node) {
}
runCfg(def.child[3].start, nf, def, n)

// Set return values
for i, v := range rvalues {
if v != nil {
v(f).Set(nf.data[i])
}
}

// Handle branching according to boolean result
if fnext != nil && !nf.data[0].Bool() {
return fnext
Expand Down
8 changes: 8 additions & 0 deletions interp/scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,14 @@ func (s *scope) lookup(ident string) (*symbol, int, bool) {
return nil, 0, false
}

func (s *scope) isRedeclared(n *node) bool {
if !isNewDefine(n, s) {
return false
}
// Existing symbol in the scope indicates a redeclaration.
return s.sym[n.ident] != nil
}

func (s *scope) rangeChanType(n *node) *itype {
if sym, _, found := s.lookup(n.child[1].ident); found {
if t := sym.typ; len(n.child) == 3 && t != nil && (t.cat == chanT || t.cat == chanRecvT) {
Expand Down

0 comments on commit 94de0aa

Please sign in to comment.