Skip to content

Commit

Permalink
fix: correct control flow graph for some switch statements
Browse files Browse the repository at this point in the history
  • Loading branch information
mvertes authored Mar 9, 2020
1 parent d29b0a4 commit 6e33f89
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 15 deletions.
15 changes: 15 additions & 0 deletions _test/switch23.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package main

func getType() string { return "T1" }

func main() {
switch getType() {
case "T1":
println("T1")
default:
println("default")
}
}

// Output:
// T1
16 changes: 16 additions & 0 deletions _test/switch24.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package main

func main() {
a := 3
switch a + 2 {
case 5:
println(5)
default:
println("default")
}
println("bye")
}

// Output:
// 5
// bye
18 changes: 18 additions & 0 deletions _test/switch25.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package main

func main() {
a := 2
switch {
case a == 1:
println(1)
case a == 2:
println(2)
default:
println("default")
}
println("bye")
}

// Output:
// 2
// bye
18 changes: 18 additions & 0 deletions _test/switch26.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package main

func main() {
a := 1
switch a := 2; {
case a == 1:
println(1)
case a == 2:
println(2)
default:
println("default")
}
println(a)
}

// Output:
// 2
// 1
21 changes: 6 additions & 15 deletions interp/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -1326,14 +1326,8 @@ func (interp *Interpreter) cfg(root *node, pkgID string) ([]*node, error) {
}
c := clauses[l-1]
c.tnext = c.lastChild().start
if n.child[0].action == aAssign &&
(n.child[0].child[0].kind != typeAssertExpr || len(n.child[0].child[0].child) > 1) {
// switch init statement is defined
n.start = n.child[0].start
n.child[0].tnext = sbn.start
} else {
n.start = sbn.start
}
n.start = n.child[0].start
n.child[0].tnext = sbn.start
sc = sc.pop()

case switchIfStmt: // like an if-else chain
Expand All @@ -1360,16 +1354,13 @@ func (interp *Interpreter) cfg(root *node, pkgID string) ([]*node, error) {
// If last case body statement is a fallthrough, then jump to next case body
if i < l-1 && len(body.child) > 0 && body.lastChild().kind == fallthroughtStmt {
body.tnext = clauses[i+1].lastChild().start
} else {
body.tnext = n
}
}
sbn.start = clauses[0].start
if n.child[0].action == aAssign {
// switch init statement is defined
n.start = n.child[0].start
n.child[0].tnext = sbn.start
} else {
n.start = sbn.start
}
n.start = n.child[0].start
n.child[0].tnext = sbn.start
sc = sc.pop()

case typeAssertExpr:
Expand Down

0 comments on commit 6e33f89

Please sign in to comment.