interp: fix handling of redeclared variables in short declaration.

Fixes #1640.
This commit is contained in:
Marc Vertes
2024-07-18 12:34:04 +02:00
committed by GitHub
parent 77c1ce01c4
commit 94de0aa68c
4 changed files with 39 additions and 1 deletions
+23
View File
@@ -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
+1 -1
View File
@@ -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)
}
+7
View File
@@ -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
+8
View File
@@ -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) {