Debian Codegraph @

gopls/internal/cache/typerefs/pkgrefs_test.go

raw symbols SCIP
1 // Copyright 2023 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 typerefs_test
6
7 import (
8 "bytes"
9 "context"
10 "flag"
11 "fmt"
12 "go/token"
13 "go/types"
14 "os"
15 "slices"
16 "strings"
17 "sync"
18 "testing"
19 "time"
20
21 "golang.org/x/tools/go/gcexportdata"
22 "golang.org/x/tools/go/packages"
23 "golang.org/x/tools/gopls/internal/cache/metadata"
24 "golang.org/x/tools/gopls/internal/cache/parsego"
25 "golang.org/x/tools/gopls/internal/cache/typerefs"
26 "golang.org/x/tools/gopls/internal/protocol"
27 "golang.org/x/tools/internal/astutil"
28 "golang.org/x/tools/internal/packagesinternal"
29 "golang.org/x/tools/internal/testenv"
30 )
31
32 var (
33 dir = flag.String("dir", "", "dir to run go/packages from")
34 query = flag.String("query", "std", "go/packages load query to use for walkdecl tests")
35 verify = flag.Bool("verify", true, "whether to verify reachable packages using export data (may be slow on large graphs)")
36 )
37
38 type (
39 packageName = metadata.PackageName
40 PackageID = metadata.PackageID
41 ImportPath = metadata.ImportPath
42 PackagePath = metadata.PackagePath
43 Metadata = metadata.Package
44 MetadataSource = metadata.Source
45 )
46
47 // TestBuildPackageGraph tests the BuildPackageGraph constructor, which uses
48 // the reference analysis of the Refs function to build a graph of
49 // relationships between packages.
50 //
51 // It simulates the operation of gopls at startup: packages are loaded via
52 // go/packages, and their syntax+metadata analyzed to determine which packages
53 // are reachable from others.
54 //
55 // The test then verifies that the 'load' graph (the graph of relationships in
56 // export data) is a subgraph of the 'reach' graph constructed by
57 // BuildPackageGraph. While doing so, it constructs some statistics about the
58 // relative sizes of these graphs, along with the 'transitive imports' graph,
59 // to report the effectiveness of the reachability analysis.
60 //
61 // The following flags affect this test:
62 // - dir sets the dir from which to run go/packages
63 // - query sets the go/packages query to load
64 // - verify toggles the verification w.r.t. the load graph (which may be
65 // prohibitively expensive with large queries).
66 func TestBuildPackageGraph(t *testing.T) {
67 if testing.Short() {
68 t.Skip("skipping with -short: loading the packages can take a long time with a cold cache")
69 }
70 testenv.NeedsGoBuild(t) // for go/packages
71
72 t0 := time.Now()
73 exports, meta, err := loadPackages(*query, *verify)
74 if err != nil {
75 t.Fatalf("loading failed: %v", err)
76 }
77 t.Logf("loaded %d packages in %v", len(exports), time.Since(t0))
78
79 ctx := context.Background()
80 var ids []PackageID
81 for id := range exports {
82 ids = append(ids, id)
83 }
84 slices.Sort(ids)
85
86 t0 = time.Now()
87 g, err := BuildPackageGraph(ctx, meta, ids, newParser().parse)
88 if err != nil {
89 t.Fatal(err)
90 }
91 t.Logf("building package graph took %v", time.Since(t0))
92
93 // Collect information about the edges between packages for later analysis.
94 //
95 // We compare the following package graphs:
96 // - the imports graph: edges are transitive imports
97 // - the reaches graph: edges are reachability relationships through syntax
98 // of imports (as defined in the package doc)
99 // - the loads graph: edges are packages loaded through the export data of
100 // imports
101 //
102 // By definition, loads < reaches < imports.
103 type edgeSet map[PackageID]map[PackageID]bool
104 var (
105 imports = make(edgeSet) // A imports B transitively
106 importedBy = make(edgeSet) // A is imported by B transitively
107 reaches = make(edgeSet) // A reaches B through top-level declaration syntax
108 reachedBy = make(edgeSet) // A is reached by B through top-level declaration syntax
109 loads = make(edgeSet) // A loads B through export data of its direct dependencies
110 loadedBy = make(edgeSet) // A is loaded by B through export data of B's direct dependencies
111 )
112 recordEdge := func(from, to PackageID, fwd, rev edgeSet) {
113 if fwd[from] == nil {
114 fwd[from] = make(map[PackageID]bool)
115 }
116 fwd[from][to] = true
117 if rev[to] == nil {
118 rev[to] = make(map[PackageID]bool)
119 }
120 rev[to][from] = true
121 }
122
123 exportedPackages := make(map[PackageID]*types.Package)
124 importPackage := func(id PackageID) *types.Package {
125 exportFile := exports[id]
126 if exportFile == "" {
127 return nil // no exported symbols
128 }
129 mp := meta.Metadata(id)
130 tpkg, ok := exportedPackages[id]
131 if !ok {
132 pkgPath := string(mp.PkgPath)
133 tpkg, err = importFromExportData(pkgPath, exportFile)
134 if err != nil {
135 t.Fatalf("importFromExportData(%s, %s) failed: %v", pkgPath, exportFile, err)
136 }
137 exportedPackages[id] = tpkg
138 }
139 return tpkg
140 }
141
142 for _, id := range ids {
143 pkg, err := g.Package(ctx, id)
144 if err != nil {
145 t.Fatal(err)
146 }
147 pkg.ReachesByDeps.Elems(func(id2 typerefs.IndexID) {
148 recordEdge(id, g.pkgIndex.PackageID(id2), reaches, reachedBy)
149 })
150
151 importMap := importMap(id, meta)
152 for _, id2 := range importMap {
153 recordEdge(id, id2, imports, importedBy)
154 }
155
156 if *verify {
157 for _, depID := range meta.Metadata(id).DepsByPkgPath {
158 tpkg := importPackage(depID)
159 if tpkg == nil {
160 continue
161 }
162 for _, imp := range tpkg.Imports() {
163 depID, ok := importMap[PackagePath(imp.Path())]
164 if !ok {
165 t.Errorf("import map (len: %d) for %s missing imported types.Package %s", len(importMap), id, imp.Path())
166 continue
167 }
168 recordEdge(id, depID, loads, loadedBy)
169 }
170 }
171
172 for depID := range loads[id] {
173 if !pkg.ReachesByDeps.Contains(depID) {
174 t.Errorf("package %s was imported by %s, but not detected as reachable", depID, id)
175 }
176 }
177 }
178 }
179
180 if testing.Verbose() {
181 fmt.Printf("%-52s%8s%8s%8s%8s%8s%8s\n", "package ID", "imp", "impBy", "reach", "reachBy", "load", "loadBy")
182 for _, id := range ids {
183 fmt.Printf("%-52s%8d%8d%8d%8d%8d%8d\n", id, len(imports[id]), len(importedBy[id]), len(reaches[id]), len(reachedBy[id]), len(loads[id]), len(loadedBy[id]))
184 }
185 fmt.Println(strings.Repeat("-", 100))
186 fmt.Printf("%-52s%8s%8s%8s%8s%8s%8s\n", "package ID", "imp", "impBy", "reach", "reachBy", "load", "loadBy")
187
188 avg := func(m edgeSet) float64 {
189 var avg float64
190 for _, id := range ids {
191 s := m[id]
192 avg += float64(len(s)) / float64(len(ids))
193 }
194 return avg
195 }
196 fmt.Printf("%52s%8.1f%8.1f%8.1f%8.1f%8.1f%8.1f\n", "averages:", avg(imports), avg(importedBy), avg(reaches), avg(reachedBy), avg(loads), avg(loadedBy))
197 }
198 }
199
200 func importMap(id PackageID, meta MetadataSource) map[PackagePath]PackageID {
201 imports := make(map[PackagePath]PackageID)
202 var recordIDs func(PackageID)
203 recordIDs = func(id PackageID) {
204 mp := meta.Metadata(id)
205 if _, ok := imports[mp.PkgPath]; ok {
206 return
207 }
208 imports[mp.PkgPath] = id
209 for _, id := range mp.DepsByPkgPath {
210 recordIDs(id)
211 }
212 }
213 for _, id := range meta.Metadata(id).DepsByPkgPath {
214 recordIDs(id)
215 }
216 return imports
217 }
218
219 func importFromExportData(pkgPath, exportFile string) (*types.Package, error) {
220 file, err := os.Open(exportFile)
221 if err != nil {
222 return nil, err
223 }
224 r, err := gcexportdata.NewReader(file)
225 if err != nil {
226 file.Close() // ignore error
227 return nil, err
228 }
229 fset := token.NewFileSet()
230 tpkg, err := gcexportdata.Read(r, fset, make(map[string]*types.Package), pkgPath)
231 file.Close() // ignore error
232 if err != nil {
233 return nil, err
234 }
235 // The export file reported by go/packages is produced by the compiler, which
236 // has additional package dependencies due to inlining.
237 //
238 // Export and re-import so that we only observe dependencies from the
239 // exported API.
240 var out bytes.Buffer
241 err = gcexportdata.Write(&out, fset, tpkg)
242 if err != nil {
243 return nil, err
244 }
245 return gcexportdata.Read(&out, token.NewFileSet(), make(map[string]*types.Package), pkgPath)
246 }
247
248 func BenchmarkBuildPackageGraph(b *testing.B) {
249 t0 := time.Now()
250 exports, meta, err := loadPackages(*query, *verify)
251 if err != nil {
252 b.Fatalf("loading failed: %v", err)
253 }
254 b.Logf("loaded %d packages in %v", len(exports), time.Since(t0))
255 ctx := context.Background()
256 var ids []PackageID
257 for id := range exports {
258 ids = append(ids, id)
259 }
260
261 for b.Loop() {
262 _, err := BuildPackageGraph(ctx, meta, ids, newParser().parse)
263 if err != nil {
264 b.Fatal(err)
265 }
266 }
267 }
268
269 type memoizedParser struct {
270 mu sync.Mutex
271 files map[protocol.DocumentURI]*futureParse
272 }
273
274 type futureParse struct {
275 done chan struct{}
276 pgf *parsego.File
277 err error
278 }
279
280 func newParser() *memoizedParser {
281 return &memoizedParser{
282 files: make(map[protocol.DocumentURI]*futureParse),
283 }
284 }
285
286 func (p *memoizedParser) parse(ctx context.Context, uri protocol.DocumentURI) (*parsego.File, error) {
287 doParse := func(ctx context.Context, uri protocol.DocumentURI) (*parsego.File, error) {
288 // TODO(adonovan): hoist this operation outside the benchmark critsec.
289 content, err := os.ReadFile(uri.Path())
290 if err != nil {
291 return nil, err
292 }
293 content = astutil.PurgeFuncBodies(content)
294 pgf, _ := parsego.Parse(ctx, token.NewFileSet(), uri, content, parsego.Full, false)
295 return pgf, nil
296 }
297
298 p.mu.Lock()
299 fut, ok := p.files[uri]
300 if ok {
301 p.mu.Unlock()
302 select {
303 case <-fut.done:
304 case <-ctx.Done():
305 return nil, ctx.Err()
306 }
307 } else {
308 fut = &futureParse{done: make(chan struct{})}
309 p.files[uri] = fut
310 p.mu.Unlock()
311 fut.pgf, fut.err = doParse(ctx, uri)
312 close(fut.done)
313 }
314 return fut.pgf, fut.err
315 }
316
317 type mapMetadataSource struct {
318 m map[PackageID]*Metadata
319 }
320
321 func (s mapMetadataSource) Metadata(id PackageID) *Metadata {
322 return s.m[id]
323 }
324
325 // This function is a compressed version of snapshot.load from the
326 // internal/cache package, for use in testing.
327 //
328 // TODO(rfindley): it may be valuable to extract this logic from the snapshot,
329 // since it is otherwise standalone.
330 func loadPackages(query string, needExport bool) (map[PackageID]string, MetadataSource, error) {
331 cfg := &packages.Config{
332 Dir: *dir,
333 Mode: packages.NeedName |
334 packages.NeedFiles |
335 packages.NeedCompiledGoFiles |
336 packages.NeedImports |
337 packages.NeedDeps |
338 packages.NeedTypesSizes |
339 packages.NeedModule |
340 packages.NeedEmbedFiles |
341 packages.LoadMode(packagesinternal.DepsErrors) |
342 packages.NeedForTest,
343 Tests: true,
344 }
345 if needExport {
346 cfg.Mode |= packages.NeedExportFile // ExportFile is not requested by gopls: this is used to verify reachability
347 }
348 pkgs, err := packages.Load(cfg, query)
349 if err != nil {
350 return nil, nil, err
351 }
352
353 meta := make(map[PackageID]*Metadata)
354 var buildMetadata func(pkg *packages.Package)
355 buildMetadata = func(pkg *packages.Package) {
356 id := PackageID(pkg.ID)
357 if meta[id] != nil {
358 return
359 }
360 mp := &Metadata{
361 ID: id,
362 PkgPath: PackagePath(pkg.PkgPath),
363 Name: packageName(pkg.Name),
364 ForTest: PackagePath(pkg.ForTest),
365 TypesSizes: pkg.TypesSizes,
366 LoadDir: cfg.Dir,
367 Module: pkg.Module,
368 Errors: pkg.Errors,
369 DepsErrors: packagesinternal.GetDepsErrors(pkg),
370 }
371 meta[id] = mp
372
373 for _, filename := range pkg.CompiledGoFiles {
374 mp.CompiledGoFiles = append(mp.CompiledGoFiles, protocol.URIFromPath(filename))
375 }
376 for _, filename := range pkg.GoFiles {
377 mp.GoFiles = append(mp.GoFiles, protocol.URIFromPath(filename))
378 }
379
380 mp.DepsByImpPath = make(map[ImportPath]PackageID)
381 mp.DepsByPkgPath = make(map[PackagePath]PackageID)
382 for importPath, imported := range pkg.Imports {
383 importPath := ImportPath(importPath)
384
385 // see note in gopls/internal/cache/load.go for an explanation of this check.
386 if importPath != "unsafe" && len(imported.CompiledGoFiles) == 0 {
387 mp.DepsByImpPath[importPath] = "" // missing
388 continue
389 }
390
391 mp.DepsByImpPath[importPath] = PackageID(imported.ID)
392 mp.DepsByPkgPath[PackagePath(imported.PkgPath)] = PackageID(imported.ID)
393 buildMetadata(imported)
394 }
395 }
396
397 exportFiles := make(map[PackageID]string)
398 for _, pkg := range pkgs {
399 exportFiles[PackageID(pkg.ID)] = pkg.ExportFile
400 buildMetadata(pkg)
401 }
402 return exportFiles, &mapMetadataSource{meta}, nil
403 }