Debian Codegraph @

go/callgraph/cha/cha_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 // No testdata on Android.
6
7 //go:build !android
8
9 package cha_test
10
11 import (
12 "bytes"
13 "fmt"
14 "go/ast"
15 "go/token"
16 "go/types"
17 "os"
18 "path/filepath"
19 "sort"
20 "strings"
21 "testing"
22
23 "golang.org/x/tools/go/callgraph"
24 "golang.org/x/tools/go/callgraph/cha"
25 "golang.org/x/tools/go/packages"
26 "golang.org/x/tools/go/ssa"
27 "golang.org/x/tools/go/ssa/ssautil"
28 "golang.org/x/tools/internal/testenv"
29 "golang.org/x/tools/internal/testfiles"
30 "golang.org/x/tools/txtar"
31 )
32
33 var inputs = []string{
34 "testdata/func.go",
35 "testdata/iface.go",
36 "testdata/recv.go",
37 "testdata/issue23925.go",
38 }
39
40 func expectation(f *ast.File) (string, token.Pos) {
41 for _, c := range f.Comments {
42 text := strings.TrimSpace(c.Text())
43 if t, ok := strings.CutPrefix(text, "WANT:\n"); ok {
44 return t, c.Pos()
45 }
46 }
47 return "", token.NoPos
48 }
49
50 // TestCHA runs CHA on each file in inputs, prints the dynamic edges of
51 // the call graph, and compares it with the golden results embedded in
52 // the WANT comment at the end of the file.
53 func TestCHA(t *testing.T) {
54 for _, filename := range inputs {
55 pkg, ssapkg := loadFile(t, filename, ssa.InstantiateGenerics)
56
57 want, pos := expectation(pkg.Syntax[0])
58 if pos == token.NoPos {
59 t.Error(fmt.Errorf("No WANT: comment in %s", filename))
60 continue
61 }
62
63 cg := cha.CallGraph(ssapkg.Prog)
64
65 if got := printGraph(cg, pkg.Types, "dynamic", "Dynamic calls"); got != want {
66 t.Errorf("%s: got:\n%s\nwant:\n%s",
67 ssapkg.Prog.Fset.Position(pos), got, want)
68 }
69 }
70 }
71
72 // TestCHAGenerics is TestCHA tailored for testing generics,
73 func TestCHAGenerics(t *testing.T) {
74 filename := "testdata/generics.go"
75 pkg, ssapkg := loadFile(t, filename, ssa.InstantiateGenerics)
76
77 want, pos := expectation(pkg.Syntax[0])
78 if pos == token.NoPos {
79 t.Fatal(fmt.Errorf("No WANT: comment in %s", filename))
80 }
81
82 cg := cha.CallGraph(ssapkg.Prog)
83
84 if got := printGraph(cg, pkg.Types, "", "All calls"); got != want {
85 t.Errorf("%s: got:\n%s\nwant:\n%s",
86 ssapkg.Prog.Fset.Position(pos), got, want)
87 }
88 }
89
90 // TestCHAUnexported tests call resolution for unexported methods.
91 func TestCHAUnexported(t *testing.T) {
92 // The two packages below each have types with methods called "m".
93 // Each of these methods should only be callable by functions in their
94 // own package, because they are unexported.
95 //
96 // In particular:
97 // - main.main can call (main.S1).m
98 // - p2.Foo can call (p2.S2).m
99 // - main.main cannot call (p2.S2).m
100 // - p2.Foo cannot call (main.S1).m
101 //
102 // We use CHA to build a callgraph, then check that it has the
103 // appropriate set of edges.
104
105 const src = `
106 -- go.mod --
107 module x.io
108 go 1.18
109
110 -- main/main.go --
111 package main
112
113 import "x.io/p2"
114
115 type I1 interface { m() }
116 type S1 struct { p2.I2 }
117 func (s S1) m() { }
118 func main() {
119 var s S1
120 var o I1 = s
121 o.m()
122 p2.Foo(s)
123 }
124
125 -- p2/p2.go --
126 package p2
127
128 type I2 interface { m() }
129 type S2 struct { }
130 func (s S2) m() { }
131 func Foo(i I2) { i.m() }
132 `
133
134 want := `All calls
135 x.io/main.init --> x.io/p2.init
136 x.io/main.main --> (x.io/main.S1).m
137 x.io/main.main --> x.io/p2.Foo
138 x.io/p2.Foo --> (x.io/p2.S2).m`
139
140 pkgs := testfiles.LoadPackages(t, txtar.Parse([]byte(src)), "./...")
141 prog, _ := ssautil.Packages(pkgs, ssa.InstantiateGenerics)
142 prog.Build()
143
144 cg := cha.CallGraph(prog)
145
146 // The graph is easier to read without synthetic nodes.
147 cg.DeleteSyntheticNodes()
148
149 if got := printGraph(cg, nil, "", "All calls"); got != want {
150 t.Errorf("cha.CallGraph: got:\n%s\nwant:\n%s", got, want)
151 }
152 }
153
154 // loadFile loads a built SSA package for a single-file "x.io/main" package.
155 // (Ideally all uses would be converted over to txtar files with explicit go.mod files.)
156 func loadFile(t testing.TB, filename string, mode ssa.BuilderMode) (*packages.Package, *ssa.Package) {
157 testenv.NeedsGoPackages(t)
158
159 data, err := os.ReadFile(filename)
160 if err != nil {
161 t.Fatal(err)
162 }
163 dir := t.TempDir()
164 cfg := &packages.Config{
165 Mode: packages.LoadAllSyntax,
166 Dir: dir,
167 Overlay: map[string][]byte{
168 filepath.Join(dir, "go.mod"): []byte("module x.io\ngo 1.22"),
169 filepath.Join(dir, "main/main.go"): data,
170 },
171 Env: append(os.Environ(), "GO111MODULES=on", "GOPATH=", "GOWORK=off", "GOPROXY=off"),
172 }
173 pkgs, err := packages.Load(cfg, "./main")
174 if err != nil {
175 t.Fatal(err)
176 }
177 if num := packages.PrintErrors(pkgs); num > 0 {
178 t.Fatalf("packages contained %d errors", num)
179 }
180 prog, ssapkgs := ssautil.Packages(pkgs, mode)
181 prog.Build()
182 return pkgs[0], ssapkgs[0]
183 }
184
185 // printGraph returns a string representation of cg involving only edges
186 // whose description contains edgeMatch. The string representation is
187 // prefixed with a desc line.
188 func printGraph(cg *callgraph.Graph, from *types.Package, edgeMatch string, desc string) string {
189 var edges []string
190 callgraph.GraphVisitEdges(cg, func(e *callgraph.Edge) error {
191 if strings.Contains(e.Description(), edgeMatch) {
192 edges = append(edges, fmt.Sprintf("%s --> %s",
193 e.Caller.Func.RelString(from),
194 e.Callee.Func.RelString(from)))
195 }
196 return nil
197 })
198 sort.Strings(edges)
199
200 var buf bytes.Buffer
201 buf.WriteString(desc + "\n")
202 for _, edge := range edges {
203 fmt.Fprintf(&buf, " %s\n", edge)
204 }
205 return strings.TrimSpace(buf.String())
206 }