-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexample_test.go
59 lines (50 loc) · 959 Bytes
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package controlflow
import (
"go/ast"
"go/parser"
"go/printer"
"go/token"
"os"
)
func ExampleElimGotos() {
code := `
package branchy
func isGoodNumber(x int) bool {
if x%3 == 0 {
goto fail
} else if x%5 == 0 {
goto fail
}
return true
fail:
return false
}
`
// Parse the code
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "code.go", code, 0)
if err != nil {
panic(err)
}
// List of statements in the function's body
body := file.Decls[0].(*ast.FuncDecl).Body.List
// Rewrite the function body without goto statements
newBody := ElimGotos(body)
// Print the result
config := printer.Config{Mode: printer.UseSpaces, Tabwidth: 4}
config.Fprint(os.Stdout, token.NewFileSet(), newBody)
// Output:
// gotofail := false
// if x%3 == 0 {
// gotofail = true
// } else {
// gotofail = x%5 == 0
// }
// if !gotofail {
// return true
// }
// return false
if err != nil {
panic(err)
}
}