Debian Codegraph @

gopls/internal/cache/typerefs/pkggraph_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 // This file is logically part of the test in pkgrefs_test.go: that
8 // file defines the test assertion logic; this file provides a
9 // reference implementation of a client of the typerefs package.
10
11 import (
12 "bytes"
13 "context"
14 "fmt"
15 "os"
16 "runtime"
17 "sync"
18
19 "golang.org/x/sync/errgroup"
20 "golang.org/x/tools/gopls/internal/cache/metadata"
21 "golang.org/x/tools/gopls/internal/cache/parsego"
22 "golang.org/x/tools/gopls/internal/cache/typerefs"
23 "golang.org/x/tools/gopls/internal/protocol"
24 )
25
26 const (
27 // trace enables additional trace output to stdout, for debugging.
28 //
29 // Warning: produces a lot of output! Best to run with small package queries.
30 trace = false
31 )
32
33 // A Package holds reference information for a single package.
34 type Package struct {
35 // metapkg holds metapkg about this package and its dependencies.
36 metapkg *metadata.Package
37
38 // transitiveRefs records, for each exported declaration in the package, the
39 // transitive set of packages within the containing graph that are
40 // transitively reachable through references, starting with the given decl.
41 transitiveRefs map[string]*typerefs.PackageSet
42
43 // ReachesByDeps records the set of packages in the containing graph whose
44 // syntax may affect the current package's types. See the package
45 // documentation for more details of what this means.
46 ReachesByDeps *typerefs.PackageSet
47 }
48
49 // A PackageGraph represents a fully analyzed graph of packages and their
50 // dependencies.
51 type PackageGraph struct {
52 pkgIndex *typerefs.PackageIndex
53 meta metadata.Source
54 parse func(context.Context, protocol.DocumentURI) (*parsego.File, error)
55
56 mu sync.Mutex
57 packages map[metadata.PackageID]*futurePackage
58 }
59
60 // BuildPackageGraph analyzes the package graph for the requested ids, whose
61 // metadata is described by meta.
62 //
63 // The provided parse function is used to parse the CompiledGoFiles of each package.
64 //
65 // The resulting PackageGraph is fully evaluated, and may be investigated using
66 // the Package method.
67 //
68 // See the package documentation for more information on the package reference
69 // algorithm.
70 func BuildPackageGraph(ctx context.Context, meta metadata.Source, ids []metadata.PackageID, parse func(context.Context, protocol.DocumentURI) (*parsego.File, error)) (*PackageGraph, error) {
71 g := &PackageGraph{
72 pkgIndex: typerefs.NewPackageIndex(),
73 meta: meta,
74 parse: parse,
75 packages: make(map[metadata.PackageID]*futurePackage),
76 }
77 metadata.SortPostOrder(meta, ids)
78
79 workers := runtime.GOMAXPROCS(0)
80 if trace {
81 workers = 1
82 }
83
84 var eg errgroup.Group
85 eg.SetLimit(workers)
86 for _, id := range ids {
87 eg.Go(func() error {
88 _, err := g.Package(ctx, id)
89 return err
90 })
91 }
92 return g, eg.Wait()
93 }
94
95 // futurePackage is a future result of analyzing a package, for use from Package only.
96 type futurePackage struct {
97 done chan struct{}
98 pkg *Package
99 err error
100 }
101
102 // Package gets the result of analyzing references for a single package.
103 func (g *PackageGraph) Package(ctx context.Context, id metadata.PackageID) (*Package, error) {
104 g.mu.Lock()
105 fut, ok := g.packages[id]
106 if ok {
107 g.mu.Unlock()
108 select {
109 case <-fut.done:
110 case <-ctx.Done():
111 return nil, ctx.Err()
112 }
113 } else {
114 fut = &futurePackage{done: make(chan struct{})}
115 g.packages[id] = fut
116 g.mu.Unlock()
117 fut.pkg, fut.err = g.buildPackage(ctx, id)
118 close(fut.done)
119 }
120 return fut.pkg, fut.err
121 }
122
123 // buildPackage parses a package and extracts its reference graph. It should
124 // only be called from Package.
125 func (g *PackageGraph) buildPackage(ctx context.Context, id metadata.PackageID) (*Package, error) {
126 p := &Package{
127 metapkg: g.meta.Metadata(id),
128 transitiveRefs: make(map[string]*typerefs.PackageSet),
129 }
130 var files []*parsego.File
131 for _, filename := range p.metapkg.CompiledGoFiles {
132 f, err := g.parse(ctx, filename)
133 if err != nil {
134 return nil, err
135 }
136 files = append(files, f)
137 }
138 imports := make(map[metadata.ImportPath]*metadata.Package)
139 for impPath, depID := range p.metapkg.DepsByImpPath {
140 if depID != "" {
141 imports[impPath] = g.meta.Metadata(depID)
142 }
143 }
144
145 // Compute the symbol-level dependencies through this package.
146 data := typerefs.Encode(files, imports)
147
148 // data can be persisted in a filecache, keyed
149 // by hash(id, CompiledGoFiles, imports).
150
151 // This point separates the local preprocessing
152 // -- of a single package (above) from the global --
153 // transitive reachability query (below).
154
155 // classes records syntactic edges between declarations in this
156 // package and declarations in this package or another
157 // package. See the package documentation for a detailed
158 // description of what these edges do (and do not) represent.
159 classes := typerefs.Decode(g.pkgIndex, data)
160
161 // Debug
162 if trace && len(classes) > 0 {
163 var buf bytes.Buffer
164 fmt.Fprintf(&buf, "%s\n", id)
165 for _, class := range classes {
166 for i, name := range class.Decls {
167 if i == 0 {
168 fmt.Fprintf(&buf, "\t")
169 }
170 fmt.Fprintf(&buf, " .%s", name)
171 }
172 // Group symbols by package.
173 var prevID PackageID
174 for _, sym := range class.Refs {
175 id := g.pkgIndex.DeclaringPackage(sym)
176 if id != prevID {
177 prevID = id
178 fmt.Fprintf(&buf, "\n\t\t-> %s:", id)
179 }
180 fmt.Fprintf(&buf, " .%s", sym.Name)
181 }
182 fmt.Fprintln(&buf)
183 }
184 os.Stderr.Write(buf.Bytes())
185 }
186
187 // Now compute the transitive closure of packages reachable
188 // from any exported symbol of this package.
189 for _, class := range classes {
190 set := g.pkgIndex.NewSet()
191
192 // The Refs slice is sorted by (PackageID, name),
193 // so we can economize by calling g.Package only
194 // when the package id changes.
195 depP := p
196 for _, sym := range class.Refs {
197 symPkgID := g.pkgIndex.DeclaringPackage(sym)
198 if symPkgID == id {
199 panic("intra-package edge")
200 }
201 if depP.metapkg.ID != symPkgID {
202 // package changed
203 var err error
204 depP, err = g.Package(ctx, symPkgID)
205 if err != nil {
206 return nil, err
207 }
208 }
209 set.Add(sym.Package)
210 set.Union(depP.transitiveRefs[sym.Name])
211 }
212 for _, name := range class.Decls {
213 p.transitiveRefs[name] = set
214 }
215 }
216
217 // Finally compute the union of transitiveRefs
218 // across the direct deps of this package.
219 byDeps, err := g.reachesByDeps(ctx, p.metapkg)
220 if err != nil {
221 return nil, err
222 }
223 p.ReachesByDeps = byDeps
224
225 return p, nil
226 }
227
228 // reachesByDeps computes the set of packages that are reachable through
229 // dependencies of the package m.
230 func (g *PackageGraph) reachesByDeps(ctx context.Context, mp *metadata.Package) (*typerefs.PackageSet, error) {
231 transitive := g.pkgIndex.NewSet()
232 for _, depID := range mp.DepsByPkgPath {
233 dep, err := g.Package(ctx, depID)
234 if err != nil {
235 return nil, err
236 }
237 transitive.AddPackage(dep.metapkg.ID)
238 for _, set := range dep.transitiveRefs {
239 transitive.Union(set)
240 }
241 }
242 return transitive, nil
243 }