| 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. |
| 4 | |
| 5 | // No testdata on Android. |
| 6 | |
| 7 | //go:build !android |
| 8 | |
| 9 | package ssautil_test |
| 10 | |
| 11 | import ( |
| 12 | "strings" |
| 13 | "testing" |
| 14 | |
| 15 | "golang.org/x/tools/go/ssa" |
| 16 | "golang.org/x/tools/go/ssa/ssautil" |
| 17 | "golang.org/x/tools/internal/testfiles" |
| 18 | "golang.org/x/tools/txtar" |
| 19 | ) |
| 20 | |
| 21 | func TestSwitches(t *testing.T) { |
| 22 | archive, err := txtar.ParseFile("testdata/switches.txtar") |
| 23 | if err != nil { |
| 24 | t.Fatal(err) |
| 25 | } |
| 26 | ppkgs := testfiles.LoadPackages(t, archive, ".") |
| 27 | if len(ppkgs) != 1 { |
| 28 | t.Fatalf("Expected to load one package but got %d", len(ppkgs)) |
| 29 | } |
| 30 | f := ppkgs[0].Syntax[0] |
| 31 | |
| 32 | prog, _ := ssautil.Packages(ppkgs, ssa.BuilderMode(0)) |
| 33 | mainPkg := prog.Package(ppkgs[0].Types) |
| 34 | mainPkg.Build() |
| 35 | |
| 36 | for _, mem := range mainPkg.Members { |
| 37 | if fn, ok := mem.(*ssa.Function); ok { |
| 38 | if fn.Synthetic != "" { |
| 39 | continue // e.g. init() |
| 40 | } |
| 41 | // Each (multi-line) "switch" comment within |
| 42 | // this function must match the printed form |
| 43 | // of a ConstSwitch. |
| 44 | var wantSwitches []string |
| 45 | for _, c := range f.Comments { |
| 46 | if fn.Syntax().Pos() <= c.Pos() && c.Pos() < fn.Syntax().End() { |
| 47 | text := strings.TrimSpace(c.Text()) |
| 48 | if strings.HasPrefix(text, "switch ") { |
| 49 | wantSwitches = append(wantSwitches, text) |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | switches := ssautil.Switches(fn) |
| 55 | if len(switches) != len(wantSwitches) { |
| 56 | t.Errorf("in %s, found %d switches, want %d", fn, len(switches), len(wantSwitches)) |
| 57 | } |
| 58 | for i, sw := range switches { |
| 59 | got := sw.String() |
| 60 | if i >= len(wantSwitches) { |
| 61 | continue |
| 62 | } |
| 63 | want := wantSwitches[i] |
| 64 | if got != want { |
| 65 | t.Errorf("in %s, found switch %d: got <<%s>>, want <<%s>>", fn, i, got, want) |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | } |