1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // No testdata on Android.
18 "golang.org/x/tools/go/loader"
19 "honnef.co/go/tools/ir"
22 func TestSwitches(t *testing.T) {
23 conf := loader.Config{ParserMode: parser.ParseComments}
24 f, err := conf.ParseFile("testdata/switches.go", nil)
30 conf.CreateFromFiles("main", f)
31 iprog, err := conf.Load()
37 prog := CreateProgram(iprog, 0)
38 mainPkg := prog.Package(iprog.Created[0].Pkg)
41 for _, mem := range mainPkg.Members {
42 if fn, ok := mem.(*ir.Function); ok {
43 if fn.Synthetic != "" {
44 continue // e.g. init()
46 // Each (multi-line) "switch" comment within
47 // this function must match the printed form
49 var wantSwitches []string
50 for _, c := range f.Comments {
51 if fn.Source().Pos() <= c.Pos() && c.Pos() < fn.Source().End() {
52 text := strings.TrimSpace(c.Text())
53 if strings.HasPrefix(text, "switch ") {
54 wantSwitches = append(wantSwitches, text)
59 switches := Switches(fn)
60 if len(switches) != len(wantSwitches) {
61 t.Errorf("in %s, found %d switches, want %d", fn, len(switches), len(wantSwitches))
63 for i, sw := range switches {
64 got := sw.testString()
65 if i >= len(wantSwitches) {
68 want := wantSwitches[i]
70 t.Errorf("in %s, found switch %d: got <<%s>>, want <<%s>>", fn, i, got, want)
77 func (sw *Switch) testString() string {
78 // same as the actual String method, but use the second to last
79 // instruction instead, to skip over all the phi and sigma nodes
82 if sw.ConstCases != nil {
83 fmt.Fprintf(&buf, "switch %s {\n", sw.X.Name())
84 for _, c := range sw.ConstCases {
85 n := len(c.Body.Instrs) - 2
89 fmt.Fprintf(&buf, "case %s: %s\n", c.Value.Name(), c.Body.Instrs[n])
92 fmt.Fprintf(&buf, "switch %s.(type) {\n", sw.X.Name())
93 for _, c := range sw.TypeCases {
94 n := len(c.Body.Instrs) - 2
98 fmt.Fprintf(&buf, "case %s %s: %s\n",
99 c.Binding.Name(), c.Type, c.Body.Instrs[n])
102 if sw.Default != nil {
103 n := len(sw.Default.Instrs) - 2
107 fmt.Fprintf(&buf, "default: %s\n", sw.Default.Instrs[n])
109 fmt.Fprintf(&buf, "}")