Debian Codegraph @

go/callgraph/static/static_test.go

raw symbols SCIP
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 package static_test
6
7 import (
8 "fmt"
9 "reflect"
10 "sort"
11 "testing"
12
13 "golang.org/x/tools/go/callgraph"
14 "golang.org/x/tools/go/callgraph/static"
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 const input = `
22
23 -- go.mod --
24 module x.io
25
26 go 1.22
27
28 -- p/p.go --
29 package main
30
31 type C int
32 func (C) f()
33
34 type I interface{f()}
35
36 func f() {
37 p := func() {}
38 g()
39 p() // SSA constant propagation => static
40
41 if unknown {
42 p = h
43 }
44 p() // dynamic
45
46 C(0).f()
47 }
48
49 func g() {
50 var i I = C(0)
51 i.f()
52 }
53
54 func h()
55
56 var unknown bool
57
58 func main() {
59 }
60 `
61
62 const genericsInput = `
63
64 -- go.mod --
65 module x.io
66
67 go 1.22
68
69 -- p/p.go --
70 package p
71
72 type I interface {
73 F()
74 }
75
76 type A struct{}
77
78 func (a A) F() {}
79
80 type B struct{}
81
82 func (b B) F() {}
83
84 func instantiated[X I](x X) {
85 x.F()
86 }
87
88 func Bar() {}
89
90 func f(h func(), a A, b B) {
91 h()
92
93 instantiated[A](a)
94 instantiated[B](b)
95 }
96 `
97
98 func TestStatic(t *testing.T) {
99 for _, e := range []struct {
100 input string
101 want []string
102 }{
103 {input, []string{
104 "(*C).f -> (C).f",
105 "f -> (C).f",
106 "f -> f$1",
107 "f -> g",
108 }},
109 {genericsInput, []string{
110 "(*A).F -> (A).F",
111 "(*B).F -> (B).F",
112 "f -> instantiated[x.io/p.A]",
113 "f -> instantiated[x.io/p.B]",
114 "instantiated[x.io/p.A] -> (A).F",
115 "instantiated[x.io/p.B] -> (B).F",
116 }},
117 } {
118 pkgs := testfiles.LoadPackages(t, txtar.Parse([]byte(e.input)), "./p")
119 prog, _ := ssautil.Packages(pkgs, ssa.InstantiateGenerics)
120 prog.Build()
121 p := pkgs[0].Types
122
123 cg := static.CallGraph(prog)
124
125 var edges []string
126 callgraph.GraphVisitEdges(cg, func(e *callgraph.Edge) error {
127 edges = append(edges, fmt.Sprintf("%s -> %s",
128 e.Caller.Func.RelString(p),
129 e.Callee.Func.RelString(p)))
130 return nil
131 })
132 sort.Strings(edges)
133
134 if !reflect.DeepEqual(edges, e.want) {
135 t.Errorf("Got edges %v, want %v", edges, e.want)
136 }
137 }
138 }