Debian Codegraph @

gopls/internal/golang/completion/unimported.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 completion
6
7 // unimported completion is invoked when the user types something like 'foo.xx',
8 // foo is known to be a package name not yet imported in the current file, and
9 // xx (or whatever the user has typed) is interpreted as a hint (pattern) for the
10 // member of foo that the user is looking for.
11 //
12 // This code looks for a suitable completion in a number of places. A 'suitable
13 // completion' is an exported symbol (so a type, const, var, or func) from package
14 // foo, which, after converting everything to lower case, has the pattern as a
15 // subsequence.
16 //
17 // The code looks for a suitable completion in
18 // 1. the imports of some other file of the current package,
19 // 2. the standard library,
20 // 3. the imports of some other file in the current workspace,
21 // 4. imports in the current module with 'foo' as the explicit package name,
22 // 5. the module cache,
23 // It stops at the first success.
24
25 import (
26 "context"
27 "fmt"
28 "go/ast"
29 "go/printer"
30 "go/token"
31 "path"
32 "slices"
33 "strings"
34
35 "golang.org/x/tools/gopls/internal/cache/metadata"
36 "golang.org/x/tools/gopls/internal/golang/completion/snippet"
37 "golang.org/x/tools/gopls/internal/protocol"
38 "golang.org/x/tools/gopls/internal/util/bug"
39 "golang.org/x/tools/internal/imports"
40 "golang.org/x/tools/internal/modindex"
41 "golang.org/x/tools/internal/stdlib"
42 "golang.org/x/tools/internal/versions"
43 )
44
45 func (c *completer) unimported(ctx context.Context, pkgname metadata.PackageName, prefix string) {
46 wsIDs, ourIDs := c.findPackageIDs(pkgname)
47 stdpkgs := c.stdlibPkgs(pkgname)
48 if len(ourIDs) > 0 {
49 // use the one in the current package, if possible
50 items := c.pkgIDmatches(ctx, ourIDs, pkgname, prefix)
51 if c.scoreList(items) {
52 return
53 }
54 }
55 // do the stdlib next.
56 items := c.stdlibMatches(stdpkgs, pkgname, prefix)
57 if c.scoreList(items) {
58 return
59 }
60
61 // look in the rest of the workspace
62 items = c.pkgIDmatches(ctx, wsIDs, pkgname, prefix)
63 if c.scoreList(items) {
64 return
65 }
66
67 // before looking in the module cache, maybe it is an explicit
68 // package name used in this module
69 if c.explicitPkgName(ctx, pkgname, prefix) {
70 return
71 }
72
73 // look in the module cache
74 items, err := c.modcacheMatches(pkgname, prefix)
75 items = c.filterGoMod(ctx, items)
76 if err == nil && c.scoreList(items) {
77 return
78 }
79
80 // out of things to do
81 }
82
83 // prefer completion items that are referenced in the go.mod file
84 func (c *completer) filterGoMod(ctx context.Context, items []CompletionItem) []CompletionItem {
85 if c.pkg.Metadata().Module == nil {
86 // for std or GOROOT mode
87 return items
88 }
89 gomod := c.pkg.Metadata().Module.GoMod
90 uri := protocol.URIFromPath(gomod)
91 fh, err := c.snapshot.ReadFile(ctx, uri)
92 if err != nil {
93 return items
94 }
95 pm, err := c.snapshot.ParseMod(ctx, fh)
96 if err != nil || pm == nil {
97 return items
98 }
99 // if any of the items match any of the req, just return those
100 reqnames := []string{}
101 for _, req := range pm.File.Require {
102 reqnames = append(reqnames, req.Mod.Path)
103 }
104 better := []CompletionItem{}
105 for _, compl := range items {
106 if len(compl.AdditionalTextEdits) == 0 {
107 continue
108 }
109 // import "foof/pkg"
110 flds := strings.FieldsFunc(compl.AdditionalTextEdits[0].NewText, func(r rune) bool {
111 return r == '"' || r == '/'
112 })
113 if len(flds) < 3 {
114 continue
115 }
116 if slices.Contains(reqnames, flds[1]) {
117 better = append(better, compl)
118 }
119 }
120 if len(better) > 0 {
121 return better
122 }
123 return items
124 }
125
126 // see if some file in the current package satisfied a foo. import
127 // because foo is an explicit package name (import foo "a.b.c")
128 func (c *completer) explicitPkgName(ctx context.Context, pkgname metadata.PackageName, prefix string) bool {
129 for _, pgf := range c.pkg.CompiledGoFiles() {
130 imports := pgf.File.Imports
131 for _, imp := range imports {
132 if imp.Name != nil && imp.Name.Name == string(pkgname) {
133 path := strings.Trim(imp.Path.Value, `"`)
134 if c.tryPath(ctx, metadata.PackagePath(path), string(pkgname), prefix) {
135 return true // one is enough
136 }
137 }
138 }
139 }
140 return false
141 }
142
143 // see if this path contains a usable import with explicit package name
144 func (c *completer) tryPath(ctx context.Context, path metadata.PackagePath, pkgname, prefix string) bool {
145 packages := c.snapshot.MetadataGraph().ForPackagePath
146 ids := []metadata.PackageID{}
147 for _, pkg := range packages[path] { // could there ever be more than one?
148 ids = append(ids, pkg.ID) // pkg.ID. ID: "math/rand" but Name: "rand"
149 }
150 items := c.pkgIDmatches(ctx, ids, metadata.PackageName(pkgname), prefix)
151 return c.scoreList(items)
152 }
153
154 // find all the packageIDs for packages in the workspace that have the desired name
155 // thisPkgIDs contains the ones known to the current package, wsIDs contains the others
156 func (c *completer) findPackageIDs(pkgname metadata.PackageName) (wsIDs, thisPkgIDs []metadata.PackageID) {
157 g := c.snapshot.MetadataGraph()
158 for pid, pkg := range c.snapshot.MetadataGraph().Packages {
159 if pkg.Name != pkgname {
160 continue
161 }
162 imports := g.ImportedBy[pid]
163 // Metadata is not canonical: it may be held onto by a package. Therefore,
164 // we must compare by ID.
165 thisPkg := func(mp *metadata.Package) bool { return mp.ID == c.pkg.Metadata().ID }
166 if slices.ContainsFunc(imports, thisPkg) {
167 thisPkgIDs = append(thisPkgIDs, pid)
168 } else {
169 wsIDs = append(wsIDs, pid)
170 }
171 }
172 return
173 }
174
175 // find all the stdlib packages that have the desired name
176 func (c *completer) stdlibPkgs(pkgname metadata.PackageName) []metadata.PackagePath {
177 var pkgs []metadata.PackagePath // stlib packages that match pkg
178 for pkgpath := range stdlib.PackageSymbols {
179 v := metadata.PackageName(path.Base(pkgpath))
180 if v == pkgname {
181 pkgs = append(pkgs, metadata.PackagePath(pkgpath))
182 } else if imports.WithoutVersion(string(pkgpath)) == string(pkgname) {
183 pkgs = append(pkgs, metadata.PackagePath(pkgpath))
184 }
185 }
186 return pkgs
187 }
188
189 // return CompletionItems for all matching symbols in the packages in ids.
190 func (c *completer) pkgIDmatches(ctx context.Context, ids []metadata.PackageID, pkgname metadata.PackageName, prefix string) []CompletionItem {
191 pattern := strings.ToLower(prefix)
192 allpkgsyms, err := c.snapshot.Symbols(ctx, ids...)
193 if err != nil {
194 return nil // would if be worth retrying the ids one by one?
195 }
196 if len(allpkgsyms) != len(ids) {
197 bug.Reportf("Symbols returned %d values for %d pkgIDs", len(allpkgsyms), len(ids))
198 return nil
199 }
200 var got []CompletionItem
201 for i, pkgID := range ids {
202 pkg := c.snapshot.MetadataGraph().Packages[pkgID]
203 if pkg == nil {
204 bug.Reportf("no metadata for %s", pkgID)
205 continue // something changed underfoot, otherwise can't happen
206 }
207 pkgsyms := allpkgsyms[i]
208 pkgfname := pkgsyms.Files[0].Path()
209 if !imports.CanUse(c.filename, pkgfname) {
210 // avoid unusable internal, etc
211 continue
212 }
213 // are any of these any good?
214 for np, asym := range pkgsyms.Symbols {
215 for _, sym := range asym {
216 if !token.IsExported(sym.Name) {
217 continue
218 }
219 if !usefulCompletion(sym.Name, pattern) {
220 // for json.U, the existing code finds InvalidUTF8Error
221 continue
222 }
223 var params []string
224 var kind protocol.CompletionItemKind
225 var detail string
226 switch sym.Kind {
227 case protocol.Function:
228 foundURI := pkgsyms.Files[np]
229 fh, _ := c.snapshot.ReadFile(ctx, foundURI)
230 pgf, err := c.snapshot.ParseGo(ctx, fh, 0)
231 if err == nil {
232 params = funcParams(pgf.File, sym.Name)
233 }
234 kind = protocol.FunctionCompletion
235 detail = fmt.Sprintf("func (from %q)", pkg.PkgPath)
236 case protocol.Variable, protocol.Struct:
237 kind = protocol.VariableCompletion
238 detail = fmt.Sprintf("var (from %q)", pkg.PkgPath)
239 case protocol.Constant:
240 kind = protocol.ConstantCompletion
241 detail = fmt.Sprintf("const (from %q)", pkg.PkgPath)
242 default:
243 continue
244 }
245 got = c.appendNewItem(got, sym.Name,
246 detail,
247 pkg.PkgPath,
248 kind,
249 pkgname, params)
250 }
251 }
252 }
253 return got
254 }
255
256 // return CompletionItems for all the matches in packages in pkgs.
257 func (c *completer) stdlibMatches(pkgs []metadata.PackagePath, pkg metadata.PackageName, prefix string) []CompletionItem {
258 // check for deprecated symbols someday
259 got := make([]CompletionItem, 0)
260 pattern := strings.ToLower(prefix)
261 // avoid non-determinacy, especially for marker tests
262 slices.Sort(pkgs)
263 for _, candpkg := range pkgs {
264 if std, ok := stdlib.PackageSymbols[string(candpkg)]; ok {
265 for _, sym := range std {
266 if !usefulCompletion(sym.Name, pattern) {
267 continue
268 }
269 if !versions.AtLeast(c.goversion, sym.Version.String()) {
270 continue
271 }
272 var kind protocol.CompletionItemKind
273 var detail string
274 var params []string
275 switch sym.Kind {
276 case stdlib.Func:
277 params = parseSignature(sym.Signature)
278 kind = protocol.FunctionCompletion
279 detail = fmt.Sprintf("func (from %q)", candpkg)
280 case stdlib.Const:
281 kind = protocol.ConstantCompletion
282 detail = fmt.Sprintf("const (from %q)", candpkg)
283 case stdlib.Var:
284 kind = protocol.VariableCompletion
285 detail = fmt.Sprintf("var (from %q)", candpkg)
286 case stdlib.Type:
287 kind = protocol.VariableCompletion
288 detail = fmt.Sprintf("type (from %q)", candpkg)
289 default:
290 continue
291 }
292 got = c.appendNewItem(got, sym.Name,
293 detail,
294 candpkg,
295 kind,
296 pkg, params)
297 }
298 }
299 }
300 return got
301 }
302
303 func (c *completer) modcacheMatches(pkg metadata.PackageName, prefix string) ([]CompletionItem, error) {
304 ix, err := c.snapshot.View().ModcacheIndex()
305 if err != nil {
306 return nil, err
307 }
308 // retrieve everything and let usefulCompletion() and the matcher sort them out
309 cands := ix.Lookup(string(pkg), "", true)
310 lx := len(cands)
311 got := make([]CompletionItem, 0, lx)
312 pattern := strings.ToLower(prefix)
313 for _, cand := range cands {
314 if !usefulCompletion(cand.Name, pattern) {
315 continue
316 }
317 var params []string
318 var kind protocol.CompletionItemKind
319 var detail string
320 switch cand.Type {
321 case modindex.Func:
322 for _, f := range cand.Sig {
323 params = append(params, fmt.Sprintf("%s %s", f.Arg, f.Type))
324 }
325 kind = protocol.FunctionCompletion
326 detail = fmt.Sprintf("func (from %s)", cand.ImportPath)
327 case modindex.Var:
328 kind = protocol.VariableCompletion
329 detail = fmt.Sprintf("var (from %s)", cand.ImportPath)
330 case modindex.Const:
331 kind = protocol.ConstantCompletion
332 detail = fmt.Sprintf("const (from %s)", cand.ImportPath)
333 case modindex.Type: // might be a type alias
334 kind = protocol.VariableCompletion
335 detail = fmt.Sprintf("type (from %s)", cand.ImportPath)
336 default:
337 continue
338 }
339 got = c.appendNewItem(got, cand.Name,
340 detail,
341 metadata.PackagePath(cand.ImportPath),
342 kind,
343 pkg, params)
344 }
345 return got, nil
346 }
347
348 func (c *completer) appendNewItem(got []CompletionItem, name, detail string, path metadata.PackagePath, kind protocol.CompletionItemKind, pkg metadata.PackageName, params []string) []CompletionItem {
349 item := CompletionItem{
350 Label: name,
351 Detail: detail,
352 InsertText: name,
353 Kind: kind,
354 }
355 imp := importInfo{
356 importPath: string(path),
357 name: string(pkg),
358 }
359 if imports.ImportPathToAssumedName(string(path)) == string(pkg) {
360 imp.name = ""
361 }
362 item.AdditionalTextEdits, _ = c.importEdits(&imp)
363 if params != nil {
364 var sn snippet.Builder
365 c.functionCallSnippet(name, nil, params, &sn)
366 item.snippet = &sn
367 }
368 got = append(got, item)
369 return got
370 }
371
372 // score the list. Return true if any item is added to c.items
373 func (c *completer) scoreList(items []CompletionItem) bool {
374 ret := false
375 for _, item := range items {
376 item.Score = float64(c.matcher.Score(item.Label))
377 if item.Score > 0 {
378 c.items = append(c.items, item)
379 ret = true
380 }
381 }
382 return ret
383 }
384
385 // pattern is always the result of strings.ToLower
386 func usefulCompletion(name, pattern string) bool {
387 // this travesty comes from foo.(type) somehow. see issue59096.txt
388 if pattern == "_" {
389 return true
390 }
391 // convert both to lower case, and then the runes in the pattern have to occur, in order,
392 // in the name
393 cand := strings.ToLower(name)
394 for _, r := range pattern {
395 ix := strings.IndexRune(cand, r)
396 if ix < 0 {
397 return false
398 }
399 cand = cand[ix+1:]
400 }
401 return true
402 }
403
404 // return a printed version of the function arguments for snippets
405 func funcParams(f *ast.File, fname string) []string {
406 var params []string
407 setParams := func(list *ast.FieldList) {
408 if list == nil {
409 return
410 }
411 var cfg printer.Config // slight overkill
412 param := func(name string, typ ast.Expr) {
413 var buf strings.Builder
414 buf.WriteString(name)
415 buf.WriteByte(' ')
416 cfg.Fprint(&buf, token.NewFileSet(), typ) // ignore error
417 params = append(params, buf.String())
418 }
419
420 for _, field := range list.List {
421 if field.Names != nil {
422 for _, name := range field.Names {
423 param(name.Name, field.Type)
424 }
425 } else {
426 param("_", field.Type)
427 }
428 }
429 }
430 for _, n := range f.Decls {
431 switch x := n.(type) {
432 case *ast.FuncDecl:
433 if x.Recv == nil && x.Name.Name == fname {
434 setParams(x.Type.Params)
435 }
436 }
437 }
438 return params
439 }
440
441 // extract the formal parameters from the signature.
442 // func[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2) -> []{"dst M1", "src M2"}
443 // func[K comparable, V any](seq iter.Seq2[K, V]) map[K]V -> []{"seq iter.Seq2[K, V]"}
444 // func(args ...any) *Logger -> []{"args ...any"}
445 // func[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool) -> []{"m M", "del func(K, V) bool"}
446 func parseSignature(sig string) []string {
447 var level int // nesting level of delimiters
448 var processing bool // are we doing the params
449 var last int // start of current parameter
450 var params []string
451 for i := range len(sig) {
452 switch sig[i] {
453 case '[', '{':
454 level++
455 case ']', '}':
456 level--
457 case '(':
458 level++
459 if level == 1 {
460 processing = true
461 last = i + 1
462 }
463 case ')':
464 level--
465 if level == 0 && processing { // done
466 if i > last {
467 params = append(params, strings.TrimSpace(sig[last:i]))
468 }
469 return params
470 }
471 case ',':
472 if level == 1 && processing {
473 params = append(params, strings.TrimSpace(sig[last:i]))
474 last = i + 1
475 }
476 }
477 }
478 return nil
479 }