Debian Codegraph @

gopls/internal/cache/metadata/metadata.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 // The metadata package defines types and functions for working with package
6 // metadata, which describes Go packages and their relationships.
7 //
8 // Package metadata is loaded by gopls using go/packages, and the [Package]
9 // type is itself a projection and translation of data from
10 // go/packages.Package.
11 //
12 // Packages are assembled into an immutable [Graph]
13 package metadata
14
15 import (
16 "go/ast"
17 "go/types"
18 "sort"
19 "strconv"
20 "strings"
21
22 "golang.org/x/tools/go/packages"
23 "golang.org/x/tools/gopls/internal/protocol"
24 "golang.org/x/tools/internal/packagesinternal"
25 )
26
27 // Declare explicit types for package paths, names, and IDs to ensure that we
28 // never use an ID where a path belongs, and vice versa. If we confused these,
29 // it would result in confusing errors because package IDs often look like
30 // package paths.
31 type (
32 PackageID string // go list's unique identifier for a package (e.g. "vendor/example.com/foo [vendor/example.com/bar.test]")
33 PackagePath string // name used to prefix linker symbols (e.g. "vendor/example.com/foo")
34 PackageName string // identifier in 'package' declaration (e.g. "foo")
35 ImportPath string // path that appears in an import declaration (e.g. "example.com/foo")
36 )
37
38 // Package represents package metadata retrieved from go/packages.
39 // The DepsBy{Imp,Pkg}Path maps do not contain self-import edges.
40 //
41 // An ad-hoc package (without go.mod or GOPATH) has its ID, PkgPath,
42 // and LoadDir equal to the absolute path of its directory.
43 type Package struct {
44 ID PackageID
45 PkgPath PackagePath
46 Name PackageName
47
48 // These fields are as defined by go/packages.Package
49 GoFiles []protocol.DocumentURI
50 CompiledGoFiles []protocol.DocumentURI
51 IgnoredFiles []protocol.DocumentURI
52 OtherFiles []protocol.DocumentURI
53
54 ForTest PackagePath // q in a "p [q.test]" package, else ""
55 TypesSizes types.Sizes
56 Errors []packages.Error // must be set for packages in import cycles
57 DepsByImpPath map[ImportPath]PackageID // may contain dups; empty ID => missing
58 DepsByPkgPath map[PackagePath]PackageID // values are unique and non-empty
59 Module *packages.Module // may be missing for std and cmd; see Go issue #65816.
60 DepsErrors []*packagesinternal.PackageError
61 LoadDir string // directory from which go/packages was run
62 Standalone bool // package synthesized for a standalone file (e.g. ignore-tagged)
63 }
64
65 func (mp *Package) String() string { return string(mp.ID) }
66
67 // IsIntermediateTestVariant reports whether the given package is an
68 // intermediate test variant (ITV), e.g. "net/http [net/url.test]".
69 //
70 // An ITV has identical syntax to the regular variant, but different
71 // import metadata (DepsBy{Imp,Pkg}Path).
72 //
73 // Such test variants arise when an x_test package (in this case net/url_test)
74 // imports a package (in this case net/http) that itself imports the
75 // non-x_test package (in this case net/url).
76 //
77 // This is done so that the forward transitive closure of net/url_test has
78 // only one package for the "net/url" import.
79 // The ITV exists to hold the test variant import:
80 //
81 // net/url_test [net/url.test]
82 //
83 // | "net/http" -> net/http [net/url.test]
84 // | "net/url" -> net/url [net/url.test]
85 // | ...
86 //
87 // net/http [net/url.test]
88 //
89 // | "net/url" -> net/url [net/url.test]
90 // | ...
91 //
92 // This restriction propagates throughout the import graph of net/http: for
93 // every package imported by net/http that imports net/url, there must be an
94 // intermediate test variant that instead imports "net/url [net/url.test]".
95 //
96 // As one can see from the example of net/url and net/http, intermediate test
97 // variants can result in many additional packages that are essentially (but
98 // not quite) identical. For this reason, we filter these variants wherever
99 // possible.
100 //
101 // # Why we mostly ignore intermediate test variants
102 //
103 // In projects with complicated tests, there may be a very large
104 // number of ITVs--asymptotically more than the number of ordinary
105 // variants. Since they have identical syntax, it is fine in most
106 // cases to ignore them since the results of analyzing the ordinary
107 // variant suffice. However, this is not entirely sound.
108 //
109 // Consider this package:
110 //
111 // // p/p.go -- in all variants of p
112 // package p
113 // type T struct { io.Closer }
114 //
115 // // p/p_test.go -- in test variant of p
116 // package p
117 // func (T) Close() error { ... }
118 //
119 // The ordinary variant "p" defines T with a Close method promoted
120 // from io.Closer. But its test variant "p [p.test]" defines a type T
121 // with a Close method from p_test.go.
122 //
123 // Now consider a package q that imports p, perhaps indirectly. Within
124 // it, T.Close will resolve to the first Close method:
125 //
126 // // q/q.go -- in all variants of q
127 // package q
128 // import "p"
129 // var _ = new(p.T).Close
130 //
131 // Let's assume p also contains this file defining an external test (xtest):
132 //
133 // // p/p_x_test.go -- external test of p
134 // package p_test
135 // import ( "q"; "testing" )
136 // func Test(t *testing.T) { ... }
137 //
138 // Note that q imports p, but p's xtest imports q. Now, in "q
139 // [p.test]", the intermediate test variant of q built for p's
140 // external test, T.Close resolves not to the io.Closer.Close
141 // interface method, but to the concrete method of T.Close
142 // declared in p_test.go.
143 //
144 // If we now request all references to the T.Close declaration in
145 // p_test.go, the result should include the reference from q's ITV.
146 // (It's not just methods that can be affected; fields can too, though
147 // it requires bizarre code to achieve.)
148 //
149 // As a matter of policy, gopls mostly ignores this subtlety,
150 // because to account for it would require that we type-check every
151 // intermediate test variant of p, of which there could be many.
152 // Good code doesn't rely on such trickery.
153 //
154 // Most callers of MetadataForFile set removeIntermediateTestVariants parameter
155 // to discard them before requesting type checking, or the products of
156 // type-checking such as the cross-reference index or method set index.
157 //
158 // MetadataForFile doesn't do this filtering itself because in some
159 // cases we need to make a reverse dependency query on the metadata
160 // graph, and it's important to include the rdeps of ITVs in that
161 // query. But the filtering of ITVs should be applied after that step,
162 // before type checking.
163 //
164 // In general, we should never type check an ITV.
165 func (mp *Package) IsIntermediateTestVariant() bool {
166 return mp.ForTest != "" && mp.ForTest != mp.PkgPath && mp.ForTest+"_test" != mp.PkgPath
167 }
168
169 // A Source maps package IDs to metadata for the packages.
170 type Source interface {
171 // Metadata returns the [Package] for the given package ID, or nil if it does
172 // not exist.
173 // TODO(rfindley): consider returning (*Metadata, bool)
174 // TODO(rfindley): consider renaming this method.
175 Metadata(PackageID) *Package
176 }
177
178 // TODO(rfindley): move the utility functions below to a util.go file.
179
180 // IsCommandLineArguments reports whether a given value denotes
181 // "command-line-arguments" package, which is a package with an unknown ID
182 // created by the go command. It can have a test variant, which is why callers
183 // should not check that a value equals "command-line-arguments" directly.
184 func IsCommandLineArguments(id PackageID) bool {
185 return strings.Contains(string(id), "command-line-arguments")
186 }
187
188 // SortPostOrder sorts the IDs so that if x depends on y, then y appears before x.
189 func SortPostOrder(meta Source, ids []PackageID) {
190 postorder := make(map[PackageID]int)
191 order := 0
192 var visit func(PackageID)
193 visit = func(id PackageID) {
194 if _, ok := postorder[id]; !ok {
195 postorder[id] = -1 // break recursion
196 if mp := meta.Metadata(id); mp != nil {
197 for _, depID := range mp.DepsByPkgPath {
198 visit(depID)
199 }
200 }
201 order++
202 postorder[id] = order
203 }
204 }
205 for _, id := range ids {
206 visit(id)
207 }
208 sort.Slice(ids, func(i, j int) bool {
209 return postorder[ids[i]] < postorder[ids[j]]
210 })
211 }
212
213 // UnquoteImportPath returns the unquoted import path of s,
214 // or "" if the path is not properly quoted.
215 func UnquoteImportPath(spec *ast.ImportSpec) ImportPath {
216 path, err := strconv.Unquote(spec.Path.Value)
217 if err != nil {
218 return ""
219 }
220 return ImportPath(path)
221 }
222
223 // RemoveIntermediateTestVariants removes intermediate test variants, modifying
224 // the array. We use a pointer to a slice make it impossible to forget to use
225 // the result.
226 func RemoveIntermediateTestVariants(pmetas *[]*Package) {
227 metas := *pmetas
228 res := metas[:0]
229 for _, mp := range metas {
230 if !mp.IsIntermediateTestVariant() {
231 res = append(res, mp)
232 }
233 }
234 *pmetas = res
235 }
236
237 // IsValidImport returns whether from may import to.
238 func IsValidImport(from, to PackagePath, goList bool) bool {
239 // If the metadata came from a build system other than go list
240 // (e.g. bazel) it is beyond our means to compute visibility.
241 if !goList {
242 return true
243 }
244 i := strings.LastIndex(string(to), "/internal/")
245 if i == -1 {
246 return true
247 }
248 // TODO(rfindley): this looks wrong: IsCommandLineArguments is meant to
249 // operate on package IDs, not package paths.
250 if IsCommandLineArguments(PackageID(from)) {
251 return true
252 }
253 // TODO(rfindley): this is wrong. mod.testx/p should not be able to
254 // import mod.test/internal: https://go.dev/play/p/-Ca6P-E4V4q
255 return strings.HasPrefix(string(from), string(to[:i]))
256 }