Debian Codegraph @

gopls/internal/cache/metadata/graph.go

raw symbols SCIP
1 // Copyright 2022 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 metadata
6
7 import (
8 "cmp"
9 "iter"
10 "maps"
11 "slices"
12 "sort"
13 "strings"
14
15 "golang.org/x/tools/go/packages"
16 "golang.org/x/tools/gopls/internal/protocol"
17 "golang.org/x/tools/gopls/internal/util/bug"
18 )
19
20 // A Graph is an immutable and transitively closed graph of [Package] data.
21 type Graph struct {
22 // Packages maps package IDs to their associated Packages.
23 Packages map[PackageID]*Package
24
25 // Each of the three maps below is an index of the pointer values held
26 // by the Packages map. However, Package pointers are not generally canonical.
27
28 // ImportedBy maps package IDs to the list of packages that import them.
29 ImportedBy map[PackageID][]*Package
30
31 // ForPackagePath maps package by their package path to their package ID.
32 // Non-test packages appear before test packages, and within each of those
33 // categories, packages with fewer CompiledGoFiles appear first.
34 ForPackagePath map[PackagePath][]*Package
35
36 // ForFile maps file URIs to packages, sorted by (!valid, cli, packageID).
37 // A single file may belong to multiple packages due to tests packages.
38 ForFile map[protocol.DocumentURI][]*Package
39 }
40
41 // Metadata implements the [Source] interface
42 func (g *Graph) Metadata(id PackageID) *Package {
43 return g.Packages[id]
44 }
45
46 // Update creates a new Graph containing the result of applying the given
47 // updates to the receiver, though the receiver is not itself mutated. As a
48 // special case, if updates is empty, Update just returns the receiver.
49 //
50 // A nil map value is used to indicate a deletion.
51 func (g *Graph) Update(updates map[PackageID]*Package) *Graph {
52 if len(updates) == 0 {
53 // Optimization: since the graph is immutable, we can return the receiver.
54 return g
55 }
56
57 // Debugging golang/go#64227, golang/vscode-go#3126:
58 // Assert that the existing metadata graph is acyclic.
59 if cycle := cyclic(g.Packages); cycle != "" {
60 bug.Reportf("metadata is cyclic even before updates: %s", cycle)
61 }
62 // Assert that the updates contain no self-cycles.
63 for id, mp := range updates {
64 if mp != nil {
65 for _, depID := range mp.DepsByPkgPath {
66 if depID == id {
67 bug.Reportf("self-cycle in metadata update: %s", id)
68 }
69 }
70 }
71 }
72
73 // Copy pkgs map then apply updates.
74 pkgs := make(map[PackageID]*Package, len(g.Packages))
75 maps.Copy(pkgs, g.Packages)
76 for id, mp := range updates {
77 if mp == nil {
78 delete(pkgs, id)
79 } else {
80 pkgs[id] = mp
81 }
82 }
83
84 // Break import cycles involving updated nodes.
85 breakImportCycles(pkgs, updates)
86
87 return newGraph(pkgs)
88 }
89
90 // newGraph returns a new metadataGraph,
91 // deriving relations from the specified metadata.
92 func newGraph(pkgs map[PackageID]*Package) *Graph {
93 // Build the import graph.
94 importedBy := make(map[PackageID][]*Package)
95 byPackagePath := make(map[PackagePath][]*Package)
96 for _, mp := range pkgs {
97 for _, depID := range mp.DepsByPkgPath {
98 importedBy[depID] = append(importedBy[depID], mp)
99 }
100 byPackagePath[mp.PkgPath] = append(byPackagePath[mp.PkgPath], mp)
101 }
102
103 // Collect file associations.
104 uriPkgs := make(map[protocol.DocumentURI][]*Package)
105 for _, mp := range pkgs {
106 uris := map[protocol.DocumentURI]struct{}{}
107 for _, uri := range mp.CompiledGoFiles {
108 uris[uri] = struct{}{}
109 }
110 for _, uri := range mp.GoFiles {
111 uris[uri] = struct{}{}
112 }
113 for _, uri := range mp.OtherFiles {
114 if strings.HasSuffix(string(uri), ".s") { // assembly
115 uris[uri] = struct{}{}
116 }
117 }
118 for uri := range uris {
119 uriPkgs[uri] = append(uriPkgs[uri], mp)
120 }
121 }
122
123 // Sort and filter file associations.
124 for uri, pkgs := range uriPkgs {
125 sort.Slice(pkgs, func(i, j int) bool {
126 cli := IsCommandLineArguments(pkgs[i].ID)
127 clj := IsCommandLineArguments(pkgs[j].ID)
128 if cli != clj {
129 return clj
130 }
131
132 // 2. packages appear in name order.
133 return pkgs[i].ID < pkgs[j].ID
134 })
135
136 // Choose the best packages for each URI, according to the following rules:
137 // - If there are any valid real packages, choose them.
138 // - Else, choose the first valid command-line-argument package, if it exists.
139 //
140 // TODO(rfindley): it might be better to track all packages here, and exclude
141 // them later when type checking, but this is the existing behavior.
142 for i, pkg := range pkgs {
143 // If we've seen *anything* prior to command-line arguments package, take
144 // it. Note that pkgs[0] may itself be command-line-arguments.
145 if i > 0 && IsCommandLineArguments(pkg.ID) {
146 uriPkgs[uri] = pkgs[:i]
147 break
148 }
149 }
150 }
151
152 for _, mps := range byPackagePath {
153 slices.SortFunc(mps, func(a, b *Package) int {
154 if (a.ForTest == "") != (b.ForTest == "") {
155 if a.ForTest == "" {
156 return -1
157 }
158 return 1
159 }
160 if c := cmp.Compare(len(a.CompiledGoFiles), len(b.CompiledGoFiles)); c != 0 {
161 return c
162 }
163 return cmp.Compare(a.ID, b.ID)
164 })
165 }
166
167 return &Graph{
168 Packages: pkgs,
169 ImportedBy: importedBy,
170 ForPackagePath: byPackagePath,
171 ForFile: uriPkgs,
172 }
173 }
174
175 // ReverseReflexiveTransitiveClosure returns a new mapping containing the
176 // metadata for the specified packages along with any package that
177 // transitively imports one of them, keyed by ID, including all the initial packages.
178 func (g *Graph) ReverseReflexiveTransitiveClosure(ids ...PackageID) map[PackageID]*Package {
179 seen := make(map[PackageID]*Package)
180 var visitAll func([]*Package)
181 visitAll = func(pkgs []*Package) {
182 for _, pkg := range pkgs {
183 if seen[pkg.ID] == nil {
184 seen[pkg.ID] = pkg
185 visitAll(g.ImportedBy[pkg.ID])
186 }
187 }
188 }
189 var initial []*Package
190 for _, id := range ids {
191 if pkg := g.Packages[id]; pkg != nil {
192 initial = append(initial, pkg)
193 }
194 }
195 visitAll(initial)
196 return seen
197 }
198
199 // ForwardReflexiveTransitiveClosure returns an iterator over the
200 // specified nodes and all their forward dependencies, in an arbitrary
201 // topological (dependencies-first) order. The order may vary.
202 func (g *Graph) ForwardReflexiveTransitiveClosure(ids ...PackageID) iter.Seq[*Package] {
203 return func(yield func(*Package) bool) {
204 seen := make(map[PackageID]bool)
205 var visit func(PackageID) bool
206 visit = func(id PackageID) bool {
207 if !seen[id] {
208 seen[id] = true
209 if mp := g.Packages[id]; mp != nil {
210 for _, depID := range mp.DepsByPkgPath {
211 if !visit(depID) {
212 return false
213 }
214 }
215 if !yield(mp) {
216 return false
217 }
218 }
219 }
220 return true
221 }
222 for _, id := range ids {
223 visit(id)
224 }
225 }
226 }
227
228 // breakImportCycles breaks import cycles in the metadata by deleting
229 // Deps* edges. It modifies only metadata present in the 'updates'
230 // subset. This function has an internal test.
231 func breakImportCycles(metadata, updates map[PackageID]*Package) {
232 // 'go list' should never report a cycle without flagging it
233 // as such, but we're extra cautious since we're combining
234 // information from multiple runs of 'go list'. Also, Bazel
235 // may silently report cycles.
236 cycles := detectImportCycles(metadata, updates)
237 if len(cycles) > 0 {
238 // There were cycles (uncommon). Break them.
239 //
240 // The naive way to break cycles would be to perform a
241 // depth-first traversal and to detect and delete
242 // cycle-forming edges as we encounter them.
243 // However, we're not allowed to modify the existing
244 // Metadata records, so we can only break edges out of
245 // the 'updates' subset.
246 //
247 // Another possibility would be to delete not the
248 // cycle forming edge but the topmost edge on the
249 // stack whose tail is an updated node.
250 // However, this would require that we retroactively
251 // undo all the effects of the traversals that
252 // occurred since that edge was pushed on the stack.
253 //
254 // We use a simpler scheme: we compute the set of cycles.
255 // All cyclic paths necessarily involve at least one
256 // updated node, so it is sufficient to break all
257 // edges from each updated node to other members of
258 // the strong component.
259 //
260 // This may result in the deletion of dominating
261 // edges, causing some dependencies to appear
262 // spuriously unreachable. Consider A <-> B -> C
263 // where updates={A,B}. The cycle is {A,B} so the
264 // algorithm will break both A->B and B->A, causing
265 // A to no longer depend on B or C.
266 //
267 // But that's ok: any error in Metadata.Errors is
268 // conservatively assumed by snapshot.clone to be a
269 // potential import cycle error, and causes special
270 // invalidation so that if B later drops its
271 // cycle-forming import of A, both A and B will be
272 // invalidated.
273 for _, cycle := range cycles {
274 cyclic := make(map[PackageID]bool)
275 for _, mp := range cycle {
276 cyclic[mp.ID] = true
277 }
278 for id := range cyclic {
279 if mp := updates[id]; mp != nil {
280 for path, depID := range mp.DepsByImpPath {
281 if cyclic[depID] {
282 delete(mp.DepsByImpPath, path)
283 }
284 }
285 for path, depID := range mp.DepsByPkgPath {
286 if cyclic[depID] {
287 delete(mp.DepsByPkgPath, path)
288 }
289 }
290
291 // Set m.Errors to enable special
292 // invalidation logic in snapshot.clone.
293 if len(mp.Errors) == 0 {
294 mp.Errors = []packages.Error{{
295 Msg: "detected import cycle",
296 Kind: packages.ListError,
297 }}
298 }
299 }
300 }
301 }
302
303 // double-check when debugging
304 if false {
305 if cycles := detectImportCycles(metadata, updates); len(cycles) > 0 {
306 bug.Reportf("unbroken cycle: %v", cycles)
307 }
308 }
309 }
310 }
311
312 // cyclic returns a description of a cycle,
313 // if the graph is cyclic, otherwise "".
314 func cyclic(graph map[PackageID]*Package) string {
315 const (
316 unvisited = 0
317 visited = 1
318 onstack = 2
319 )
320 color := make(map[PackageID]int)
321 var visit func(id PackageID) string
322 visit = func(id PackageID) string {
323 switch color[id] {
324 case unvisited:
325 color[id] = onstack
326 case onstack:
327 return string(id) // cycle!
328 case visited:
329 return ""
330 }
331 if mp := graph[id]; mp != nil {
332 for _, depID := range mp.DepsByPkgPath {
333 if cycle := visit(depID); cycle != "" {
334 return string(id) + "->" + cycle
335 }
336 }
337 }
338 color[id] = visited
339 return ""
340 }
341 for id := range graph {
342 if cycle := visit(id); cycle != "" {
343 return cycle
344 }
345 }
346 return ""
347 }
348
349 // detectImportCycles reports cycles in the metadata graph. It returns a new
350 // unordered array of all cycles (nontrivial strong components) in the
351 // metadata graph reachable from a non-nil 'updates' value.
352 func detectImportCycles(metadata, updates map[PackageID]*Package) [][]*Package {
353 // We use the depth-first algorithm of Tarjan.
354 // https://doi.org/10.1137/0201010
355 //
356 // TODO(adonovan): when we can use generics, consider factoring
357 // in common with the other implementation of Tarjan (in typerefs),
358 // abstracting over the node and edge representation.
359
360 // A node wraps a Metadata with its working state.
361 // (Unfortunately we can't intrude on shared Metadata.)
362 type node struct {
363 rep *node
364 mp *Package
365 index, lowlink int32
366 scc int8 // TODO(adonovan): opt: cram these 1.5 bits into previous word
367 }
368 nodes := make(map[PackageID]*node, len(metadata))
369 nodeOf := func(id PackageID) *node {
370 n, ok := nodes[id]
371 if !ok {
372 mp := metadata[id]
373 if mp == nil {
374 // Dangling import edge.
375 // Not sure whether a go/packages driver ever
376 // emits this, but create a dummy node in case.
377 // Obviously it won't be part of any cycle.
378 mp = &Package{ID: id}
379 }
380 n = &node{mp: mp}
381 n.rep = n
382 nodes[id] = n
383 }
384 return n
385 }
386
387 // find returns the canonical node decl.
388 // (The nodes form a disjoint set forest.)
389 var find func(*node) *node
390 find = func(n *node) *node {
391 rep := n.rep
392 if rep != n {
393 rep = find(rep)
394 n.rep = rep // simple path compression (no union-by-rank)
395 }
396 return rep
397 }
398
399 // global state
400 var (
401 index int32 = 1
402 stack []*node
403 sccs [][]*Package // set of nontrivial strongly connected components
404 )
405
406 // visit implements the depth-first search of Tarjan's SCC algorithm
407 // Precondition: x is canonical.
408 var visit func(*node)
409 visit = func(x *node) {
410 x.index = index
411 x.lowlink = index
412 index++
413
414 stack = append(stack, x) // push
415 x.scc = -1
416
417 for _, yid := range x.mp.DepsByPkgPath {
418 y := nodeOf(yid)
419 // Loop invariant: x is canonical.
420 y = find(y)
421 if x == y {
422 continue // nodes already combined (self-edges are impossible)
423 }
424
425 switch {
426 case y.scc > 0:
427 // y is already a collapsed SCC
428
429 case y.scc < 0:
430 // y is on the stack, and thus in the current SCC.
431 if y.index < x.lowlink {
432 x.lowlink = y.index
433 }
434
435 default:
436 // y is unvisited; visit it now.
437 visit(y)
438 // Note: x and y are now non-canonical.
439 x = find(x)
440 if y.lowlink < x.lowlink {
441 x.lowlink = y.lowlink
442 }
443 }
444 }
445
446 // Is x the root of an SCC?
447 if x.lowlink == x.index {
448 // Gather all metadata in the SCC (if nontrivial).
449 var scc []*Package
450 for {
451 // Pop y from stack.
452 i := len(stack) - 1
453 y := stack[i]
454 stack = stack[:i]
455 if x != y || scc != nil {
456 scc = append(scc, y.mp)
457 }
458 if x == y {
459 break // complete
460 }
461 // x becomes y's canonical representative.
462 y.rep = x
463 }
464 if scc != nil {
465 sccs = append(sccs, scc)
466 }
467 x.scc = 1
468 }
469 }
470
471 // Visit only the updated nodes:
472 // the existing metadata graph has no cycles,
473 // so any new cycle must involve an updated node.
474 for id, mp := range updates {
475 if mp != nil {
476 if n := nodeOf(id); n.index == 0 { // unvisited
477 visit(n)
478 }
479 }
480 }
481
482 return sccs
483 }