interp: fix type switch on arbitrary expressions

If the value on which to type-switch was already set (i.e. a variable),
there was no problem. But if it had to be obtained through a complex
expression (func call, array index, etc...), then the code to retrieve
the value prior type-switch was not scheduled. This is now fixed.

This issue is nasty because the behavior is silently changed,
leading potentially to further unrelated issues or runtime panics.

Fixes #1444.
This commit is contained in:
Marc Vertes
2022-08-25 12:04:08 +02:00
committed by GitHub
parent e02621577f
commit 03ccda1a69
3 changed files with 42 additions and 1 deletions

17
_test/switch39.go Normal file
View File

@@ -0,0 +1,17 @@
package main
func f(params ...interface{}) {
switch p0 := params[0].(type) {
case string:
println("string:", p0)
default:
println("not a string")
}
}
func main() {
f("Hello")
}
// Output:
// string: Hello

17
_test/switch40.go Normal file
View File

@@ -0,0 +1,17 @@
package main
func f(params ...interface{}) {
switch params[0].(type) {
case string:
println("a string")
default:
println("not a string")
}
}
func main() {
f("Hello")
}
// Output:
// a string

View File

@@ -2051,7 +2051,14 @@ func (interp *Interpreter) cfg(root *node, sc *scope, importPath, pkgName string
}
sbn.start = clauses[0].start
n.start = n.child[0].start
n.child[0].tnext = sbn.start
if n.kind == typeSwitch {
// Handle the typeSwitch init (the type assert expression).
init := n.child[1].lastChild().child[0]
init.tnext = sbn.start
n.child[0].tnext = init.start
} else {
n.child[0].tnext = sbn.start
}
case switchIfStmt: // like an if-else chain
sc = sc.pop()