Debian Codegraph @

gopls/internal/cache/source.go

raw symbols SCIP
1 // Copyright 2025 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 cache
6
7 import (
8 "context"
9 "maps"
10 "slices"
11 "strings"
12
13 "golang.org/x/tools/gopls/internal/cache/metadata"
14 "golang.org/x/tools/gopls/internal/cache/symbols"
15 "golang.org/x/tools/gopls/internal/protocol"
16 "golang.org/x/tools/gopls/internal/util/moremaps"
17 "golang.org/x/tools/internal/imports"
18 )
19
20 // goplsSource is an imports.Source that provides import information using
21 // gopls and the module cache index.
22 type goplsSource struct {
23 snapshot *Snapshot
24
25 // set by each invocation of ResolveReferences
26 ctx context.Context
27 }
28
29 func (s *Snapshot) NewGoplsSource() *goplsSource {
30 return &goplsSource{
31 snapshot: s,
32 }
33 }
34
35 func (s *goplsSource) LoadPackageNames(ctx context.Context, srcDir string, paths []imports.ImportPath) (map[imports.ImportPath]imports.PackageName, error) {
36 // The goplsSource does not need to do this
37 return nil, nil
38 }
39
40 type result struct {
41 res *imports.Result
42 deprecated bool
43 }
44
45 // ResolveReferences tries to find resolving imports in the workspace, and failing
46 // that, in the module cache. It uses heuristics to decide among alternatives.
47 // The heuristics will usually prefer a v2 version, if there is one.
48 // TODO: It does not take advantage of hints provided by the user:
49 // 1. syntactic context: pkg.Name().Foo
50 // 3. already imported files in the same module
51 func (s *goplsSource) ResolveReferences(ctx context.Context, filename string, missing imports.References) ([]*imports.Result, error) {
52 s.ctx = ctx
53 // get results from the workspace. There will at most one for each package name
54 fromWS, err := s.resolveWorkspaceReferences(filename, missing)
55 if err != nil {
56 return nil, err
57 }
58 // collect the ones that are still
59 needed := maps.Clone(missing)
60 for _, a := range fromWS {
61 delete(needed, a.Package.Name)
62 }
63 // when debug (below) is gone, change this to: if len(needed) == 0 {return fromWS, nil}
64 var fromCache []*result
65 if len(needed) != 0 {
66 var err error
67 fromCache, err = s.resolveCacheReferences(needed)
68 if err != nil {
69 return nil, err
70 }
71 // trim candidates to one per missing package.
72 byPkgNm := make(map[string][]*result)
73 for _, c := range fromCache {
74 // avoid internal and vendor
75 if !imports.CanUse(filename, c.res.Import.ImportPath) {
76 continue
77 }
78 byPkgNm[c.res.Package.Name] = append(byPkgNm[c.res.Package.Name], c)
79 }
80 for k, v := range byPkgNm {
81 fromWS = append(fromWS, s.bestCache(k, v))
82 }
83 }
84 return fromWS, nil
85
86 }
87
88 func (s *goplsSource) resolveCacheReferences(missing imports.References) ([]*result, error) {
89 ix, err := s.snapshot.view.ModcacheIndex()
90 if err != nil {
91 return nil, err
92 }
93
94 found := make(map[string]*result)
95 for pkgName, nameSet := range missing {
96 names := moremaps.KeySlice(nameSet)
97 for importPath, cands := range ix.LookupAll(pkgName, names...) {
98 res := found[importPath]
99 if res == nil {
100 res = &result{
101 res: &imports.Result{
102 Import: &imports.ImportInfo{
103 ImportPath: importPath,
104 },
105 Package: &imports.PackageInfo{
106 Name: pkgName,
107 Exports: make(map[string]bool)},
108 },
109 deprecated: false,
110 }
111 found[importPath] = res
112 }
113 for _, c := range cands {
114 res.res.Package.Exports[c.Name] = true
115 // The import path is deprecated if a symbol that would be used is deprecated
116 res.deprecated = res.deprecated || c.Deprecated
117 }
118 }
119
120 }
121 // return results in some deterministic order
122 got := moremaps.ValueSlice(found)
123 slices.SortFunc(got, func(a, b *result) int {
124 return strings.Compare(a.res.Import.ImportPath, b.res.Import.ImportPath)
125 })
126 return got, nil
127 }
128
129 type found struct {
130 sym *symbols.Package
131 res *imports.Result
132 }
133
134 func (s *goplsSource) resolveWorkspaceReferences(filename string, missing imports.References) ([]*imports.Result, error) {
135 uri := protocol.URIFromPath(filename)
136 mypkgs, err := s.snapshot.MetadataForFile(s.ctx, uri, false)
137 if err != nil {
138 return nil, err
139 }
140 if len(mypkgs) == 0 {
141 return nil, nil
142 }
143 mypkg := mypkgs[0] // narrowest package
144 // search the metadata graph for package ids corresponding to missing
145 g := s.snapshot.MetadataGraph()
146 var ids []metadata.PackageID
147 var pkgs []*metadata.Package
148 for pid, pkg := range g.Packages {
149 // no test packages, except perhaps for ourselves
150 if pkg.ForTest != "" && pkg != mypkg {
151 continue
152 }
153 if missingWants(missing, pkg.Name) {
154 ids = append(ids, pid)
155 pkgs = append(pkgs, pkg)
156 }
157 }
158 // find the symbols in those packages
159 // the syms occur in the same order as the ids and the pkgs
160 syms, err := s.snapshot.Symbols(s.ctx, ids...)
161 if err != nil {
162 return nil, err
163 }
164 // keep track of used syms and found results by package name
165 // TODO: avoid import cycles (is current package in forward closure)
166 founds := make(map[string][]found)
167 for i := range len(ids) {
168 nm := string(pkgs[i].Name)
169 if satisfies(syms[i], missing[nm]) {
170 got := &imports.Result{
171 Import: &imports.ImportInfo{
172 Name: "",
173 ImportPath: string(pkgs[i].PkgPath),
174 },
175 Package: &imports.PackageInfo{
176 Name: string(pkgs[i].Name),
177 Exports: missing[imports.PackageName(pkgs[i].Name)],
178 },
179 }
180 founds[nm] = append(founds[nm], found{syms[i], got})
181 }
182 }
183 var ans []*imports.Result
184 for _, v := range founds {
185 // make sure the elements of v are unique
186 // (Import.ImportPath or Package.Name must differ)
187 cmp := func(l, r found) int {
188 switch strings.Compare(l.res.Import.ImportPath, r.res.Import.ImportPath) {
189 case -1:
190 return -1
191 case 1:
192 return 1
193 }
194 return strings.Compare(l.res.Package.Name, r.res.Package.Name)
195 }
196 slices.SortFunc(v, cmp)
197 newv := make([]found, 0, len(v))
198 newv = append(newv, v[0])
199 for i := 1; i < len(v); i++ {
200 if cmp(v[i], v[i-1]) != 0 {
201 newv = append(newv, v[i])
202 }
203 }
204 ans = append(ans, bestImport(filename, newv))
205 }
206 return ans, nil
207 }
208
209 // for each package name, choose one using heuristics
210 func bestImport(filename string, got []found) *imports.Result {
211 if len(got) == 1 {
212 return got[0].res
213 }
214 isTestFile := strings.HasSuffix(filename, "_test.go")
215 var leftovers []found
216 for _, g := range got {
217 // don't use _test packages unless isTestFile
218 testPkg := strings.HasSuffix(string(g.res.Package.Name), "_test") || strings.HasSuffix(string(g.res.Import.Name), "_test")
219 if testPkg && !isTestFile {
220 continue // no test covers this
221 }
222 if imports.CanUse(filename, g.sym.Files[0].DirPath()) {
223 leftovers = append(leftovers, g)
224 }
225 }
226 switch len(leftovers) {
227 case 0:
228 break // use got, they are all bad
229 case 1:
230 return leftovers[0].res // only one left
231 default:
232 got = leftovers // filtered some out
233 }
234
235 // TODO: if there are versions (like /v2) prefer them
236
237 // use distance to common ancestor with filename
238 // (TestDirectoryFilters_MultiRootImportScanning)
239 // filename is .../a/main.go, choices are
240 // .../a/hi/hi.go and .../b/hi/hi.go
241 longest := -1
242 ix := -1
243 for i := 0; i < len(got); i++ {
244 d := commonpref(filename, got[i].sym.Files[0].Path())
245 if d > longest {
246 longest = d
247 ix = i
248 }
249 }
250 // it is possible that there were several tied, but we return the first
251 return got[ix].res
252 }
253
254 // choose the best result for the package named nm from the module cache
255 func (s *goplsSource) bestCache(nm string, got []*result) *imports.Result {
256 if len(got) == 1 {
257 return got[0].res
258 }
259 // does the go.mod file choose one?
260 if ans := s.fromGoMod(got); ans != nil {
261 return ans
262 }
263 got = preferUndeprecated(got)
264 // want the best Import.ImportPath
265 // these are all for the package named nm,
266 // nm (probably) occurs in all the paths;
267 // choose the longest (after nm), so as to get /v2
268 maxlen, which := -1, -1
269 for i := 0; i < len(got); i++ {
270 ix := strings.Index(got[i].res.Import.ImportPath, nm)
271 if ix == -1 {
272 continue // now what?
273 }
274 cnt := len(got[i].res.Import.ImportPath) - ix
275 if cnt > maxlen {
276 maxlen = cnt
277 which = i
278 }
279 // what about ties? (e.g., /v2 and /v3)
280 }
281 if which >= 0 {
282 return got[which].res
283 }
284 return got[0].res // arbitrary guess
285 }
286
287 // if go.mod requires one of the packages, return that
288 func (s *goplsSource) fromGoMod(got []*result) *imports.Result {
289 // should we use s.S.view.worsspaceModFiles, and the union of their requires?
290 // (note that there are no tests where it contains more than one)
291 modURI := s.snapshot.view.gomod
292 modfh, ok := s.snapshot.files.get(modURI)
293 if !ok {
294 return nil
295 }
296 parsed, err := s.snapshot.ParseMod(s.ctx, modfh)
297 if err != nil {
298 return nil
299 }
300 reqs := parsed.File.Require
301 for _, g := range got {
302 for _, req := range reqs {
303 if strings.HasPrefix(g.res.Import.ImportPath, req.Syntax.Token[1]) {
304 return g.res
305 }
306 }
307 }
308 return nil
309 }
310
311 func commonpref(filename string, path string) int {
312 k := 0
313 for ; k < len(filename) && k < len(path) && filename[k] == path[k]; k++ {
314 }
315 return k
316 }
317
318 func satisfies(pkg *symbols.Package, missing map[string]bool) bool {
319 syms := make(map[string]bool)
320 for _, x := range pkg.Symbols {
321 for _, s := range x {
322 syms[s.Name] = true
323 }
324 }
325 for k := range missing {
326 if !syms[k] {
327 return false
328 }
329 }
330 return true
331 }
332
333 // does pkgPath potentially satisfy a missing reference?
334 func missingWants(missing imports.References, pkgPath metadata.PackageName) bool {
335 for k := range missing {
336 if string(k) == string(pkgPath) {
337 return true
338 }
339 }
340 return false
341 }
342
343 // If there are both deprecated and undprecated ones
344 // then return only the undeprecated one
345 func preferUndeprecated(got []*result) []*result {
346 var ok []*result
347 for _, g := range got {
348 if !g.deprecated {
349 ok = append(ok, g)
350 }
351 }
352 if len(ok) > 0 {
353 return ok
354 }
355 return got
356 }