Skip to content

Commit

Permalink
interp: fix type switch on arbitrary expressions
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mvertes authored Aug 25, 2022
1 parent e026215 commit 03ccda1
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
17 changes: 17 additions & 0 deletions _test/switch39.go
Original file line number Diff line number Diff line change
@@ -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 changes: 17 additions & 0 deletions _test/switch40.go
Original file line number Diff line number Diff line change
@@ -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
9 changes: 8 additions & 1 deletion interp/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit 03ccda1

Please sign in to comment.