Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / honnef.co / go / tools@v0.0.1-2020.1.5 / callgraph / static / static_test.go
1 // Copyright 2014 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 //lint:file-ignore SA1019 go/callgraph's test suite is built around the deprecated go/loader. We'll leave fixing that to upstream.
6
7 package static_test
8
9 import (
10         "fmt"
11         "go/parser"
12         "reflect"
13         "sort"
14         "testing"
15
16         "golang.org/x/tools/go/loader"
17         "honnef.co/go/tools/callgraph"
18         "honnef.co/go/tools/callgraph/static"
19         "honnef.co/go/tools/ir/irutil"
20 )
21
22 const input = `package P
23
24 type C int
25 func (C) f()
26
27 type I interface{f()}
28
29 func f() {
30         p := func() {}
31         g()
32         p() // IR constant propagation => static
33
34         if unknown {
35                 p = h
36         }
37         p() // dynamic
38
39         C(0).f()
40 }
41
42 func g() {
43         var i I = C(0)
44         i.f()
45 }
46
47 func h()
48
49 var unknown bool
50 `
51
52 func TestStatic(t *testing.T) {
53         conf := loader.Config{ParserMode: parser.ParseComments}
54         f, err := conf.ParseFile("P.go", input)
55         if err != nil {
56                 t.Fatal(err)
57         }
58
59         conf.CreateFromFiles("P", f)
60         iprog, err := conf.Load()
61         if err != nil {
62                 t.Fatal(err)
63         }
64
65         P := iprog.Created[0].Pkg
66
67         prog := irutil.CreateProgram(iprog, 0)
68         prog.Build()
69
70         cg := static.CallGraph(prog)
71
72         var edges []string
73         callgraph.GraphVisitEdges(cg, func(e *callgraph.Edge) error {
74                 edges = append(edges, fmt.Sprintf("%s -> %s",
75                         e.Caller.Func.RelString(P),
76                         e.Callee.Func.RelString(P)))
77                 return nil
78         })
79         sort.Strings(edges)
80
81         want := []string{
82                 "(*C).f -> (C).f",
83                 "f -> (C).f",
84                 "f -> f$1",
85                 "f -> g",
86         }
87         if !reflect.DeepEqual(edges, want) {
88                 t.Errorf("Got edges %v, want %v", edges, want)
89         }
90 }