Debian Codegraph @

gopls/internal/golang/completion/completion.go

raw symbols SCIP
1 // Copyright 2018 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 provides core functionality for code completion in Go
6 // editors and tools.
7 package completion
8
9 import (
10 "context"
11 "fmt"
12 "go/ast"
13 "go/constant"
14 "go/scanner"
15 "go/token"
16 "go/types"
17 "iter"
18 "math"
19 "slices"
20 "sort"
21 "strconv"
22 "strings"
23 "sync"
24 "time"
25 "unicode"
26 "unicode/utf8"
27
28 goastutil "golang.org/x/tools/go/ast/astutil"
29 "golang.org/x/tools/gopls/internal/cache"
30 "golang.org/x/tools/gopls/internal/cache/metadata"
31 "golang.org/x/tools/gopls/internal/cache/parsego"
32 "golang.org/x/tools/gopls/internal/file"
33 "golang.org/x/tools/gopls/internal/fuzzy"
34 "golang.org/x/tools/gopls/internal/golang"
35 "golang.org/x/tools/gopls/internal/golang/completion/snippet"
36 "golang.org/x/tools/gopls/internal/protocol"
37 "golang.org/x/tools/gopls/internal/settings"
38 "golang.org/x/tools/gopls/internal/util/bug"
39 "golang.org/x/tools/gopls/internal/util/safetoken"
40 "golang.org/x/tools/internal/astutil"
41 "golang.org/x/tools/internal/event"
42 "golang.org/x/tools/internal/imports"
43 "golang.org/x/tools/internal/typeparams"
44 "golang.org/x/tools/internal/typesinternal"
45 "golang.org/x/tools/internal/versions"
46 )
47
48 // A CompletionItem represents a possible completion suggested by the algorithm.
49 type CompletionItem struct {
50
51 // Invariant: CompletionItem does not refer to syntax or types.
52
53 // Label is the primary text the user sees for this completion item.
54 Label string
55
56 // Detail is supplemental information to present to the user.
57 // This often contains the type or return type of the completion item.
58 Detail string
59
60 // InsertText is the text to insert if this item is selected.
61 // Any of the prefix that has already been typed is not trimmed.
62 // The insert text does not contain snippets.
63 InsertText string
64
65 Kind protocol.CompletionItemKind
66 Tags []protocol.CompletionItemTag
67 Deprecated bool // Deprecated, prefer Tags if available
68
69 // An optional array of additional TextEdits that are applied when
70 // selecting this completion.
71 //
72 // Additional text edits should be used to change text unrelated to the current cursor position
73 // (for example adding an import statement at the top of the file if the completion item will
74 // insert an unqualified type).
75 AdditionalTextEdits []protocol.TextEdit
76
77 // Depth is how many levels were searched to find this completion.
78 // For example when completing "foo<>", "fooBar" is depth 0, and
79 // "fooBar.Baz" is depth 1.
80 Depth int
81
82 // Score is the internal relevance score.
83 // A higher score indicates that this completion item is more relevant.
84 Score float64
85
86 // snippet is the LSP snippet for the completion item. The LSP
87 // specification contains details about LSP snippets. For example, a
88 // snippet for a function with the following signature:
89 //
90 // func foo(a, b, c int)
91 //
92 // would be:
93 //
94 // foo(${1:a int}, ${2: b int}, ${3: c int})
95 //
96 // If Placeholders is false in the CompletionOptions, the above
97 // snippet would instead be:
98 //
99 // foo(${1:})
100 snippet *snippet.Builder
101
102 // Documentation is the documentation for the completion item.
103 Documentation string
104
105 // isSlice reports whether the underlying type of the object
106 // from which this candidate was derived is a slice.
107 // (Used to complete append() calls.)
108 isSlice bool
109 }
110
111 // completionOptions holds completion specific configuration.
112 type completionOptions struct {
113 unimported bool
114 documentation bool
115 fullDocumentation bool
116 placeholders bool
117 snippets bool
118 postfix bool
119 matcher settings.Matcher
120 budget time.Duration
121 completeFunctionCalls bool
122 }
123
124 // Snippet is a convenience returns the snippet if available, otherwise
125 // the InsertText.
126 // used for an item, depending on if the callee wants placeholders or not.
127 func (i *CompletionItem) Snippet() string {
128 if i.snippet != nil {
129 return i.snippet.String()
130 }
131 return i.InsertText
132 }
133
134 // addConversion wraps the existing completionItem in a conversion expression.
135 // Only affects the receiver's InsertText and snippet fields, not the Label.
136 // An empty conv argument has no effect.
137 func (i *CompletionItem) addConversion(c *completer, conv conversionEdits) {
138 if conv.prefix != "" {
139 // If we are in a selector, add an edit to place prefix before selector.
140 if sel := enclosingSelector(c.path, c.pos); sel != nil {
141 edits, err := c.editText(sel.Pos(), sel.Pos(), conv.prefix)
142 if err != nil {
143 // safetoken failed: invalid token.Pos information in AST.
144 return
145 }
146 i.AdditionalTextEdits = append(i.AdditionalTextEdits, edits...)
147 } else {
148 // If there is no selector, just stick the prefix at the start.
149 i.InsertText = conv.prefix + i.InsertText
150 i.snippet.PrependText(conv.prefix)
151 }
152 }
153
154 if conv.suffix != "" {
155 i.InsertText += conv.suffix
156 i.snippet.WriteText(conv.suffix)
157 }
158 }
159
160 // Scoring constants are used for weighting the relevance of different candidates.
161 const (
162 // lowScore indicates an irrelevant or not useful completion item.
163 lowScore float64 = 0.01
164
165 // stdScore is the base score for all completion items.
166 stdScore float64 = 1.0
167
168 // highScore indicates a very relevant completion item.
169 highScore float64 = 10.0
170 )
171
172 // matcher matches a candidate's label against the user input. The
173 // returned score reflects the quality of the match. A score of zero
174 // indicates no match, and a score of one means a perfect match.
175 type matcher interface {
176 Score(candidateLabel string) (score float32)
177 }
178
179 // prefixMatcher implements case sensitive prefix matching.
180 type prefixMatcher string
181
182 func (pm prefixMatcher) Score(candidateLabel string) float32 {
183 if strings.HasPrefix(candidateLabel, string(pm)) {
184 return 1
185 }
186 return -1
187 }
188
189 // insensitivePrefixMatcher implements case insensitive prefix matching.
190 type insensitivePrefixMatcher string
191
192 func (ipm insensitivePrefixMatcher) Score(candidateLabel string) float32 {
193 if strings.HasPrefix(strings.ToLower(candidateLabel), string(ipm)) {
194 return 1
195 }
196 return -1
197 }
198
199 // completer contains the necessary information for a single completion request.
200 type completer struct {
201 snapshot *cache.Snapshot
202 pkg *cache.Package
203 qual types.Qualifier // for qualifying typed expressions
204 mq golang.MetadataQualifier // for syntactic qualifying
205 opts *completionOptions
206
207 // completionContext contains information about the trigger for this
208 // completion request.
209 completionContext completionContext
210
211 // fh is a handle to the file associated with this completion request.
212 fh file.Handle
213
214 // filename is the name of the file associated with this completion request.
215 filename string
216
217 // pgf is the AST of the file associated with this completion request.
218 pgf *parsego.File // debugging
219
220 // goversion is the version of Go in force in the file, as
221 // defined by x/tools/internal/versions. Empty if unknown.
222 // Since go1.22 it should always be known.
223 goversion string
224
225 // pos is the position at which the request was triggered.
226 pos token.Pos
227
228 // path is the path of AST nodes enclosing the position.
229 path []ast.Node
230
231 // seen is the map that ensures we do not return duplicate results.
232 seen map[types.Object]bool
233
234 // items is the list of completion items returned.
235 items []CompletionItem
236
237 // completionCallbacks is a list of callbacks to collect completions that
238 // require expensive operations. This includes operations where we search
239 // through the entire module cache.
240 completionCallbacks []func(context.Context, *imports.Options) error
241
242 // surrounding describes the identifier surrounding the position.
243 surrounding *Selection
244
245 // inferredSelectorLHS is the identifier before the dot in a selector
246 // expression, inferred from tokens when the AST is broken.
247 inferredSelectorLHS string
248
249 // inference contains information we've inferred about ideal
250 // candidates such as the candidate's type.
251 inference candidateInference
252
253 // enclosingFunc contains information about the function enclosing
254 // the position.
255 enclosingFunc *funcInfo
256
257 // enclosingCompositeLiteral contains information about the composite literal
258 // enclosing the position.
259 enclosingCompositeLiteral *compLitInfo
260
261 // deepState contains the current state of our deep completion search.
262 deepState deepCompletionState
263
264 // matcher matches the candidates against the surrounding prefix.
265 matcher matcher
266
267 // methodSetCache caches the [types.NewMethodSet] call, which is relatively
268 // expensive and can be called many times for the same type while searching
269 // for deep completions.
270 // TODO(adonovan): use [typeutil.MethodSetCache], which exists for this purpose.
271 methodSetCache map[methodSetKey]*types.MethodSet
272
273 // tooNewSymbolsCache is a cache of
274 // [typesinternal.TooNewStdSymbols], recording for each std
275 // package which of its exported symbols are too new for
276 // the version of Go in force in the completion file.
277 // (The value is the minimum version in the form "go1.%d".)
278 tooNewSymbolsCache map[*types.Package]map[types.Object]string
279
280 // mapper converts the positions in the file from which the completion originated.
281 mapper *protocol.Mapper
282
283 // startTime is when we started processing this completion request. It does
284 // not include any time the request spent in the queue.
285 //
286 // Note: in CL 503016, startTime move to *after* type checking, but it was
287 // subsequently determined that it was better to keep setting it *before*
288 // type checking, so that the completion budget best approximates the user
289 // experience. See golang/go#62665 for more details.
290 startTime time.Time
291
292 // scopes contains all scopes defined by nodes in our path,
293 // including nil values for nodes that don't defined a scope. It
294 // also includes our package scope and the universal scope at the
295 // end.
296 //
297 // (It is tempting to replace this with fileScope.Innermost(pos)
298 // and simply follow the Scope.Parent chain, but we need to
299 // preserve the pairwise association of scopes[i] and path[i]
300 // because there is no way to get from the Scope to the Node.)
301 scopes []*types.Scope
302 }
303
304 // tooNew reports whether obj is a standard library symbol that is too
305 // new for the specified Go version.
306 func (c *completer) tooNew(obj types.Object) bool {
307 pkg := obj.Pkg()
308 if pkg == nil {
309 return false // unsafe.Pointer or error.Error
310 }
311 disallowed, ok := c.tooNewSymbolsCache[pkg]
312 if !ok {
313 disallowed = typesinternal.TooNewStdSymbols(pkg, c.goversion)
314 c.tooNewSymbolsCache[pkg] = disallowed
315 }
316 return disallowed[obj] != ""
317 }
318
319 // funcInfo holds info about a function object.
320 type funcInfo struct {
321 // sig is the function declaration enclosing the position.
322 sig *types.Signature
323
324 // body is the function's body.
325 body *ast.BlockStmt
326 }
327
328 type compLitInfo struct {
329 // cl is the *ast.CompositeLit enclosing the position.
330 cl *ast.CompositeLit
331
332 // clType is the type of cl.
333 clType types.Type
334
335 // kv is the *ast.KeyValueExpr enclosing the position, if any.
336 kv *ast.KeyValueExpr
337
338 // inKey is true if we are certain the position is in the key side
339 // of a key-value pair.
340 inKey bool
341
342 // maybeInFieldName is true if inKey is false and it is possible
343 // we are completing a struct field name. For example,
344 // "SomeStruct{<>}" will be inKey=false, but maybeInFieldName=true
345 // because we _could_ be completing a field name.
346 maybeInFieldName bool
347 }
348
349 type importInfo struct {
350 importPath string
351 name string
352 }
353
354 type methodSetKey struct {
355 typ types.Type
356 addressable bool
357 }
358
359 type completionContext struct {
360 // triggerCharacter is the character used to trigger completion at current
361 // position, if any.
362 triggerCharacter string
363
364 // triggerKind is information about how a completion was triggered.
365 triggerKind protocol.CompletionTriggerKind
366
367 // commentCompletion is true if we are completing a comment.
368 commentCompletion bool
369
370 // commentNeedsLeadingSpace is true when the completion edit range starts
371 // immediately after "//" with no intervening space. Completion items should
372 // prepend a space so that accepting a suggestion produces "// Name" rather
373 // than "//Name". This applies both when the cursor is right after "//" and
374 // when the user has partially typed an identifier (e.g. "//Fo").
375 commentNeedsLeadingSpace bool
376
377 // packageCompletion is true if we are completing a package name.
378 packageCompletion bool
379 }
380
381 // A Selection represents the cursor position and surrounding identifier.
382 type Selection struct {
383 content string // invariant: 0<=cursor-start<=len(content)
384 tokFile *token.File
385 start, end, cursor token.Pos // relative to rng.TokFile
386 mapper *protocol.Mapper
387 }
388
389 // Range returns the surrounding identifier's protocol.Range.
390 func (p Selection) Range() (protocol.Range, error) {
391 return p.mapper.PosRange(p.tokFile, p.start, p.end)
392 }
393
394 // PrefixRange returns the protocol.Range of the prefix of the selection.
395 func (p Selection) PrefixRange() (protocol.Range, error) {
396 return p.mapper.PosRange(p.tokFile, p.start, p.cursor)
397 }
398
399 func (p Selection) Prefix() string {
400 return p.content[:p.cursor-p.start]
401 }
402
403 func (p Selection) Suffix() string {
404 return p.content[p.cursor-p.start:]
405 }
406
407 // check that Prefix and Suffix will succeed (golang/go#77050)
408 // at the time a Selection is constructed.
409 func (p Selection) check() {
410 offset := int(p.cursor - p.start)
411 // separate the cases so that they are distinguished in the stack trace
412 if offset < 0 {
413 bug.Reportf("Selection invariant, len(content)=%d cursor=%d start=%d", len(p.content), p.cursor, p.start)
414 }
415 if offset > len(p.content) {
416 bug.Reportf("Selection invariant, len(content)=%d cursor=%d start=%d", len(p.content), p.cursor, p.start)
417 }
418 }
419
420 func (c *completer) setSurrounding(ident *ast.Ident) {
421 if c.surrounding != nil {
422 return
423 }
424 if !(ident.Pos() <= c.pos && c.pos <= ident.End()) {
425 return
426 }
427
428 c.surrounding = &Selection{
429 content: ident.Name,
430 cursor: c.pos,
431 // Overwrite the prefix only.
432 tokFile: c.pgf.Tok,
433 start: ident.Pos(),
434 end: ident.End(),
435 mapper: c.mapper,
436 }
437 c.surrounding.check()
438
439 c.setMatcherFromPrefix(c.surrounding.Prefix())
440 }
441
442 func (c *completer) setMatcherFromPrefix(prefix string) {
443 switch c.opts.matcher {
444 case settings.Fuzzy:
445 c.matcher = fuzzy.NewMatcher(prefix)
446 case settings.CaseSensitive:
447 c.matcher = prefixMatcher(prefix)
448 default:
449 c.matcher = insensitivePrefixMatcher(strings.ToLower(prefix))
450 }
451 }
452
453 func (c *completer) getSurrounding() *Selection {
454 if c.surrounding == nil {
455 c.surrounding = &Selection{
456 content: "",
457 cursor: c.pos,
458 tokFile: c.pgf.Tok,
459 start: c.pos,
460 end: c.pos,
461 mapper: c.mapper,
462 }
463 c.surrounding.check()
464 }
465 return c.surrounding
466 }
467
468 // candidate represents a completion candidate.
469 type candidate struct {
470 // obj is the types.Object to complete to.
471 // TODO(adonovan): eliminate dependence on go/types throughout this struct.
472 // See comment in (*completer).selector for explanation.
473 obj types.Object
474
475 // score is used to rank candidates.
476 score float64
477
478 // name is the deep object name path, e.g. "foo.bar"
479 name string
480
481 // detail is additional information about this item. If not specified,
482 // defaults to type string for the object.
483 detail string
484
485 // path holds the path from the search root (excluding the candidate
486 // itself) for a deep candidate.
487 path []types.Object
488
489 // pathInvokeMask is a bit mask tracking whether each entry in path
490 // should be formatted with "()" (i.e. whether it is a function
491 // invocation).
492 pathInvokeMask uint16
493
494 // mods contains modifications that should be applied to the
495 // candidate when inserted. For example, "foo" may be inserted as
496 // "*foo" or "foo()".
497 mods []typeModKind
498
499 // addressable is true if a pointer can be taken to the candidate.
500 addressable bool
501
502 // convertTo is a type that this candidate should be cast to. For
503 // example, if convertTo is float64, "foo" should be formatted as
504 // "float64(foo)".
505 convertTo types.Type
506
507 // imp is the import that needs to be added to this package in order
508 // for this candidate to be valid. nil if no import needed.
509 imp *importInfo
510 }
511
512 func (c candidate) hasMod(mod typeModKind) bool {
513 return slices.Contains(c.mods, mod)
514 }
515
516 // Completion returns a list of possible candidates for completion, given a
517 // a file and a position.
518 //
519 // The selection is computed based on the preceding identifier and can be used by
520 // the client to score the quality of the completion. For instance, some clients
521 // may tolerate imperfect matches as valid completion results, since users may make typos.
522 func Completion(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, protoPos protocol.Position, protoContext protocol.CompletionContext) ([]CompletionItem, *Selection, error) {
523 ctx, done := event.Start(ctx, "completion.Completion")
524 defer done()
525
526 startTime := time.Now()
527
528 pkg, pgf, err := golang.NarrowestPackageForFile(ctx, snapshot, fh.URI())
529 if err != nil || !pgf.File.Package.IsValid() {
530 // Invalid package declaration
531 //
532 // If we can't parse this file or find position for the package
533 // keyword, it may be missing a package declaration. Try offering
534 // suggestions for the package declaration.
535 // Note that this would be the case even if the keyword 'package' is
536 // present but no package name exists.
537 items, surrounding, innerErr := packageClauseCompletions(ctx, snapshot, fh, protoPos)
538 if innerErr != nil {
539 // return the error for GetParsedFile since it's more relevant in this situation.
540 return nil, nil, fmt.Errorf("getting file %s for Completion: %v (package completions: %v)", fh.URI(), err, innerErr)
541 }
542 return items, surrounding, nil
543 }
544
545 pos, err := pgf.PositionPos(protoPos)
546 if err != nil {
547 return nil, nil, err
548 }
549 // Completion is based on what precedes the cursor.
550 // Find the path to the position before pos.
551 path, _ := goastutil.PathEnclosingInterval(pgf.File, pos-1, pos-1)
552 if path == nil {
553 return nil, nil, fmt.Errorf("cannot find node enclosing position")
554 }
555
556 info := pkg.TypesInfo()
557
558 // Check if completion at this position is valid. If not, return early.
559 switch n := path[0].(type) {
560 case *ast.BasicLit:
561 // Skip completion inside literals except for ImportSpec
562 if len(path) > 1 {
563 if _, ok := path[1].(*ast.ImportSpec); ok {
564 break
565 }
566 }
567 return nil, nil, nil
568 case *ast.CallExpr:
569 if n.Ellipsis.IsValid() && pos > n.Ellipsis && pos <= n.Ellipsis+token.Pos(len("...")) {
570 // Don't offer completions inside or directly after "...". For
571 // example, don't offer completions at "<>" in "foo(bar...<>").
572 return nil, nil, nil
573 }
574 case *ast.Ident:
575 // Don't offer completions for (most) defining identifiers.
576 if obj, ok := info.Defs[n]; ok {
577 if v, ok := obj.(*types.Var); ok && v.IsField() && v.Embedded() {
578 // Allow completion of anonymous fields, since they may reference type
579 // names.
580 } else if pgf.File.Name == n {
581 // Allow package name completion.
582 } else {
583 // Check if we have special completion for this definition, such as
584 // test function name completion.
585 ans, sel := definition(path, obj, pgf)
586 if ans != nil {
587 sort.Slice(ans, func(i, j int) bool {
588 return ans[i].Score > ans[j].Score
589 })
590 return ans, sel, nil
591 }
592
593 return nil, nil, nil // No completions.
594 }
595 }
596 }
597
598 // Collect all surrounding scopes, innermost first, inserting
599 // nils as needed to preserve the correspondence with path[i].
600 var scopes []*types.Scope
601 for _, n := range path {
602 switch node := n.(type) {
603 case *ast.FuncDecl:
604 n = node.Type
605 case *ast.FuncLit:
606 n = node.Type
607 }
608 scopes = append(scopes, info.Scopes[n])
609 }
610 scopes = append(scopes, pkg.Types().Scope(), types.Universe)
611
612 opts := snapshot.Options()
613 c := &completer{
614 pkg: pkg,
615 snapshot: snapshot,
616 qual: typesinternal.FileQualifier(pgf.File, pkg.Types()),
617 mq: golang.MetadataQualifierForFile(snapshot, pgf.File, pkg.Metadata()),
618 completionContext: completionContext{
619 triggerCharacter: protoContext.TriggerCharacter,
620 triggerKind: protoContext.TriggerKind,
621 },
622 fh: fh,
623 filename: fh.URI().Path(),
624 pgf: pgf,
625 goversion: versions.FileVersion(info, pgf.File), // may be "" => no version check
626 path: path,
627 pos: pos,
628 seen: make(map[types.Object]bool),
629 enclosingFunc: enclosingFunction(path, info),
630 enclosingCompositeLiteral: enclosingCompositeLiteral(path, pos, info),
631 deepState: deepCompletionState{
632 enabled: opts.DeepCompletion,
633 },
634 opts: &completionOptions{
635 matcher: opts.Matcher,
636 unimported: opts.CompleteUnimported,
637 documentation: opts.CompletionDocumentation && opts.HoverKind != settings.NoDocumentation,
638 fullDocumentation: opts.HoverKind == settings.FullDocumentation,
639 placeholders: opts.UsePlaceholders,
640 budget: opts.CompletionBudget,
641 snippets: opts.InsertTextFormat == protocol.SnippetTextFormat,
642 postfix: opts.ExperimentalPostfixCompletions,
643 completeFunctionCalls: opts.CompleteFunctionCalls,
644 },
645 // default to a matcher that always matches
646 matcher: prefixMatcher(""),
647 methodSetCache: make(map[methodSetKey]*types.MethodSet),
648 tooNewSymbolsCache: make(map[*types.Package]map[types.Object]string),
649 mapper: pgf.Mapper,
650 startTime: startTime,
651 scopes: scopes,
652 }
653
654 ctx, cancel := context.WithCancel(ctx)
655 defer cancel()
656
657 // Compute the deadline for this operation. Deadline is relative to the
658 // search operation, not the entire completion RPC, as the work up until this
659 // point depends significantly on how long it took to type-check, which in
660 // turn depends on the timing of the request relative to other operations on
661 // the snapshot. Including that work in the budget leads to inconsistent
662 // results (and realistically, if type-checking took 200ms already, the user
663 // is unlikely to be significantly more bothered by e.g. another 100ms of
664 // search).
665 //
666 // Don't overload the context with this deadline, as we don't want to
667 // conflate user cancellation (=fail the operation) with our time limit
668 // (=stop searching and succeed with partial results).
669 var deadline *time.Time
670 if c.opts.budget > 0 {
671 d := startTime.Add(c.opts.budget)
672 deadline = &d
673 }
674
675 if surrounding := c.containingIdent(pgf.Src); surrounding != nil {
676 c.setSurrounding(surrounding)
677 }
678
679 c.inference = expectedCandidate(ctx, c)
680
681 err = c.collectCompletions(ctx)
682 if err != nil {
683 return nil, nil, fmt.Errorf("failed to collect completions: %v", err)
684 }
685
686 // Deep search collected candidates and their members for more candidates.
687 c.deepSearch(ctx, 1, deadline)
688
689 // At this point we have a sufficiently complete set of results, and want to
690 // return as close to the completion budget as possible. Previously, we
691 // avoided cancelling the context because it could result in partial results
692 // for e.g. struct fields. At this point, we have a minimal valid set of
693 // candidates, and so truncating due to context cancellation is acceptable.
694 if c.opts.budget > 0 {
695 timeoutDuration := time.Until(c.startTime.Add(c.opts.budget))
696 ctx, cancel = context.WithTimeout(ctx, timeoutDuration)
697 defer cancel()
698 }
699
700 for _, callback := range c.completionCallbacks {
701 if deadline == nil || time.Now().Before(*deadline) {
702 if err := c.snapshot.RunProcessEnvFunc(ctx, callback); err != nil {
703 return nil, nil, fmt.Errorf("failed to run goimports callback: %v", err)
704 }
705 }
706 }
707
708 // Search candidates populated by expensive operations like
709 // unimportedMembers etc. for more completion items.
710 c.deepSearch(ctx, 0, deadline)
711
712 // Statement candidates offer an entire statement in certain contexts, as
713 // opposed to a single object. Add statement candidates last because they
714 // depend on other candidates having already been collected.
715 c.addStatementCandidates()
716
717 sortItems(c.items)
718 return c.items, c.getSurrounding(), nil
719 }
720
721 // collectCompletions adds possible completion candidates to either the deep
722 // search queue or completion items directly for different completion contexts.
723 func (c *completer) collectCompletions(ctx context.Context) error {
724 // Inside import blocks, return completions for unimported packages.
725 for _, importSpec := range c.pgf.File.Imports {
726 if !(importSpec.Path.Pos() <= c.pos && c.pos <= importSpec.Path.End()) {
727 continue
728 }
729 return c.populateImportCompletions(importSpec)
730 }
731
732 // Inside comments, offer completions for the name of the relevant symbol.
733 for _, comment := range c.pgf.File.Comments {
734 if comment.Pos() < c.pos && c.pos <= comment.End() {
735 c.populateCommentCompletions(comment)
736 return nil
737 }
738 }
739
740 // Struct literals are handled entirely separately.
741 if wantStructFieldCompletions(c.enclosingCompositeLiteral) {
742 // If we are definitely completing a struct field name, deep completions
743 // don't make sense.
744 if c.enclosingCompositeLiteral.inKey {
745 c.deepState.enabled = false
746 }
747 return c.structLiteralFieldName(ctx)
748 }
749
750 if lt := c.wantLabelCompletion(); lt != labelNone {
751 c.labels(lt)
752 return nil
753 }
754
755 if c.emptySwitchStmt() {
756 // Empty switch statements only admit "default" and "case" keywords.
757 c.addKeywordItems(map[string]bool{}, highScore, CASE, DEFAULT)
758 return nil
759 }
760
761 switch n := c.path[0].(type) {
762 case *ast.Ident:
763 if c.pgf.File.Name == n {
764 return c.packageNameCompletions(ctx, c.fh.URI(), n)
765 } else if sel, ok := c.path[1].(*ast.SelectorExpr); ok && sel.Sel == n {
766 // We are in the Sel part of a selector (e.g. x.‸sel or x.sel‸).
767 return c.selector(ctx, sel)
768 }
769 return c.lexical(ctx)
770
771 case *ast.TypeAssertExpr:
772 // The function name hasn't been typed yet, but the parens are there:
773 // recv.‸(arg)
774 // Create a fake selector expression.
775
776 // The name "_" is the convention used by go/parser to represent phantom
777 // selectors.
778 sel := &ast.Ident{NamePos: n.X.End() + token.Pos(len(".")), Name: "_"}
779 return c.selector(ctx, &ast.SelectorExpr{X: n.X, Sel: sel})
780
781 case *ast.SelectorExpr:
782 // We are in the X part of a selector (x‸.sel),
783 // or after the dot with a fixed/phantom Sel (x.‸_).
784 return c.selector(ctx, n)
785
786 case *ast.BadDecl, *ast.File:
787 // At the file scope, only keywords are allowed.
788 c.addKeywordCompletions()
789
790 default:
791 if c.tryInferredSelector() {
792 return nil
793 }
794 // fallback to lexical completions
795 return c.lexical(ctx)
796 }
797
798 return nil
799 }
800
801 // tryInferredSelector attempts to complete members of an inferred selector LHS.
802 // It returns true if it successfully added completion items.
803 func (c *completer) tryInferredSelector() bool {
804 if c.inferredSelectorLHS == "" {
805 return false
806 }
807 for _, scope := range c.scopes {
808 if scope == nil {
809 continue
810 }
811 obj := scope.Lookup(c.inferredSelectorLHS)
812 if obj == nil {
813 continue
814 }
815 if pkgName, ok := obj.(*types.PkgName); ok {
816 c.packageMembers(pkgName.Imported(), stdScore, nil, c.deepState.enqueue)
817 return true
818 }
819 if typeIsValid(obj.Type()) {
820 c.methodsAndFields(obj.Type(), isVar(obj), nil, c.deepState.enqueue)
821 return true
822 }
823 }
824 return false
825 }
826
827 // containingIdent returns the *ast.Ident containing pos, if any. It
828 // synthesizes an *ast.Ident to allow completion in the face of
829 // certain syntax errors.
830 func (c *completer) containingIdent(src []byte) *ast.Ident {
831 // In the normal case, our leaf AST node is the identifier being completed.
832 if ident, ok := c.path[0].(*ast.Ident); ok {
833 return ident
834 }
835
836 pos, tkn, lit := c.scanToken(src)
837 if ok, lhs := c.inferSelector(src); ok {
838 c.inferredSelectorLHS = lhs
839 }
840 if !pos.IsValid() {
841 return nil
842 }
843
844 fakeIdent := &ast.Ident{Name: lit, NamePos: pos}
845 if _, isBadDecl := c.path[0].(*ast.BadDecl); isBadDecl {
846 // You don't get *ast.Idents at the file level, so look for bad
847 // decls and use the manually extracted token.
848 return fakeIdent
849 } else if c.emptySwitchStmt() {
850 // Only keywords are allowed in empty switch statements.
851 // *ast.Idents are not parsed, so we must use the manually
852 // extracted token.
853 return fakeIdent
854 } else if tkn.IsKeyword() {
855 // Otherwise, manually extract the prefix if our containing token
856 // is a keyword. This improves completion after an "accidental
857 // keyword", e.g. completing to "variance" in "someFunc(var<>)".
858 return fakeIdent
859 } else if tkn == token.IDENT {
860 // If the token is an identifier but was not parsed as an *ast.Ident
861 // (likely due to syntax errors), use the scanned token.
862 return fakeIdent
863 } else if block, ok := c.path[0].(*ast.BlockStmt); ok && len(block.List) != 0 {
864 last := block.List[len(block.List)-1]
865 // Handle incomplete AssignStmt with multiple left-hand vars:
866 // var left, right int
867 // left, ri‸ -> "right"
868 if expr, ok := last.(*ast.ExprStmt); ok &&
869 (is[*ast.Ident](expr.X) ||
870 is[*ast.SelectorExpr](expr.X) ||
871 is[*ast.IndexExpr](expr.X) ||
872 is[*ast.StarExpr](expr.X)) {
873 return fakeIdent
874 }
875 }
876
877 return nil
878 }
879
880 // scanToken scans pgh's contents for the token containing pos.
881 func (c *completer) scanToken(contents []byte) (token.Pos, token.Token, string) {
882 tok := c.pkg.FileSet().File(c.pos)
883
884 var s scanner.Scanner
885 // TODO(adonovan): fix! this mutates the token.File borrowed from c.pkg,
886 // calling AddLine and AddLineColumnInfo. Not sound!
887 s.Init(tok, contents, nil, 0)
888 for {
889 tknPos, tkn, lit := s.Scan()
890 if tkn == token.EOF || tknPos >= c.pos {
891 return token.NoPos, token.ILLEGAL, ""
892 }
893
894 if len(lit) > 0 && tknPos <= c.pos && c.pos <= tknPos+token.Pos(len(lit)) {
895 return tknPos, tkn, lit
896 }
897 }
898 }
899
900 // inferSelector attempts to infer if the cursor is at a selector expression
901 // (IDENT . IDENT or IDENT .) in invalid code where the AST is broken.
902 // It returns true and the literal of the LHS identifier if detected.
903 func (c *completer) inferSelector(src []byte) (bool, string) {
904 offset, err := safetoken.Offset(c.pgf.Tok, c.pos)
905 if err != nil {
906 return false, ""
907 }
908
909 // scanBackIdent scans backward from src[:end] over valid Go identifier
910 // characters (Unicode letters, digits, '_') and returns the start offset.
911 scanBackIdent := func(end int) int {
912 i := end
913 for i > 0 {
914 r, size := utf8.DecodeLastRune(src[:i])
915 if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' {
916 break
917 }
918 i -= size
919 }
920 return i
921 }
922
923 // Skip past the identifier at cursor (if any).
924 beforeIdent := scanBackIdent(offset)
925
926 // Check for a dot.
927 if beforeIdent <= 0 || src[beforeIdent-1] != '.' {
928 return false, ""
929 }
930
931 // Find the identifier before the dot.
932 startOfLHS := scanBackIdent(beforeIdent - 1)
933 if startOfLHS == beforeIdent-1 {
934 return false, ""
935 }
936
937 lhs := string(src[startOfLHS : beforeIdent-1])
938 if !token.IsIdentifier(lhs) {
939 return false, ""
940 }
941 return true, lhs
942 }
943
944 func sortItems(items []CompletionItem) {
945 sort.SliceStable(items, func(i, j int) bool {
946 // Sort by score first.
947 if items[i].Score != items[j].Score {
948 return items[i].Score > items[j].Score
949 }
950
951 // Then sort by label so order stays consistent. This also has the
952 // effect of preferring shorter candidates.
953 return items[i].Label < items[j].Label
954 })
955 }
956
957 // emptySwitchStmt reports whether pos is in an empty switch or select
958 // statement.
959 func (c *completer) emptySwitchStmt() bool {
960 block, ok := c.path[0].(*ast.BlockStmt)
961 if !ok || len(block.List) > 0 || len(c.path) == 1 {
962 return false
963 }
964
965 switch c.path[1].(type) {
966 case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt:
967 return true
968 default:
969 return false
970 }
971 }
972
973 // populateImportCompletions yields completions for an import path around the cursor.
974 //
975 // Completions are suggested at the directory depth of the given import path so
976 // that we don't overwhelm the user with a large list of possibilities. As an
977 // example, a completion for the prefix "golang" results in "golang.org/".
978 // Completions for "golang.org/" yield its subdirectories
979 // (i.e. "golang.org/x/"). The user is meant to accept completion suggestions
980 // until they reach a complete import path.
981 func (c *completer) populateImportCompletions(searchImport *ast.ImportSpec) error {
982 if !strings.HasPrefix(searchImport.Path.Value, `"`) {
983 return nil
984 }
985
986 // deepSearch is not valuable for import completions.
987 c.deepState.enabled = false
988
989 importPath := searchImport.Path.Value
990
991 // Extract the text between the quotes (if any) in an import spec.
992 // prefix is the part of import path before the cursor.
993 prefixEnd := c.pos - searchImport.Path.Pos()
994 prefix := strings.Trim(importPath[:prefixEnd], `"`)
995
996 // The number of directories in the import path gives us the depth at
997 // which to search.
998 depth := len(strings.Split(prefix, "/")) - 1
999
1000 content := importPath
1001 start, end := searchImport.Path.Pos(), searchImport.Path.End()
1002 namePrefix, nameSuffix := `"`, `"`
1003 // If a starting quote is present, adjust surrounding to either after the
1004 // cursor or after the first slash (/), except if cursor is at the starting
1005 // quote. Otherwise we provide a completion including the starting quote.
1006 if strings.HasPrefix(importPath, `"`) && c.pos > searchImport.Path.Pos() {
1007 content = content[1:]
1008 start++
1009 if depth > 0 {
1010 // Adjust textEdit start to replacement range. For ex: if current
1011 // path was "golang.or/x/to<>ols/internal/", where <> is the cursor
1012 // position, start of the replacement range would be after
1013 // "golang.org/x/".
1014 path := strings.SplitAfter(prefix, "/")
1015 numChars := len(strings.Join(path[:len(path)-1], ""))
1016 content = content[numChars:]
1017 start += token.Pos(numChars)
1018 }
1019 namePrefix = ""
1020 }
1021
1022 // We won't provide an ending quote if one is already present, except if
1023 // cursor is after the ending quote but still in import spec. This is
1024 // because cursor has to be in our textEdit range.
1025 if strings.HasSuffix(importPath, `"`) && c.pos < searchImport.Path.End() {
1026 end--
1027 content = content[:len(content)-1]
1028 nameSuffix = ""
1029 }
1030
1031 c.surrounding = &Selection{
1032 content: content,
1033 cursor: c.pos,
1034 tokFile: c.pgf.Tok,
1035 start: start,
1036 end: end,
1037 mapper: c.mapper,
1038 }
1039 c.surrounding.check()
1040
1041 seenImports := make(map[string]struct{})
1042 for _, importSpec := range c.pgf.File.Imports {
1043 if importSpec.Path.Value == importPath {
1044 continue
1045 }
1046 seenImportPath, err := strconv.Unquote(importSpec.Path.Value)
1047 if err != nil {
1048 return err
1049 }
1050 seenImports[seenImportPath] = struct{}{}
1051 }
1052
1053 var mu sync.Mutex // guard c.items locally, since searchImports is called in parallel
1054 seen := make(map[string]struct{})
1055 searchImports := func(pkg imports.ImportFix) {
1056 path := pkg.StmtInfo.ImportPath
1057 if _, ok := seenImports[path]; ok {
1058 return
1059 }
1060
1061 // Any package path containing fewer directories than the search
1062 // prefix is not a match.
1063 pkgDirList := strings.Split(path, "/")
1064 if len(pkgDirList) < depth+1 {
1065 return
1066 }
1067 pkgToConsider := strings.Join(pkgDirList[:depth+1], "/")
1068
1069 name := pkgDirList[depth]
1070 // if we're adding an opening quote to completion too, set name to full
1071 // package path since we'll need to overwrite that range.
1072 if namePrefix == `"` {
1073 name = pkgToConsider
1074 }
1075
1076 score := pkg.Relevance
1077 if len(pkgDirList)-1 == depth {
1078 score *= highScore
1079 } else {
1080 // For incomplete package paths, add a terminal slash to indicate that the
1081 // user should keep triggering completions.
1082 name += "/"
1083 pkgToConsider += "/"
1084 }
1085
1086 if _, ok := seen[pkgToConsider]; ok {
1087 return
1088 }
1089 seen[pkgToConsider] = struct{}{}
1090
1091 mu.Lock()
1092 defer mu.Unlock()
1093
1094 name = namePrefix + name + nameSuffix
1095 obj := types.NewPkgName(0, nil, name, types.NewPackage(pkgToConsider, name))
1096 c.deepState.enqueue(candidate{
1097 obj: obj,
1098 detail: strconv.Quote(pkgToConsider),
1099 score: score,
1100 })
1101 }
1102
1103 c.completionCallbacks = append(c.completionCallbacks, func(ctx context.Context, opts *imports.Options) error {
1104 if err := imports.GetImportPaths(ctx, searchImports, prefix, c.filename, c.pkg.Types().Name(), opts.Env); err != nil {
1105 return fmt.Errorf("getting import paths: %v", err)
1106 }
1107 return nil
1108 })
1109 return nil
1110 }
1111
1112 // populateCommentCompletions yields completions for comments preceding or in declarations.
1113 func (c *completer) populateCommentCompletions(comment *ast.CommentGroup) {
1114 // If the completion was triggered by a period, ignore it. These types of
1115 // completions will not be useful in comments.
1116 if c.completionContext.triggerCharacter == "." {
1117 return
1118 }
1119
1120 // Using the comment position find the line after
1121 file := c.pkg.FileSet().File(comment.End())
1122 if file == nil {
1123 return
1124 }
1125
1126 // Deep completion doesn't work properly in comments since we don't
1127 // have a type object to complete further.
1128 c.deepState.enabled = false
1129 c.completionContext.commentCompletion = true
1130
1131 // Documentation isn't useful in comments, since it might end up being the
1132 // comment itself.
1133 c.opts.documentation = false
1134
1135 commentLine := safetoken.Line(file, comment.End())
1136
1137 // comment is valid, set surrounding as word boundaries around cursor
1138 c.setSurroundingForComment(comment)
1139
1140 // If the edit range (what's being replaced) starts immediately after "//"
1141 // with no space, completions must prepend a space to produce proper Go doc
1142 // comment style ("// Name" rather than "//Name"). This covers both the case
1143 // where the cursor is right after "//" and where the user has already typed
1144 // some characters (e.g. "//Fo" completing to "// FooBar").
1145 if c.surrounding != nil {
1146 for _, cmt := range comment.List {
1147 if c.surrounding.start == cmt.Slash+2 {
1148 c.completionContext.commentNeedsLeadingSpace = true
1149 break
1150 }
1151 }
1152 }
1153
1154 // Using the next line pos, grab and parse the exported symbol on that line
1155 for _, n := range c.pgf.File.Decls {
1156 declLine := safetoken.Line(file, n.Pos())
1157 // if the comment is not in, directly above or on the same line as a declaration
1158 if declLine != commentLine && declLine != commentLine+1 &&
1159 !(n.Pos() <= comment.Pos() && comment.End() <= n.End()) {
1160 continue
1161 }
1162 switch node := n.(type) {
1163 // handle const, vars, and types
1164 case *ast.GenDecl:
1165 for _, spec := range node.Specs {
1166 switch spec := spec.(type) {
1167 case *ast.ValueSpec:
1168 for _, name := range spec.Names {
1169 if name.String() == "_" {
1170 continue
1171 }
1172 obj := c.pkg.TypesInfo().ObjectOf(name)
1173 c.deepState.enqueue(candidate{obj: obj, score: stdScore})
1174 }
1175 case *ast.TypeSpec:
1176 // add TypeSpec fields to completion
1177 switch typeNode := spec.Type.(type) {
1178 case *ast.StructType:
1179 c.addFieldItems(typeNode.Fields)
1180 case *ast.FuncType:
1181 c.addFieldItems(typeNode.Params)
1182 c.addFieldItems(typeNode.Results)
1183 case *ast.InterfaceType:
1184 c.addFieldItems(typeNode.Methods)
1185 }
1186
1187 if spec.Name.String() == "_" {
1188 continue
1189 }
1190
1191 obj := c.pkg.TypesInfo().ObjectOf(spec.Name)
1192 // Type name should get a higher score than fields but not highScore by default
1193 // since field near a comment cursor gets a highScore
1194 score := stdScore * 1.1
1195 // If type declaration is on the line after comment, give it a highScore.
1196 if declLine == commentLine+1 {
1197 score = highScore
1198 }
1199
1200 c.deepState.enqueue(candidate{obj: obj, score: score})
1201 }
1202 }
1203 // handle functions
1204 case *ast.FuncDecl:
1205 c.addFieldItems(node.Recv)
1206 c.addFieldItems(node.Type.Params)
1207 c.addFieldItems(node.Type.Results)
1208
1209 // collect receiver struct fields
1210 if node.Recv != nil {
1211 fn, ok := c.pkg.TypesInfo().Defs[node.Name].(*types.Func)
1212 if !ok {
1213 // A duplicate FuncDecl may lack a Defs entry.
1214 // Avoid panicking in this case; see go.dev/issue/71273.
1215 continue
1216 }
1217 sig := fn.Signature()
1218 recv := sig.Recv()
1219 if recv == nil {
1220 continue // may be nil if ill-typed
1221 }
1222 _, named := typesinternal.ReceiverNamed(recv)
1223 if named != nil {
1224 if recvStruct, ok := named.Underlying().(*types.Struct); ok {
1225 for field := range recvStruct.Fields() {
1226 c.deepState.enqueue(candidate{obj: field, score: lowScore})
1227 }
1228 }
1229 }
1230 }
1231
1232 if node.Name.String() == "_" {
1233 continue
1234 }
1235
1236 obj := c.pkg.TypesInfo().ObjectOf(node.Name)
1237 if obj == nil || obj.Pkg() != nil && obj.Pkg() != c.pkg.Types() {
1238 continue
1239 }
1240
1241 c.deepState.enqueue(candidate{obj: obj, score: highScore})
1242 }
1243 }
1244 }
1245
1246 // sets word boundaries surrounding a cursor for a comment
1247 func (c *completer) setSurroundingForComment(comments *ast.CommentGroup) {
1248 var cursorComment *ast.Comment
1249 for _, comment := range comments.List {
1250 if c.pos >= comment.Pos() && c.pos <= comment.End() {
1251 cursorComment = comment
1252 break
1253 }
1254 }
1255 // if cursor isn't in the comment
1256 if cursorComment == nil {
1257 return
1258 }
1259
1260 // index of cursor in comment text
1261 cursorOffset := int(c.pos - cursorComment.Pos())
1262 start, end := cursorOffset, cursorOffset
1263 for start > 0 && isValidIdentifierChar(cursorComment.Text[start-1]) {
1264 start--
1265 }
1266 for end < len(cursorComment.Text) && isValidIdentifierChar(cursorComment.Text[end]) {
1267 end++
1268 }
1269
1270 c.surrounding = &Selection{
1271 content: cursorComment.Text[start:end],
1272 cursor: c.pos,
1273 tokFile: c.pgf.Tok,
1274 start: token.Pos(int(cursorComment.Slash) + start),
1275 end: token.Pos(int(cursorComment.Slash) + end),
1276 mapper: c.mapper,
1277 }
1278 c.surrounding.check()
1279 c.setMatcherFromPrefix(c.surrounding.Prefix())
1280 }
1281
1282 // isValidIdentifierChar returns true if a byte is a valid go identifier
1283 // character, i.e. unicode letter or digit or underscore.
1284 func isValidIdentifierChar(char byte) bool {
1285 charRune := rune(char)
1286 return unicode.In(charRune, unicode.Letter, unicode.Digit) || char == '_'
1287 }
1288
1289 // adds struct fields, interface methods, function declaration fields to completion
1290 func (c *completer) addFieldItems(fields *ast.FieldList) {
1291 // TODO: in golang/go#72828, we get here with a nil surrounding.
1292 // This indicates a logic bug elsewhere: we should only be interrogating the
1293 // surrounding if it is set.
1294 if fields == nil || c.surrounding == nil {
1295 return
1296 }
1297
1298 cursor := c.surrounding.cursor
1299 for _, field := range fields.List {
1300 for _, name := range field.Names {
1301 if name.String() == "_" {
1302 continue
1303 }
1304 obj := c.pkg.TypesInfo().ObjectOf(name)
1305 if obj == nil {
1306 continue
1307 }
1308
1309 // if we're in a field comment/doc, score that field as more relevant
1310 score := stdScore
1311 if field.Comment != nil && field.Comment.Pos() <= cursor && cursor <= field.Comment.End() {
1312 score = highScore
1313 } else if field.Doc != nil && field.Doc.Pos() <= cursor && cursor <= field.Doc.End() {
1314 score = highScore
1315 }
1316
1317 c.deepState.enqueue(candidate{obj: obj, score: score})
1318 }
1319 }
1320 }
1321
1322 func wantStructFieldCompletions(enclosingCl *compLitInfo) bool {
1323 if enclosingCl == nil {
1324 return false
1325 }
1326 return is[*types.Struct](enclosingCl.clType) && (enclosingCl.inKey || enclosingCl.maybeInFieldName)
1327 }
1328
1329 func (c *completer) wantTypeName() bool {
1330 return !c.completionContext.commentCompletion && c.inference.typeName.wantTypeName
1331 }
1332
1333 // See https://golang.org/issue/36001. Unimported completions are expensive.
1334 const (
1335 maxUnimportedPackageNames = 5
1336 )
1337
1338 // selector finds completions for the specified selector expression.
1339 //
1340 // The caller should ensure that sel.X has type information,
1341 // even if sel is synthetic.
1342 func (c *completer) selector(ctx context.Context, sel *ast.SelectorExpr) error {
1343 c.inference.objChain = objChain(c.pkg.TypesInfo(), sel.X)
1344
1345 // True selector?
1346 if tv, ok := c.pkg.TypesInfo().Types[sel.X]; ok {
1347 c.methodsAndFields(tv.Type, tv.Addressable(), nil, c.deepState.enqueue)
1348 c.addPostfixSnippetCandidates(ctx, sel)
1349 return nil
1350 }
1351
1352 id, ok := sel.X.(*ast.Ident)
1353 if !ok {
1354 return nil
1355 }
1356
1357 // Treat sel as a qualified identifier.
1358 if pkgName, ok := c.pkg.TypesInfo().Uses[id].(*types.PkgName); ok {
1359 // Qualified identifier with import declaration.
1360 imp := pkgName.Imported()
1361
1362 // Known direct dependency? Expand using type information.
1363 if _, ok := c.pkg.Metadata().DepsByPkgPath[golang.PackagePath(imp.Path())]; ok {
1364 c.packageMembers(imp, stdScore, nil, c.deepState.enqueue)
1365 return nil
1366 }
1367
1368 }
1369
1370 // Search unimported packages.
1371 if !c.opts.unimported {
1372 return nil // feature disabled
1373 }
1374
1375 // -- completion of symbols in unimported packages --
1376
1377 // The user might have typed strings.TLower, so id.Name==strings, sel.Sel.Name == TLower,
1378 // but the cursor might be inside TLower, so adjust the prefix
1379 prefix := sel.Sel.Name
1380 if c.surrounding != nil {
1381 if c.surrounding.content != sel.Sel.Name {
1382 // the bug reports do not include the Reportf strings just the line numbers
1383 if len(c.surrounding.content) == 0 {
1384 bug.Reportf("surrounding is empty, should be %q", sel.Sel.Name)
1385 } else if len(sel.Sel.Name) == 0 {
1386 bug.Reportf("sel.Sel.Name is empty, should be %q", c.surrounding.content)
1387 } else {
1388 bug.Reportf("unexpected surrounding: %q != %q", c.surrounding.content, sel.Sel.Name)
1389 }
1390 } else {
1391 prefix = sel.Sel.Name[:c.surrounding.cursor-c.surrounding.start]
1392 }
1393 }
1394 c.unimported(ctx, metadata.PackageName(id.Name), prefix)
1395 return nil
1396
1397 }
1398
1399 // unimportedScore returns a score for an unimported package that is generally
1400 // lower than other candidates.
1401 func unimportedScore(relevance float64) float64 {
1402 return (stdScore + .1*relevance) / 2
1403 }
1404
1405 func (c *completer) packageMembers(pkg *types.Package, score float64, imp *importInfo, cb func(candidate)) {
1406 scope := pkg.Scope()
1407 for _, name := range scope.Names() {
1408 obj := scope.Lookup(name)
1409 if c.tooNew(obj) {
1410 continue // std symbol too new for file's Go version
1411 }
1412 cb(candidate{
1413 obj: obj,
1414 score: score,
1415 imp: imp,
1416 addressable: isVar(obj),
1417 })
1418 }
1419 }
1420
1421 // ignoreUnimportedCompletion reports whether an unimported completion
1422 // resulting in the given import should be ignored.
1423 func ignoreUnimportedCompletion(fix *imports.ImportFix) bool {
1424 // golang/go#60062: don't add unimported completion to golang.org/toolchain.
1425 return fix != nil && strings.HasPrefix(fix.StmtInfo.ImportPath, "golang.org/toolchain")
1426 }
1427
1428 func (c *completer) methodsAndFields(typ types.Type, addressable bool, imp *importInfo, cb func(candidate)) {
1429 if isStarTestingDotF(typ) {
1430 // is that a sufficient test? (or is more care needed?)
1431 if c.fuzz(typ, imp, cb) {
1432 return
1433 }
1434 }
1435
1436 mset := c.methodSetCache[methodSetKey{typ, addressable}]
1437 if mset == nil {
1438 if addressable && !types.IsInterface(typ) && !isPointer(typ) {
1439 // Add methods of *T, which includes methods with receiver T.
1440 mset = types.NewMethodSet(types.NewPointer(typ))
1441 } else {
1442 // Add methods of T.
1443 mset = types.NewMethodSet(typ)
1444 }
1445 c.methodSetCache[methodSetKey{typ, addressable}] = mset
1446 }
1447
1448 for method := range mset.Methods() {
1449 obj := method.Obj()
1450 // to the other side of the cb() queue?
1451 if c.tooNew(obj) {
1452 continue // std method too new for file's Go version
1453 }
1454 cb(candidate{
1455 obj: method.Obj(),
1456 score: stdScore,
1457 imp: imp,
1458 addressable: addressable || isPointer(typ),
1459 })
1460 }
1461
1462 // Add fields of T.
1463 eachField(typ, func(v *types.Var) {
1464 if c.tooNew(v) {
1465 return // std field too new for file's Go version
1466 }
1467 cb(candidate{
1468 obj: v,
1469 score: stdScore - 0.01,
1470 imp: imp,
1471 addressable: addressable || isPointer(typ),
1472 })
1473 })
1474 }
1475
1476 // isStarTestingDotF reports whether typ is *testing.F.
1477 func isStarTestingDotF(typ types.Type) bool {
1478 // No Unalias, since go test doesn't consider
1479 // types when enumeratinf test funcs, only syntax.
1480 ptr, _ := typ.(*types.Pointer)
1481 if ptr == nil {
1482 return false
1483 }
1484 named, _ := ptr.Elem().(*types.Named)
1485 if named == nil {
1486 return false
1487 }
1488 obj := named.Obj()
1489 // obj.Pkg is nil for the error type.
1490 return obj != nil && obj.Pkg() != nil && obj.Pkg().Path() == "testing" && obj.Name() == "F"
1491 }
1492
1493 // lexical finds completions in the lexical environment.
1494 func (c *completer) lexical(ctx context.Context) error {
1495 var (
1496 builtinIota = types.Universe.Lookup("iota")
1497 builtinNil = types.Universe.Lookup("nil")
1498
1499 // TODO(rfindley): only allow "comparable" where it is valid (in constraint
1500 // position or embedded in interface declarations).
1501 // builtinComparable = types.Universe.Lookup("comparable")
1502 )
1503
1504 // Track seen variables to avoid showing completions for shadowed variables.
1505 // This works since we look at scopes from innermost to outermost.
1506 seen := make(map[string]struct{})
1507
1508 // Process scopes innermost first.
1509 for i, scope := range c.scopes {
1510 if scope == nil {
1511 continue
1512 }
1513
1514 Names:
1515 for _, name := range scope.Names() {
1516 declScope, obj := scope.LookupParent(name, c.pos)
1517 if declScope != scope {
1518 continue // scope of name starts after c.pos
1519 }
1520
1521 // If obj's type is invalid, find the AST node that defines the lexical block
1522 // containing the declaration of obj. Don't resolve types for packages.
1523 if !isPkgName(obj) && !typeIsValid(obj.Type()) {
1524 // Match the scope to its ast.Node. If the scope is the package scope,
1525 // use the *ast.File as the starting node.
1526 var node ast.Node
1527 if i < len(c.path) {
1528 node = c.path[i]
1529 } else if i == len(c.path) { // use the *ast.File for package scope
1530 node = c.path[i-1]
1531 }
1532 if node != nil {
1533 if resolved := resolveInvalid(c.pkg.FileSet(), obj, node, c.pkg.TypesInfo()); resolved != nil {
1534 obj = resolved
1535 }
1536 }
1537 }
1538
1539 // Don't use LHS of decl in RHS.
1540 for _, ident := range enclosingDeclLHS(c.path) {
1541 if obj.Pos() == ident.Pos() {
1542 continue Names
1543 }
1544 }
1545
1546 // Don't suggest "iota" outside of const decls.
1547 if obj == builtinIota && !c.inConstDecl() {
1548 continue
1549 }
1550
1551 // Rank outer scopes lower than inner.
1552 score := stdScore * math.Pow(.99, float64(i))
1553
1554 // Dowrank "nil" a bit so it is ranked below more interesting candidates.
1555 if obj == builtinNil {
1556 score /= 2
1557 }
1558
1559 // If we haven't already added a candidate for an object with this name.
1560 if _, ok := seen[obj.Name()]; !ok {
1561 seen[obj.Name()] = struct{}{}
1562 c.deepState.enqueue(candidate{
1563 obj: obj,
1564 score: score,
1565 addressable: isVar(obj),
1566 })
1567 }
1568 }
1569 }
1570
1571 if c.inference.objType != nil {
1572 if named, ok := types.Unalias(typesinternal.Unpointer(c.inference.objType)).(*types.Named); ok {
1573 // If we expected a named type, check the type's package for
1574 // completion items. This is useful when the current file hasn't
1575 // imported the type's package yet.
1576
1577 if named.Obj() != nil && named.Obj().Pkg() != nil {
1578 pkg := named.Obj().Pkg()
1579
1580 // Make sure the package name isn't already in use by another
1581 // object, and that this file doesn't import the package yet.
1582 // TODO(adonovan): what if pkg.Path has vendor/ prefix?
1583 if _, ok := seen[pkg.Name()]; !ok && pkg != c.pkg.Types() && !alreadyImports(c.pgf.File, golang.ImportPath(pkg.Path())) {
1584 seen[pkg.Name()] = struct{}{}
1585 obj := types.NewPkgName(0, nil, pkg.Name(), pkg)
1586 imp := &importInfo{
1587 importPath: pkg.Path(),
1588 }
1589 if imports.ImportPathToAssumedName(pkg.Path()) != pkg.Name() {
1590 imp.name = pkg.Name()
1591 }
1592 c.deepState.enqueue(candidate{
1593 obj: obj,
1594 score: stdScore,
1595 imp: imp,
1596 })
1597 }
1598 }
1599 }
1600 }
1601
1602 if c.opts.unimported {
1603 if err := c.unimportedPackages(ctx, seen); err != nil {
1604 return err
1605 }
1606 }
1607
1608 if c.inference.typeName.isTypeParam {
1609 // If we are completing a type param, offer each structural type.
1610 // This ensures we suggest "[]int" and "[]float64" for a constraint
1611 // with type union "[]int | []float64".
1612 if t, ok := c.inference.objType.(*types.Interface); ok {
1613 if terms, err := typeparams.InterfaceTermSet(t); err == nil {
1614 for _, term := range terms {
1615 c.injectType(ctx, term.Type())
1616 }
1617 }
1618 }
1619 } else {
1620 c.injectType(ctx, c.inference.objType)
1621 }
1622
1623 // Add keyword completion items appropriate in the current context.
1624 c.addKeywordCompletions()
1625
1626 return nil
1627 }
1628
1629 // injectType manufactures candidates based on the given type. This is
1630 // intended for types not discoverable via lexical search, such as
1631 // composite and/or generic types. For example, if the type is "[]int",
1632 // this method makes sure you get candidates "[]int{}" and "[]int"
1633 // (the latter applies when completing a type name).
1634 func (c *completer) injectType(ctx context.Context, t types.Type) {
1635 if t == nil {
1636 return
1637 }
1638
1639 t = typesinternal.Unpointer(t)
1640
1641 // If we have an expected type and it is _not_ a named type, handle
1642 // it specially. Non-named types like "[]int" will never be
1643 // considered via a lexical search, so we need to directly inject
1644 // them. Also allow generic types since lexical search does not
1645 // infer instantiated versions of them.
1646 if pnt, ok := t.(typesinternal.NamedOrAlias); !ok || pnt.TypeParams().Len() > 0 {
1647 // If our expected type is "[]int", this will add a literal
1648 // candidate of "[]int{}".
1649 c.literal(ctx, t, nil)
1650
1651 if _, isBasic := t.(*types.Basic); !isBasic {
1652 // If we expect a non-basic type name (e.g. "[]int"), hack up
1653 // a named type whose name is literally "[]int". This allows
1654 // us to reuse our object based completion machinery.
1655 fakeNamedType := candidate{
1656 obj: types.NewTypeName(token.NoPos, nil, types.TypeString(t, c.qual), t),
1657 score: stdScore,
1658 }
1659 // Make sure the type name matches before considering
1660 // candidate. This cuts down on useless candidates.
1661 if c.matchingTypeName(&fakeNamedType) {
1662 c.deepState.enqueue(fakeNamedType)
1663 }
1664 }
1665 }
1666 }
1667
1668 func (c *completer) unimportedPackages(ctx context.Context, seen map[string]struct{}) error {
1669 var prefix string
1670 if c.surrounding != nil {
1671 prefix = c.surrounding.Prefix()
1672 }
1673
1674 // Don't suggest unimported packages if we have absolutely nothing
1675 // to go on.
1676 if prefix == "" {
1677 return nil
1678 }
1679
1680 count := 0
1681
1682 // Search the forward transitive closure of the workspace.
1683 all, err := c.snapshot.AllMetadata(ctx)
1684 if err != nil {
1685 return err
1686 }
1687 pkgNameByPath := make(map[golang.PackagePath]string)
1688 var paths []string // actually PackagePaths
1689 for _, mp := range all {
1690 if mp.ForTest != "" {
1691 continue // skip all test variants
1692 }
1693 if mp.Name == "main" {
1694 continue // main is non-importable
1695 }
1696 if !strings.HasPrefix(string(mp.Name), prefix) {
1697 continue // not a match
1698 }
1699 paths = append(paths, string(mp.PkgPath))
1700 pkgNameByPath[mp.PkgPath] = string(mp.Name)
1701 }
1702
1703 // Rank candidates using goimports' algorithm.
1704 var relevances map[string]float64
1705 if len(paths) != 0 {
1706 if err := c.snapshot.RunProcessEnvFunc(ctx, func(ctx context.Context, opts *imports.Options) error {
1707 var err error
1708 relevances, err = imports.ScoreImportPaths(ctx, opts.Env, paths)
1709 return err
1710 }); err != nil {
1711 return err
1712 }
1713 }
1714 sort.Slice(paths, func(i, j int) bool {
1715 if relevances[paths[i]] != relevances[paths[j]] {
1716 return relevances[paths[i]] > relevances[paths[j]]
1717 }
1718
1719 // Fall back to lexical sort to keep truncated set of candidates
1720 // in a consistent order.
1721 return paths[i] < paths[j]
1722 })
1723
1724 for _, path := range paths {
1725 name := pkgNameByPath[golang.PackagePath(path)]
1726 if _, ok := seen[name]; ok {
1727 continue
1728 }
1729 imp := &importInfo{
1730 importPath: path,
1731 }
1732 if imports.ImportPathToAssumedName(path) != name {
1733 imp.name = name
1734 }
1735 if count >= maxUnimportedPackageNames {
1736 return nil
1737 }
1738 c.deepState.enqueue(candidate{
1739 // Pass an empty *types.Package to disable deep completions.
1740 obj: types.NewPkgName(0, nil, name, types.NewPackage(path, name)),
1741 score: unimportedScore(relevances[path]),
1742 imp: imp,
1743 })
1744 count++
1745 }
1746
1747 var mu sync.Mutex
1748 add := func(pkg imports.ImportFix) {
1749 if ignoreUnimportedCompletion(&pkg) {
1750 return
1751 }
1752 mu.Lock()
1753 defer mu.Unlock()
1754 if _, ok := seen[pkg.IdentName]; ok {
1755 return
1756 }
1757 if _, ok := relevances[pkg.StmtInfo.ImportPath]; ok {
1758 return
1759 }
1760
1761 if count >= maxUnimportedPackageNames {
1762 return
1763 }
1764
1765 // Do not add the unimported packages to seen, since we can have
1766 // multiple packages of the same name as completion suggestions, since
1767 // only one will be chosen.
1768 obj := types.NewPkgName(0, nil, pkg.IdentName, types.NewPackage(pkg.StmtInfo.ImportPath, pkg.IdentName))
1769 c.deepState.enqueue(candidate{
1770 obj: obj,
1771 score: unimportedScore(pkg.Relevance),
1772 imp: &importInfo{
1773 importPath: pkg.StmtInfo.ImportPath,
1774 name: pkg.StmtInfo.Name,
1775 },
1776 })
1777 count++
1778 }
1779
1780 c.completionCallbacks = append(c.completionCallbacks, func(ctx context.Context, opts *imports.Options) error {
1781 if err := imports.GetAllCandidates(ctx, add, prefix, c.filename, c.pkg.Types().Name(), opts.Env); err != nil {
1782 return fmt.Errorf("getting completion candidates: %v", err)
1783 }
1784 return nil
1785 })
1786
1787 return nil
1788 }
1789
1790 // alreadyImports reports whether f has an import with the specified path.
1791 func alreadyImports(f *ast.File, path golang.ImportPath) bool {
1792 for _, s := range f.Imports {
1793 if metadata.UnquoteImportPath(s) == path {
1794 return true
1795 }
1796 }
1797 return false
1798 }
1799
1800 func (c *completer) inConstDecl() bool {
1801 for _, n := range c.path {
1802 if decl, ok := n.(*ast.GenDecl); ok && decl.Tok == token.CONST {
1803 return true
1804 }
1805 }
1806 return false
1807 }
1808
1809 // structLiteralFieldName finds completions for struct field names inside a struct literal.
1810 func (c *completer) structLiteralFieldName(ctx context.Context) error {
1811 clInfo := c.enclosingCompositeLiteral
1812
1813 if t, ok := clInfo.clType.Underlying().(*types.Struct); ok {
1814
1815 // Collect selection indices of all existing
1816 // fields specified by the struct literal.
1817 existing := make(map[types.Object][]int)
1818 for _, elt := range clInfo.cl.Elts {
1819 if kv, ok := elt.(*ast.KeyValueExpr); ok {
1820 if key, ok := kv.Key.(*ast.Ident); ok && clInfo.kv != kv {
1821 seln, ok := types.LookupSelection(clInfo.clType, true, c.pkg.Types(), key.Name)
1822 if ok {
1823 existing[seln.Obj()] = seln.Index()
1824 }
1825 }
1826 }
1827 }
1828
1829 // fields returns the sequence of candidate fields of struct type t.
1830 fields := func(t *types.Struct) iter.Seq[*types.Var] {
1831 // go1.27 permits promoted fields in struct literals.
1832 deep := versions.AtLeast(c.goversion, versions.Go1_27)
1833
1834 return func(yield func(*types.Var) bool) {
1835 var collect func(t *types.Struct) bool
1836 collect = func(t *types.Struct) bool {
1837 for f := range t.Fields() {
1838 if !yield(f) {
1839 return false
1840 }
1841 if deep && f.Anonymous() {
1842 if inner, ok := f.Type().Underlying().(*types.Struct); ok && !collect(inner) {
1843 return false
1844 }
1845 }
1846 }
1847 return true
1848 }
1849 collect(t)
1850 }
1851 }
1852
1853 // conflict reports whether one field index
1854 // sequence is a prefix (ancestor) of the other.
1855 conflict := func(a, b []int) bool {
1856 for i := range min(len(a), len(b)) {
1857 if a[i] != b[i] {
1858 return false
1859 }
1860 }
1861 return true
1862 }
1863
1864 fieldloop:
1865 for f := range fields(t) {
1866 seln, ok := types.LookupSelection(clInfo.clType, true, c.pkg.Types(), f.Name())
1867 if !ok || seln.Obj() != f {
1868 continue // candidate's name is shadowed or ambiguous here
1869 }
1870
1871 // Reject candidates that conflict with existing fields.
1872 for _, indices := range existing {
1873 if conflict(seln.Index(), indices) {
1874 continue fieldloop
1875 }
1876 }
1877
1878 const deltaScore = 0.0001
1879 const depthPenalty = 0.01
1880 depth := len(seln.Index())
1881 fieldIdx := seln.Index()[depth-1]
1882 c.deepState.enqueue(candidate{
1883 obj: seln.Obj(),
1884 score: highScore - float64(depth-1)*depthPenalty - float64(fieldIdx)*deltaScore,
1885 })
1886 }
1887
1888 // Fall through and add lexical completions if we aren't
1889 // certain we are in the key part of a key-value pair.
1890 if !clInfo.maybeInFieldName {
1891 return nil
1892 }
1893 }
1894
1895 return c.lexical(ctx)
1896 }
1897
1898 // enclosingCompositeLiteral returns information about the composite literal enclosing the
1899 // position.
1900 // It returns nil on failure; for example, if there is no type information for a
1901 // node on path.
1902 func enclosingCompositeLiteral(path []ast.Node, pos token.Pos, info *types.Info) *compLitInfo {
1903 for _, n := range path {
1904 switch n := n.(type) {
1905 case *ast.CompositeLit:
1906 // The enclosing node will be a composite literal if the user has just
1907 // opened the curly brace (e.g. &x{<>) or the completion request is triggered
1908 // from an already completed composite literal expression (e.g. &x{foo: 1, <>})
1909 //
1910 // The position is not part of the composite literal unless it falls within the
1911 // curly braces (e.g. "foo.Foo<>Struct{}").
1912 if !(n.Lbrace < pos && pos <= n.Rbrace) {
1913 // Keep searching since we may yet be inside a composite literal.
1914 // For example "Foo{B: Ba<>{}}".
1915 break
1916 }
1917
1918 tv, ok := info.Types[n]
1919 if !ok {
1920 return nil
1921 }
1922
1923 clInfo := compLitInfo{
1924 cl: n,
1925 clType: typesinternal.Unpointer(tv.Type).Underlying(),
1926 }
1927
1928 var (
1929 expr ast.Expr
1930 hasKeys bool
1931 )
1932 for _, el := range n.Elts {
1933 // Remember the expression that the position falls in, if any.
1934 if el.Pos() <= pos && pos <= el.End() {
1935 expr = el
1936 }
1937
1938 if kv, ok := el.(*ast.KeyValueExpr); ok {
1939 hasKeys = true
1940 // If expr == el then we know the position falls in this expression,
1941 // so also record kv as the enclosing *ast.KeyValueExpr.
1942 if expr == el {
1943 clInfo.kv = kv
1944 break
1945 }
1946 }
1947 }
1948
1949 if clInfo.kv != nil {
1950 // If in a *ast.KeyValueExpr, we know we are in the key if the position
1951 // is to the left of the colon (e.g. "Foo{F<>: V}".
1952 clInfo.inKey = pos <= clInfo.kv.Colon
1953 } else if hasKeys {
1954 // If we aren't in a *ast.KeyValueExpr but the composite literal has
1955 // other *ast.KeyValueExprs, we must be on the key side of a new
1956 // *ast.KeyValueExpr (e.g. "Foo{F: V, <>}").
1957 clInfo.inKey = true
1958 } else {
1959 switch clInfo.clType.(type) {
1960 case *types.Struct:
1961 if len(n.Elts) == 0 {
1962 // If the struct literal is empty, next could be a struct field
1963 // name or an expression (e.g. "Foo{<>}" could become "Foo{F:}"
1964 // or "Foo{someVar}").
1965 clInfo.maybeInFieldName = true
1966 } else if len(n.Elts) == 1 {
1967 // If there is one expression and the position is in that expression
1968 // and the expression is an identifier, we may be writing a field
1969 // name or an expression (e.g. "Foo{F<>}").
1970 _, clInfo.maybeInFieldName = expr.(*ast.Ident)
1971 }
1972 case *types.Map:
1973 // If we aren't in a *ast.KeyValueExpr we must be adding a new key
1974 // to the map.
1975 clInfo.inKey = true
1976 }
1977 }
1978
1979 return &clInfo
1980 default:
1981 if breaksExpectedTypeInference(n, pos) {
1982 return nil
1983 }
1984 }
1985 }
1986
1987 return nil
1988 }
1989
1990 // enclosingFunction returns the signature and body of the function
1991 // enclosing the given position.
1992 func enclosingFunction(path []ast.Node, info *types.Info) *funcInfo {
1993 for _, node := range path {
1994 switch t := node.(type) {
1995 case *ast.FuncDecl:
1996 if obj, ok := info.Defs[t.Name]; ok {
1997 return &funcInfo{
1998 sig: obj.Type().(*types.Signature),
1999 body: t.Body,
2000 }
2001 }
2002 case *ast.FuncLit:
2003 if typ, ok := info.Types[t]; ok {
2004 if sig, _ := typ.Type.(*types.Signature); sig == nil {
2005 // golang/go#49397: it should not be possible, but we somehow arrived
2006 // here with a non-signature type, most likely due to AST mangling
2007 // such that node.Type is not a FuncType.
2008 return nil
2009 }
2010 return &funcInfo{
2011 sig: typ.Type.(*types.Signature),
2012 body: t.Body,
2013 }
2014 }
2015 }
2016 }
2017 return nil
2018 }
2019
2020 func expectedCompositeLiteralType(clInfo *compLitInfo, pos token.Pos) types.Type {
2021 switch t := clInfo.clType.(type) {
2022 case *types.Slice:
2023 if clInfo.inKey {
2024 return types.Typ[types.UntypedInt]
2025 }
2026 return t.Elem()
2027 case *types.Array:
2028 if clInfo.inKey {
2029 return types.Typ[types.UntypedInt]
2030 }
2031 return t.Elem()
2032 case *types.Map:
2033 if clInfo.inKey {
2034 return t.Key()
2035 }
2036 return t.Elem()
2037 case *types.Struct:
2038 // If we are completing a key (i.e. field name), there is no expected type.
2039 if clInfo.inKey {
2040 return nil
2041 }
2042
2043 // If we are in a key-value pair, but not in the key, then we must be on the
2044 // value side. The expected type of the value will be determined from the key.
2045 if clInfo.kv != nil {
2046 if key, ok := clInfo.kv.Key.(*ast.Ident); ok {
2047 for field := range t.Fields() {
2048 if field.Name() == key.Name {
2049 return field.Type()
2050 }
2051 }
2052 }
2053 } else {
2054 // If we aren't in a key-value pair and aren't in the key, we must be using
2055 // implicit field names.
2056
2057 // The order of the literal fields must match the order in the struct definition.
2058 // Find the element that the position belongs to and suggest that field's type.
2059 if i := exprAtPos(pos, clInfo.cl.Elts); i < t.NumFields() {
2060 return t.Field(i).Type()
2061 }
2062 }
2063 }
2064 return nil
2065 }
2066
2067 // typeMod represents an operator that changes the expected type.
2068 type typeMod struct {
2069 mod typeModKind
2070 arrayLen int64
2071 }
2072
2073 type typeModKind int
2074
2075 const (
2076 dereference typeModKind = iota // pointer indirection: "*"
2077 reference // adds level of pointer: "&" for values, "*" for type names
2078 chanRead // channel read operator: "<-"
2079 sliceType // make a slice type: "[]" in "[]int"
2080 arrayType // make an array type: "[2]" in "[2]int"
2081 invoke // make a function call: "()" in "foo()"
2082 takeSlice // take slice of array: "[:]" in "foo[:]"
2083 takeDotDotDot // turn slice into variadic args: "..." in "foo..."
2084 index // index into slice/array: "[0]" in "foo[0]"
2085 )
2086
2087 type objKind int
2088
2089 const (
2090 kindAny objKind = 0
2091 kindArray objKind = 1 << iota
2092 kindSlice
2093 kindChan
2094 kindMap
2095 kindStruct
2096 kindString
2097 kindInt
2098 kindBool
2099 kindBytes
2100 kindPtr
2101 kindInterface
2102 kindFloat
2103 kindComplex
2104 kindError
2105 kindStringer
2106 kindFunc
2107 kindRange0Func
2108 kindRange1Func
2109 kindRange2Func
2110 )
2111
2112 // penalizedObj represents an object that should be disfavored as a
2113 // completion candidate.
2114 type penalizedObj struct {
2115 // objChain is the full "chain", e.g. "foo.bar().baz" becomes
2116 // []types.Object{foo, bar, baz}.
2117 objChain []types.Object
2118 // penalty is score penalty in the range (0, 1).
2119 penalty float64
2120 }
2121
2122 // candidateInference holds information we have inferred about a type that can be
2123 // used at the current position.
2124 type candidateInference struct {
2125 // objType is the desired type of an object used at the query position.
2126 objType types.Type
2127
2128 // objKind is a mask of expected kinds of types such as "map", "slice", etc.
2129 objKind objKind
2130
2131 // variadic is true if we are completing the initial variadic
2132 // parameter. For example:
2133 // append([]T{}, <>) // objType=T variadic=true
2134 // append([]T{}, T{}, <>) // objType=T variadic=false
2135 variadic bool
2136
2137 // modifiers are prefixes such as "*", "&" or "<-" that influence how
2138 // a candidate type relates to the expected type.
2139 modifiers []typeMod
2140
2141 // convertibleTo is a type our candidate type must be convertible to.
2142 convertibleTo types.Type
2143
2144 // needsExactType is true if the candidate type must be exactly the type of
2145 // the objType, e.g. an interface rather than its implementors.
2146 //
2147 // This is necessary when objType is derived using reverse type inference:
2148 // any different (but assignable) type may lead to different type inference,
2149 // which may no longer be valid.
2150 //
2151 // For example, consider the following scenario:
2152 //
2153 // func f[T any](x T) []T { return []T{x} }
2154 //
2155 // var s []any = f(_)
2156 //
2157 // Reverse type inference would infer that the type at _ must be 'any', but
2158 // that does not mean that any object in the lexical scope is valid: the type of
2159 // the object must be *exactly* any, otherwise type inference will cause the
2160 // slice assignment to fail.
2161 needsExactType bool
2162
2163 // typeName holds information about the expected type name at
2164 // position, if any.
2165 typeName typeNameInference
2166
2167 // assignees are the types that would receive a function call's
2168 // results at the position. For example:
2169 //
2170 // foo := 123
2171 // foo, bar := <>
2172 //
2173 // at "<>", the assignees are [int, <invalid>].
2174 assignees []types.Type
2175
2176 // variadicAssignees is true if we could be completing an inner
2177 // function call that fills out an outer function call's variadic
2178 // params. For example:
2179 //
2180 // func foo(int, ...string) {}
2181 //
2182 // foo(<>) // variadicAssignees=true
2183 // foo(bar<>) // variadicAssignees=true
2184 // foo(bar, baz<>) // variadicAssignees=false
2185 variadicAssignees bool
2186
2187 // penalized holds expressions that should be disfavored as
2188 // candidates. For example, it tracks expressions already used in a
2189 // switch statement's other cases. Each expression is tracked using
2190 // its entire object "chain" allowing differentiation between
2191 // "a.foo" and "b.foo" when "a" and "b" are the same type.
2192 penalized []penalizedObj
2193
2194 // objChain contains the chain of objects representing the
2195 // surrounding *ast.SelectorExpr. For example, if we are completing
2196 // "foo.bar.ba<>", objChain will contain []types.Object{foo, bar}.
2197 objChain []types.Object
2198 }
2199
2200 // typeNameInference holds information about the expected type name at
2201 // position.
2202 type typeNameInference struct {
2203 // wantTypeName is true if we expect the name of a type.
2204 wantTypeName bool
2205
2206 // modifiers are prefixes such as "*", "&" or "<-" that influence how
2207 // a candidate type relates to the expected type.
2208 modifiers []typeMod
2209
2210 // assertableFrom is a type that must be assertable to our candidate type.
2211 assertableFrom types.Type
2212
2213 // wantComparable is true if we want a comparable type.
2214 wantComparable bool
2215
2216 // seenTypeSwitchCases tracks types that have already been used by
2217 // the containing type switch.
2218 seenTypeSwitchCases []types.Type
2219
2220 // compLitType is true if we are completing a composite literal type
2221 // name, e.g "foo<>{}".
2222 compLitType bool
2223
2224 // isTypeParam is true if we are completing a type instantiation parameter
2225 isTypeParam bool
2226 }
2227
2228 // expectedCandidate returns information about the expected candidate
2229 // for an expression at the query position.
2230 func expectedCandidate(ctx context.Context, c *completer) (inf candidateInference) {
2231 inf.typeName = expectTypeName(c)
2232
2233 if c.enclosingCompositeLiteral != nil {
2234 inf.objType = expectedCompositeLiteralType(c.enclosingCompositeLiteral, c.pos)
2235 }
2236
2237 Nodes:
2238 for i, node := range c.path {
2239 switch node := node.(type) {
2240 case *ast.BinaryExpr:
2241 // Determine if query position comes from left or right of op.
2242 e := node.X
2243 if c.pos < node.OpPos {
2244 e = node.Y
2245 }
2246 if tv, ok := c.pkg.TypesInfo().Types[e]; ok {
2247 switch node.Op {
2248 case token.LAND, token.LOR:
2249 // Don't infer "bool" type for "&&" or "||". Often you want
2250 // to compose a boolean expression from non-boolean
2251 // candidates.
2252 default:
2253 inf.objType = tv.Type
2254 }
2255 break Nodes
2256 }
2257 case *ast.AssignStmt:
2258 objType, assignees := expectedAssignStmtTypes(c.pkg, node, c.pos)
2259 inf.objType = objType
2260 inf.assignees = assignees
2261 return inf
2262 case *ast.ValueSpec:
2263 inf.objType = expectedValueSpecType(c.pkg, node, c.pos)
2264 return
2265 case *ast.ReturnStmt:
2266 if c.enclosingFunc != nil {
2267 inf.objType = expectedReturnStmtType(c.enclosingFunc.sig, node, c.pos)
2268 }
2269 return inf
2270 case *ast.SendStmt:
2271 if typ := expectedSendStmtType(c.pkg, node, c.pos); typ != nil {
2272 inf.objType = typ
2273 }
2274 return inf
2275 case *ast.CallExpr:
2276 // Only consider CallExpr args if position falls between parens.
2277 if node.Lparen < c.pos && c.pos <= node.Rparen {
2278 // For type conversions like "int64(foo)" we can only infer our
2279 // desired type is convertible to int64.
2280 if typ := typeConversion(node, c.pkg.TypesInfo()); typ != nil {
2281 inf.convertibleTo = typ
2282 break Nodes
2283 }
2284
2285 if sig, ok := c.pkg.TypesInfo().Types[node.Fun].Type.(*types.Signature); ok {
2286 // Out of bounds arguments get no inference completion.
2287 if !sig.Variadic() && exprAtPos(c.pos, node.Args) >= sig.Params().Len() {
2288 return inf
2289 }
2290
2291 // Inference is necessary only when function results are generic.
2292 var free typeparams.Free
2293 if free.Has(sig.Results()) {
2294 targs := c.getTypeArgs(node)
2295 res := inferExpectedResultTypes(c, i)
2296 substs := reverseInferTypeArgs(sig, targs, res)
2297 inst := instantiate(sig, substs)
2298 if inst != nil {
2299 // TODO(jacobz): If partial signature instantiation becomes possible,
2300 // make needsExactType only true if necessary.
2301 // Currently, ambiguous cases always resolve to a conversion expression
2302 // wrapping the completion, which is occasionally superfluous.
2303 inf.needsExactType = true
2304 sig = inst
2305 }
2306 }
2307
2308 inf = c.expectedCallParamType(inf, node, sig)
2309 }
2310
2311 if funIdent, ok := node.Fun.(*ast.Ident); ok {
2312 obj := c.pkg.TypesInfo().ObjectOf(funIdent)
2313
2314 if obj != nil && obj.Parent() == types.Universe {
2315 // Defer call to builtinArgType so we can provide it the
2316 // inferred type from its parent node.
2317 defer func() {
2318 inf = c.builtinArgType(obj, node, inf)
2319 inf.objKind = c.builtinArgKind(ctx, obj, node)
2320 }()
2321
2322 // The expected type of builtin arguments like append() is
2323 // the expected type of the builtin call itself. For
2324 // example:
2325 //
2326 // var foo []int = append(<>)
2327 //
2328 // To find the expected type at <> we "skip" the append()
2329 // node and get the expected type one level up, which is
2330 // []int.
2331 continue Nodes
2332 }
2333 }
2334
2335 return inf
2336 }
2337 case *ast.CaseClause:
2338 if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, node).(*ast.SwitchStmt); ok {
2339 if tv, ok := c.pkg.TypesInfo().Types[swtch.Tag]; ok {
2340 inf.objType = tv.Type
2341
2342 // Record which objects have already been used in the case
2343 // statements so we don't suggest them again.
2344 for _, cc := range swtch.Body.List {
2345 for _, caseExpr := range cc.(*ast.CaseClause).List {
2346 // Don't record the expression we are currently completing.
2347 if caseExpr.Pos() < c.pos && c.pos <= caseExpr.End() {
2348 continue
2349 }
2350
2351 if objs := objChain(c.pkg.TypesInfo(), caseExpr); len(objs) > 0 {
2352 inf.penalized = append(inf.penalized, penalizedObj{objChain: objs, penalty: 0.1})
2353 }
2354 }
2355 }
2356 }
2357 }
2358 return inf
2359 case *ast.SliceExpr:
2360 // Make sure position falls within the brackets (e.g. "foo[a:<>]").
2361 if node.Lbrack < c.pos && c.pos <= node.Rbrack {
2362 inf.objType = types.Typ[types.UntypedInt]
2363 }
2364 return inf
2365 case *ast.IndexExpr:
2366 // Make sure position falls within the brackets (e.g. "foo[<>]").
2367 if node.Lbrack < c.pos && c.pos <= node.Rbrack {
2368 if tv, ok := c.pkg.TypesInfo().Types[node.X]; ok {
2369 switch t := tv.Type.Underlying().(type) {
2370 case *types.Map:
2371 inf.objType = t.Key()
2372 case *types.Slice, *types.Array:
2373 inf.objType = types.Typ[types.UntypedInt]
2374 }
2375
2376 if ct := expectedConstraint(tv.Type, 0); ct != nil {
2377 inf.objType = ct
2378 inf.typeName.wantTypeName = true
2379 inf.typeName.isTypeParam = true
2380 if typ := c.inferExpectedTypeArg(i+1, 0); typ != nil {
2381 inf.objType = typ
2382 }
2383 }
2384 }
2385 }
2386 return inf
2387 case *ast.IndexListExpr:
2388 if node.Lbrack < c.pos && c.pos <= node.Rbrack {
2389 if tv, ok := c.pkg.TypesInfo().Types[node.X]; ok {
2390 typeParamIdx := exprAtPos(c.pos, node.Indices)
2391 if ct := expectedConstraint(tv.Type, typeParamIdx); ct != nil {
2392 inf.objType = ct
2393 inf.typeName.wantTypeName = true
2394 inf.typeName.isTypeParam = true
2395 if typ := c.inferExpectedTypeArg(i+1, typeParamIdx); typ != nil {
2396 inf.objType = typ
2397 }
2398 }
2399 }
2400 }
2401 return inf
2402 case *ast.RangeStmt:
2403 if astutil.NodeContainsPos(node.X, c.pos) {
2404 inf.objKind |= kindSlice | kindArray | kindMap | kindString
2405 if node.Key == nil && node.Value == nil {
2406 inf.objKind |= kindRange0Func | kindRange1Func | kindRange2Func
2407 } else if node.Value == nil {
2408 inf.objKind |= kindChan | kindRange1Func | kindRange2Func
2409 } else {
2410 inf.objKind |= kindRange2Func
2411 }
2412 }
2413 return inf
2414 case *ast.StarExpr:
2415 inf.modifiers = append(inf.modifiers, typeMod{mod: dereference})
2416 case *ast.UnaryExpr:
2417 switch node.Op {
2418 case token.AND:
2419 inf.modifiers = append(inf.modifiers, typeMod{mod: reference})
2420 case token.ARROW:
2421 inf.modifiers = append(inf.modifiers, typeMod{mod: chanRead})
2422 }
2423 case *ast.DeferStmt, *ast.GoStmt:
2424 inf.objKind |= kindFunc
2425 return inf
2426 default:
2427 if breaksExpectedTypeInference(node, c.pos) {
2428 return inf
2429 }
2430 }
2431 }
2432
2433 return inf
2434 }
2435
2436 // inferExpectedResultTypes takes the index of a call expression within the completion
2437 // path and uses its surroundings to infer the expected result tuple of the call's signature.
2438 // Returns the signature result tuple as a slice, or nil if reverse type inference fails.
2439 //
2440 // # For example
2441 //
2442 // func generic[T any, U any](a T, b U) (T, U) { ... }
2443 //
2444 // var x TypeA
2445 // var y TypeB
2446 // x, y := generic(<cursor>, <cursor>)
2447 //
2448 // inferExpectedResultTypes can determine that the expected result type of the function is (TypeA, TypeB)
2449 func inferExpectedResultTypes(c *completer, callNodeIdx int) []types.Type {
2450 callNode, ok := c.path[callNodeIdx].(*ast.CallExpr)
2451 if !ok {
2452 bug.Reportf("inferExpectedResultTypes given callNodeIndex: %v which is not a ast.CallExpr\n", callNodeIdx)
2453 return nil
2454 }
2455
2456 if len(c.path) <= callNodeIdx+1 {
2457 return nil
2458 }
2459
2460 var expectedResults []types.Type
2461
2462 // Check the parents of the call node to extract the expected result types of the call signature.
2463 // Currently reverse inferences are only supported with the following parent expressions,
2464 // however this list isn't exhaustive.
2465 switch node := c.path[callNodeIdx+1].(type) {
2466 case *ast.KeyValueExpr:
2467 enclosingCompositeLiteral := enclosingCompositeLiteral(c.path[callNodeIdx:], callNode.Pos(), c.pkg.TypesInfo())
2468 if enclosingCompositeLiteral != nil && !wantStructFieldCompletions(enclosingCompositeLiteral) {
2469 expectedResults = append(expectedResults, expectedCompositeLiteralType(enclosingCompositeLiteral, callNode.Pos()))
2470 }
2471 case *ast.AssignStmt:
2472 objType, assignees := expectedAssignStmtTypes(c.pkg, node, c.pos)
2473 if len(assignees) > 0 {
2474 return assignees
2475 } else if objType != nil {
2476 expectedResults = append(expectedResults, objType)
2477 }
2478 case *ast.ValueSpec:
2479 if resultType := expectedValueSpecType(c.pkg, node, c.pos); resultType != nil {
2480 expectedResults = append(expectedResults, resultType)
2481 }
2482 case *ast.SendStmt:
2483 if resultType := expectedSendStmtType(c.pkg, node, c.pos); resultType != nil {
2484 expectedResults = append(expectedResults, resultType)
2485 }
2486 case *ast.ReturnStmt:
2487 if c.enclosingFunc == nil {
2488 return nil
2489 }
2490
2491 // As a special case for reverse call inference in
2492 //
2493 // return foo(<cursor>)
2494 //
2495 // Pull the result type from the enclosing function
2496 if exprAtPos(c.pos, node.Results) == 0 {
2497 if callSig := c.pkg.TypesInfo().Types[callNode.Fun].Type.(*types.Signature); callSig != nil {
2498 enclosingResults := c.enclosingFunc.sig.Results()
2499 if callSig.Results().Len() == enclosingResults.Len() {
2500 expectedResults = make([]types.Type, enclosingResults.Len())
2501 for i := range enclosingResults.Len() {
2502 expectedResults[i] = enclosingResults.At(i).Type()
2503 }
2504 return expectedResults
2505 }
2506 }
2507 }
2508
2509 if resultType := expectedReturnStmtType(c.enclosingFunc.sig, node, c.pos); resultType != nil {
2510 expectedResults = append(expectedResults, resultType)
2511 }
2512 case *ast.CallExpr:
2513 // TODO(jacobz): This is a difficult case because the normal CallExpr candidateInference
2514 // leans on control flow which is inaccessible in this helper function.
2515 // It would probably take a significant refactor to a recursive solution to make this case
2516 // work cleanly. For now it's unimplemented.
2517 }
2518 return expectedResults
2519 }
2520
2521 // expectedSendStmtType return the expected type at the position.
2522 // Returns nil if unknown.
2523 func expectedSendStmtType(pkg *cache.Package, node *ast.SendStmt, pos token.Pos) types.Type {
2524 // Make sure we are on right side of arrow (e.g. "foo <- <>").
2525 if pos > node.Arrow+1 {
2526 if tv, ok := pkg.TypesInfo().Types[node.Chan]; ok {
2527 if ch, ok := tv.Type.Underlying().(*types.Chan); ok {
2528 return ch.Elem()
2529 }
2530 }
2531 }
2532 return nil
2533 }
2534
2535 // expectedValueSpecType returns the expected type of a ValueSpec at the query
2536 // position.
2537 func expectedValueSpecType(pkg *cache.Package, node *ast.ValueSpec, pos token.Pos) types.Type {
2538 if node.Type != nil && pos > node.Type.End() {
2539 return pkg.TypesInfo().TypeOf(node.Type)
2540 }
2541 return nil
2542 }
2543
2544 // expectedAssignStmtTypes analyzes the provided assignStmt, and checks
2545 // to see if the provided pos is within a RHS expression. If so, it report
2546 // the expected type of that expression, and the LHS type(s) to which it
2547 // is being assigned.
2548 func expectedAssignStmtTypes(pkg *cache.Package, node *ast.AssignStmt, pos token.Pos) (objType types.Type, assignees []types.Type) {
2549 // Only rank completions if you are on the right side of the token.
2550 if pos > node.TokPos {
2551 i := exprAtPos(pos, node.Rhs)
2552 if i >= len(node.Lhs) {
2553 i = len(node.Lhs) - 1
2554 }
2555 if tv, ok := pkg.TypesInfo().Types[node.Lhs[i]]; ok {
2556 objType = tv.Type
2557 }
2558
2559 // If we have a single expression on the RHS, record the LHS
2560 // assignees so we can favor multi-return function calls with
2561 // matching result values.
2562 if len(node.Rhs) <= 1 {
2563 for _, lhs := range node.Lhs {
2564 assignees = append(assignees, pkg.TypesInfo().TypeOf(lhs))
2565 }
2566 } else {
2567 // Otherwise, record our single assignee, even if its type is
2568 // not available. We use this info to downrank functions
2569 // with the wrong number of result values.
2570 assignees = append(assignees, pkg.TypesInfo().TypeOf(node.Lhs[i]))
2571 }
2572 }
2573 return objType, assignees
2574 }
2575
2576 // expectedReturnStmtType returns the expected type of a return statement.
2577 // Returns nil if enclosingSig is nil.
2578 func expectedReturnStmtType(enclosingSig *types.Signature, node *ast.ReturnStmt, pos token.Pos) types.Type {
2579 if enclosingSig != nil {
2580 if resultIdx := exprAtPos(pos, node.Results); resultIdx < enclosingSig.Results().Len() {
2581 return enclosingSig.Results().At(resultIdx).Type()
2582 }
2583 }
2584 return nil
2585 }
2586
2587 // Returns the number of type arguments in a callExpr
2588 func (c *completer) getTypeArgs(callExpr *ast.CallExpr) []types.Type {
2589 var targs []types.Type
2590 switch fun := callExpr.Fun.(type) {
2591 case *ast.IndexListExpr:
2592 for i := range fun.Indices {
2593 if typ, ok := c.pkg.TypesInfo().Types[fun.Indices[i]]; ok && typeIsValid(typ.Type) {
2594 targs = append(targs, typ.Type)
2595 }
2596 }
2597 case *ast.IndexExpr:
2598 if typ, ok := c.pkg.TypesInfo().Types[fun.Index]; ok && typeIsValid(typ.Type) {
2599 targs = []types.Type{typ.Type}
2600 }
2601 }
2602 return targs
2603 }
2604
2605 // reverseInferTypeArgs takes a generic signature, a list of passed type arguments, and the expected concrete return types
2606 // inferred from the signature's call site. If possible, it returns a list of types that could be used as the type arguments
2607 // to the signature. If not possible, it returns nil.
2608 //
2609 // Does not panic if any of the arguments are nil.
2610 func reverseInferTypeArgs(sig *types.Signature, typeArgs []types.Type, expectedResults []types.Type) []types.Type {
2611 if len(expectedResults) == 0 || sig == nil || sig.TypeParams().Len() == 0 || sig.Results().Len() != len(expectedResults) {
2612 return nil
2613 }
2614
2615 tparams := make([]*types.TypeParam, sig.TypeParams().Len())
2616 for i := range sig.TypeParams().Len() {
2617 tparams[i] = sig.TypeParams().At(i)
2618 }
2619
2620 for i := len(typeArgs); i < sig.TypeParams().Len(); i++ {
2621 typeArgs = append(typeArgs, nil)
2622 }
2623
2624 u := newUnifier(tparams, typeArgs)
2625 for i, assignee := range expectedResults {
2626 // Unify does not check the constraints of the type parameters.
2627 // Checks must be applied after.
2628 if !u.unify(sig.Results().At(i).Type(), assignee, unifyModeExact) {
2629 return nil
2630 }
2631 }
2632
2633 substs := make([]types.Type, sig.TypeParams().Len())
2634 for i := range sig.TypeParams().Len() {
2635 if sub := u.handles[sig.TypeParams().At(i)]; sub != nil && *sub != nil {
2636 // Ensure the inferred subst is assignable to the type parameter's constraint.
2637 if !assignableTo(*sub, sig.TypeParams().At(i).Constraint()) {
2638 return nil
2639 }
2640 substs[i] = *sub
2641 }
2642 }
2643 return substs
2644 }
2645
2646 // inferExpectedTypeArg gives a type param candidateInference based on the surroundings of its call site.
2647 // If successful, the inf parameter is returned with only it's objType field updated.
2648 //
2649 // callNodeIdx is the index within the completion path of the type parameter's parent call expression.
2650 // typeParamIdx is the index of the type parameter at the completion pos.
2651 func (c *completer) inferExpectedTypeArg(callNodeIdx int, typeParamIdx int) types.Type {
2652 if len(c.path) <= callNodeIdx {
2653 return nil
2654 }
2655
2656 callNode, ok := c.path[callNodeIdx].(*ast.CallExpr)
2657 if !ok {
2658 return nil
2659 }
2660 sig, ok := c.pkg.TypesInfo().Types[callNode.Fun].Type.(*types.Signature)
2661 if !ok {
2662 return nil
2663 }
2664
2665 // Infer the type parameters in a function call based on context
2666 expectedResults := inferExpectedResultTypes(c, callNodeIdx)
2667 if typeParamIdx < 0 || typeParamIdx >= sig.TypeParams().Len() {
2668 return nil
2669 }
2670 substs := reverseInferTypeArgs(sig, nil, expectedResults)
2671 if substs == nil || substs[typeParamIdx] == nil {
2672 return nil
2673 }
2674
2675 return substs[typeParamIdx]
2676 }
2677
2678 // Instantiates a signature with a set of type parameters.
2679 // Wrapper around types.Instantiate but bad arguments won't cause a panic.
2680 func instantiate(sig *types.Signature, substs []types.Type) *types.Signature {
2681 if substs == nil || sig == nil || len(substs) != sig.TypeParams().Len() {
2682 return nil
2683 }
2684
2685 for i := range substs {
2686 if substs[i] == nil {
2687 substs[i] = sig.TypeParams().At(i)
2688 }
2689 }
2690
2691 if inst, err := types.Instantiate(nil, sig, substs, true); err == nil {
2692 if inst, ok := inst.(*types.Signature); ok {
2693 return inst
2694 }
2695 }
2696
2697 return nil
2698 }
2699
2700 func (c *completer) expectedCallParamType(inf candidateInference, node *ast.CallExpr, sig *types.Signature) candidateInference {
2701 numParams := sig.Params().Len()
2702 if numParams == 0 {
2703 return inf
2704 }
2705
2706 exprIdx := exprAtPos(c.pos, node.Args)
2707
2708 // If we have one or zero arg expressions, we may be
2709 // completing to a function call that returns multiple
2710 // values, in turn getting passed in to the surrounding
2711 // call. Record the assignees so we can favor function
2712 // calls that return matching values.
2713 if len(node.Args) <= 1 && exprIdx == 0 {
2714 for v := range sig.Params().Variables() {
2715 inf.assignees = append(inf.assignees, v.Type())
2716 }
2717
2718 // Record that we may be completing into variadic parameters.
2719 inf.variadicAssignees = sig.Variadic()
2720 }
2721
2722 // Make sure not to run past the end of expected parameters.
2723 if exprIdx >= numParams {
2724 inf.objType = sig.Params().At(numParams - 1).Type()
2725 } else {
2726 inf.objType = sig.Params().At(exprIdx).Type()
2727 }
2728
2729 if sig.Variadic() && exprIdx >= (numParams-1) {
2730 // If we are completing a variadic param, deslice the variadic type.
2731 inf.objType = deslice(inf.objType)
2732 // Record whether we are completing the initial variadic param.
2733 inf.variadic = exprIdx == numParams-1 && len(node.Args) <= numParams
2734
2735 // Check if we can infer object kind from printf verb.
2736 inf.objKind |= printfArgKind(c.pkg.TypesInfo(), node, exprIdx)
2737 }
2738
2739 // If our expected type is an uninstantiated generic type param,
2740 // swap to the constraint which will do a decent job filtering
2741 // candidates.
2742 if tp, _ := inf.objType.(*types.TypeParam); tp != nil {
2743 inf.objType = tp.Constraint()
2744 }
2745
2746 return inf
2747 }
2748
2749 func expectedConstraint(t types.Type, idx int) types.Type {
2750 var tp *types.TypeParamList
2751 if pnt, ok := t.(typesinternal.NamedOrAlias); ok {
2752 tp = pnt.TypeParams()
2753 } else if sig, _ := t.Underlying().(*types.Signature); sig != nil {
2754 tp = sig.TypeParams()
2755 }
2756 if tp == nil || idx >= tp.Len() {
2757 return nil
2758 }
2759 return tp.At(idx).Constraint()
2760 }
2761
2762 // objChain decomposes e into a chain of objects if possible. For
2763 // example, "foo.bar().baz" will yield []types.Object{foo, bar, baz}.
2764 // If any part can't be turned into an object, return nil.
2765 func objChain(info *types.Info, e ast.Expr) []types.Object {
2766 var objs []types.Object
2767
2768 for e != nil {
2769 switch n := e.(type) {
2770 case *ast.Ident:
2771 obj := info.ObjectOf(n)
2772 if obj == nil {
2773 return nil
2774 }
2775 objs = append(objs, obj)
2776 e = nil
2777 case *ast.SelectorExpr:
2778 obj := info.ObjectOf(n.Sel)
2779 if obj == nil {
2780 return nil
2781 }
2782 objs = append(objs, obj)
2783 e = n.X
2784 case *ast.CallExpr:
2785 if len(n.Args) > 0 {
2786 return nil
2787 }
2788 e = n.Fun
2789 default:
2790 return nil
2791 }
2792 }
2793
2794 // Reverse order so the layout matches the syntactic order.
2795 slices.Reverse(objs)
2796
2797 return objs
2798 }
2799
2800 // applyTypeModifiers applies the list of type modifiers to a type.
2801 // It returns nil if the modifiers could not be applied.
2802 func (ci candidateInference) applyTypeModifiers(typ types.Type, addressable bool) types.Type {
2803 for _, mod := range ci.modifiers {
2804 switch mod.mod {
2805 case dereference:
2806 // For every "*" indirection operator, remove a pointer layer
2807 // from candidate type.
2808 if ptr, ok := typ.Underlying().(*types.Pointer); ok {
2809 typ = ptr.Elem()
2810 } else {
2811 return nil
2812 }
2813 case reference:
2814 // For every "&" address operator, add another pointer layer to
2815 // candidate type, if the candidate is addressable.
2816 if addressable {
2817 typ = types.NewPointer(typ)
2818 } else {
2819 return nil
2820 }
2821 case chanRead:
2822 // For every "<-" operator, remove a layer of channelness.
2823 if ch, ok := typ.(*types.Chan); ok {
2824 typ = ch.Elem()
2825 } else {
2826 return nil
2827 }
2828 }
2829 }
2830
2831 return typ
2832 }
2833
2834 // applyTypeNameModifiers applies the list of type modifiers to a type name.
2835 func (ci candidateInference) applyTypeNameModifiers(typ types.Type) types.Type {
2836 for _, mod := range ci.typeName.modifiers {
2837 switch mod.mod {
2838 case reference:
2839 typ = types.NewPointer(typ)
2840 case arrayType:
2841 typ = types.NewArray(typ, mod.arrayLen)
2842 case sliceType:
2843 typ = types.NewSlice(typ)
2844 }
2845 }
2846 return typ
2847 }
2848
2849 // matchesVariadic returns true if we are completing a variadic
2850 // parameter and candType is a compatible slice type.
2851 func (ci candidateInference) matchesVariadic(candType types.Type) bool {
2852 return ci.variadic && ci.objType != nil && assignableTo(candType, types.NewSlice(ci.objType))
2853 }
2854
2855 // findSwitchStmt returns an *ast.CaseClause's corresponding *ast.SwitchStmt or
2856 // *ast.TypeSwitchStmt. path should start from the case clause's first ancestor.
2857 func findSwitchStmt(path []ast.Node, pos token.Pos, c *ast.CaseClause) ast.Stmt {
2858 // Make sure position falls within a "case <>:" clause.
2859 if exprAtPos(pos, c.List) >= len(c.List) {
2860 return nil
2861 }
2862 // A case clause is always nested within a block statement in a switch statement.
2863 if len(path) < 2 {
2864 return nil
2865 }
2866 if _, ok := path[0].(*ast.BlockStmt); !ok {
2867 return nil
2868 }
2869 switch s := path[1].(type) {
2870 case *ast.SwitchStmt:
2871 return s
2872 case *ast.TypeSwitchStmt:
2873 return s
2874 default:
2875 return nil
2876 }
2877 }
2878
2879 // breaksExpectedTypeInference reports if an expression node's type is unrelated
2880 // to its child expression node types. For example, "Foo{Bar: x.Baz(<>)}" should
2881 // expect a function argument, not a composite literal value.
2882 func breaksExpectedTypeInference(n ast.Node, pos token.Pos) bool {
2883 switch n := n.(type) {
2884 case *ast.CompositeLit:
2885 // Doesn't break inference if pos is in type name.
2886 // For example: "Foo<>{Bar: 123}"
2887 return n.Type == nil || !astutil.NodeContainsPos(n.Type, pos)
2888 case *ast.CallExpr:
2889 // Doesn't break inference if pos is in func name.
2890 // For example: "Foo<>(123)"
2891 return !astutil.NodeContainsPos(n.Fun, pos)
2892 case *ast.FuncLit, *ast.IndexExpr, *ast.SliceExpr:
2893 return true
2894 default:
2895 return false
2896 }
2897 }
2898
2899 // expectTypeName returns information about the expected type name at position.
2900 func expectTypeName(c *completer) typeNameInference {
2901 var inf typeNameInference
2902
2903 Nodes:
2904 for i, p := range c.path {
2905 switch n := p.(type) {
2906 case *ast.FieldList:
2907 // Expect a type name if pos is in a FieldList. This applies to
2908 // FuncType params/results, FuncDecl receiver, StructType, and
2909 // InterfaceType. We don't need to worry about the field name
2910 // because completion bails out early if pos is in an *ast.Ident
2911 // that defines an object.
2912 inf.wantTypeName = true
2913 break Nodes
2914 case *ast.CaseClause:
2915 // Expect type names in type switch case clauses.
2916 if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, n).(*ast.TypeSwitchStmt); ok {
2917 // The case clause types must be assertable from the type switch parameter.
2918 ast.Inspect(swtch.Assign, func(n ast.Node) bool {
2919 if ta, ok := n.(*ast.TypeAssertExpr); ok {
2920 inf.assertableFrom = c.pkg.TypesInfo().TypeOf(ta.X)
2921 return false
2922 }
2923 return true
2924 })
2925 inf.wantTypeName = true
2926
2927 // Track the types that have already been used in this
2928 // switch's case statements so we don't recommend them.
2929 for _, e := range swtch.Body.List {
2930 for _, typeExpr := range e.(*ast.CaseClause).List {
2931 // Skip if type expression contains pos. We don't want to
2932 // count it as already used if the user is completing it.
2933 if typeExpr.Pos() < c.pos && c.pos <= typeExpr.End() {
2934 continue
2935 }
2936
2937 if t := c.pkg.TypesInfo().TypeOf(typeExpr); t != nil {
2938 inf.seenTypeSwitchCases = append(inf.seenTypeSwitchCases, t)
2939 }
2940 }
2941 }
2942
2943 break Nodes
2944 }
2945 return typeNameInference{}
2946 case *ast.TypeAssertExpr:
2947 // Expect type names in type assert expressions.
2948 if n.Lparen < c.pos && c.pos <= n.Rparen {
2949 // The type in parens must be assertable from the expression type.
2950 inf.assertableFrom = c.pkg.TypesInfo().TypeOf(n.X)
2951 inf.wantTypeName = true
2952 break Nodes
2953 }
2954 return typeNameInference{}
2955 case *ast.StarExpr:
2956 inf.modifiers = append(inf.modifiers, typeMod{mod: reference})
2957 case *ast.CompositeLit:
2958 // We want a type name if position is in the "Type" part of a
2959 // composite literal (e.g. "Foo<>{}").
2960 if n.Type != nil && n.Type.Pos() <= c.pos && c.pos <= n.Type.End() {
2961 inf.wantTypeName = true
2962 inf.compLitType = true
2963
2964 if i < len(c.path)-1 {
2965 // Track preceding "&" operator. Technically it applies to
2966 // the composite literal and not the type name, but if
2967 // affects our type completion nonetheless.
2968 if u, ok := c.path[i+1].(*ast.UnaryExpr); ok && u.Op == token.AND {
2969 inf.modifiers = append(inf.modifiers, typeMod{mod: reference})
2970 }
2971 }
2972 }
2973 break Nodes
2974 case *ast.ArrayType:
2975 // If we are inside the "Elt" part of an array type, we want a type name.
2976 if n.Elt.Pos() <= c.pos && c.pos <= n.Elt.End() {
2977 inf.wantTypeName = true
2978 if n.Len == nil {
2979 // No "Len" expression means a slice type.
2980 inf.modifiers = append(inf.modifiers, typeMod{mod: sliceType})
2981 } else {
2982 // Try to get the array type using the constant value of "Len".
2983 tv, ok := c.pkg.TypesInfo().Types[n.Len]
2984 if ok && tv.Value != nil && tv.Value.Kind() == constant.Int {
2985 if arrayLen, ok := constant.Int64Val(tv.Value); ok {
2986 inf.modifiers = append(inf.modifiers, typeMod{mod: arrayType, arrayLen: arrayLen})
2987 }
2988 }
2989 }
2990
2991 // ArrayTypes can be nested, so keep going if our parent is an
2992 // ArrayType.
2993 if i < len(c.path)-1 {
2994 if _, ok := c.path[i+1].(*ast.ArrayType); ok {
2995 continue Nodes
2996 }
2997 }
2998
2999 break Nodes
3000 }
3001 case *ast.MapType:
3002 inf.wantTypeName = true
3003 if n.Key != nil {
3004 inf.wantComparable = astutil.NodeContainsPos(n.Key, c.pos)
3005 } else {
3006 // If the key is empty, assume we are completing the key if
3007 // pos is directly after the "map[".
3008 inf.wantComparable = c.pos == n.Pos()+token.Pos(len("map["))
3009 }
3010 break Nodes
3011 case *ast.ValueSpec:
3012 inf.wantTypeName = n.Type != nil && astutil.NodeContainsPos(n.Type, c.pos)
3013 break Nodes
3014 case *ast.TypeSpec:
3015 inf.wantTypeName = astutil.NodeContainsPos(n.Type, c.pos)
3016 default:
3017 if breaksExpectedTypeInference(p, c.pos) {
3018 return typeNameInference{}
3019 }
3020 }
3021 }
3022
3023 return inf
3024 }
3025
3026 func (c *completer) fakeObj(T types.Type) *types.Var {
3027 return types.NewVar(token.NoPos, c.pkg.Types(), "", T)
3028 }
3029
3030 // derivableTypes iterates types you can derive from t. For example,
3031 // from "foo" we might derive "&foo", and "foo()".
3032 func derivableTypes(t types.Type, addressable bool, f func(t types.Type, addressable bool, mod typeModKind) bool) bool {
3033 switch t := t.Underlying().(type) {
3034 case *types.Signature:
3035 // If t is a func type with a single result, offer the result type.
3036 if t.Results().Len() == 1 && f(t.Results().At(0).Type(), false, invoke) {
3037 return true
3038 }
3039 case *types.Array:
3040 if f(t.Elem(), true, index) {
3041 return true
3042 }
3043 // Try converting array to slice.
3044 if f(types.NewSlice(t.Elem()), false, takeSlice) {
3045 return true
3046 }
3047 case *types.Pointer:
3048 if f(t.Elem(), false, dereference) {
3049 return true
3050 }
3051 case *types.Slice:
3052 if f(t.Elem(), true, index) {
3053 return true
3054 }
3055 case *types.Map:
3056 if f(t.Elem(), false, index) {
3057 return true
3058 }
3059 case *types.Chan:
3060 if f(t.Elem(), false, chanRead) {
3061 return true
3062 }
3063 }
3064
3065 // Check if c is addressable and a pointer to c matches our type inference.
3066 if addressable && f(types.NewPointer(t), false, reference) {
3067 return true
3068 }
3069
3070 return false
3071 }
3072
3073 // anyCandType reports whether f returns true for any candidate type
3074 // derivable from c. It searches up to three levels of type
3075 // modification. For example, given "foo" we could discover "***foo"
3076 // or "*foo()".
3077 func (c *candidate) anyCandType(f func(t types.Type, addressable bool) bool) bool {
3078 if c.obj == nil || c.obj.Type() == nil {
3079 return false
3080 }
3081
3082 const maxDepth = 3
3083
3084 var searchTypes func(t types.Type, addressable bool, mods []typeModKind) bool
3085 searchTypes = func(t types.Type, addressable bool, mods []typeModKind) bool {
3086 if f(t, addressable) {
3087 if len(mods) > 0 {
3088 newMods := make([]typeModKind, len(mods)+len(c.mods))
3089 copy(newMods, mods)
3090 copy(newMods[len(mods):], c.mods)
3091 c.mods = newMods
3092 }
3093 return true
3094 }
3095
3096 if len(mods) == maxDepth {
3097 return false
3098 }
3099
3100 return derivableTypes(t, addressable, func(t types.Type, addressable bool, mod typeModKind) bool {
3101 return searchTypes(t, addressable, append(mods, mod))
3102 })
3103 }
3104
3105 return searchTypes(c.obj.Type(), c.addressable, make([]typeModKind, 0, maxDepth))
3106 }
3107
3108 // matchingCandidate reports whether cand matches our type inferences.
3109 // It mutates cand's score in certain cases.
3110 func (c *completer) matchingCandidate(cand *candidate) bool {
3111 if c.completionContext.commentCompletion {
3112 return false
3113 }
3114
3115 // Bail out early if we are completing a field name in a composite literal.
3116 if v, ok := cand.obj.(*types.Var); ok && v.IsField() && wantStructFieldCompletions(c.enclosingCompositeLiteral) {
3117 return true
3118 }
3119
3120 if isTypeName(cand.obj) {
3121 return c.matchingTypeName(cand)
3122 } else if c.wantTypeName() {
3123 // If we want a type, a non-type object never matches.
3124 return false
3125 }
3126
3127 if c.inference.candTypeMatches(cand) {
3128 return true
3129 }
3130
3131 candType := cand.obj.Type()
3132 if candType == nil {
3133 return false
3134 }
3135
3136 if sig, ok := candType.Underlying().(*types.Signature); ok {
3137 if c.inference.assigneesMatch(cand, sig) {
3138 // Invoke the candidate if its results are multi-assignable.
3139 cand.mods = append(cand.mods, invoke)
3140 return true
3141 }
3142 }
3143
3144 // Default to invoking *types.Func candidates. This is so function
3145 // completions in an empty statement (or other cases with no expected type)
3146 // are invoked by default.
3147 if isFunc(cand.obj) {
3148 cand.mods = append(cand.mods, invoke)
3149 }
3150
3151 return false
3152 }
3153
3154 // candTypeMatches reports whether cand makes a good completion
3155 // candidate given the candidate inference. cand's score may be
3156 // mutated to downrank the candidate in certain situations.
3157 func (ci *candidateInference) candTypeMatches(cand *candidate) bool {
3158 var (
3159 expTypes = make([]types.Type, 0, 2)
3160 variadicType types.Type
3161 )
3162 if ci.objType != nil {
3163 expTypes = append(expTypes, ci.objType)
3164
3165 if ci.variadic {
3166 variadicType = types.NewSlice(ci.objType)
3167 expTypes = append(expTypes, variadicType)
3168 }
3169 }
3170
3171 return cand.anyCandType(func(candType types.Type, addressable bool) bool {
3172 // Take into account any type modifiers on the expected type.
3173 candType = ci.applyTypeModifiers(candType, addressable)
3174 if candType == nil {
3175 return false
3176 }
3177
3178 if ci.convertibleTo != nil && convertibleTo(candType, ci.convertibleTo) {
3179 return true
3180 }
3181
3182 for _, expType := range expTypes {
3183 if isEmptyInterface(expType) {
3184 // If any type matches the expected type, fall back to other
3185 // considerations below.
3186 //
3187 // TODO(rfindley): can this be expressed via scoring, rather than a boolean?
3188 // Why is it the case that we break ties for the empty interface, but
3189 // not for other expected types that may be satisfied by a lot of
3190 // types, such as fmt.Stringer?
3191 continue
3192 }
3193
3194 matches := ci.typeMatches(expType, candType)
3195 if !matches {
3196 // If candType doesn't otherwise match, consider if we can
3197 // convert candType directly to expType.
3198 if considerTypeConversion(candType, expType, cand.path) {
3199 cand.convertTo = expType
3200 // Give a major score penalty so we always prefer directly
3201 // assignable candidates, all else equal.
3202 cand.score *= 0.5
3203 return true
3204 }
3205
3206 continue
3207 }
3208
3209 if expType == variadicType {
3210 cand.mods = append(cand.mods, takeDotDotDot)
3211 }
3212
3213 // Candidate matches, but isn't exactly identical to the expected type.
3214 // Apply a conversion to allow it to match.
3215 if ci.needsExactType && !types.Identical(candType, expType) {
3216 cand.convertTo = expType
3217 // Ranks barely lower if it needs a conversion, even though it's perfectly valid.
3218 cand.score *= 0.95
3219 }
3220
3221 // Lower candidate score for untyped conversions. This avoids
3222 // ranking untyped constants above candidates with an exact type
3223 // match. Don't lower score of builtin constants, e.g. "true".
3224 if isUntyped(candType) && !types.Identical(candType, expType) && cand.obj.Parent() != types.Universe {
3225 // Bigger penalty for deep completions into other packages to
3226 // avoid random constants from other packages popping up all
3227 // the time.
3228 if len(cand.path) > 0 && isPkgName(cand.path[0]) {
3229 cand.score *= 0.5
3230 } else {
3231 cand.score *= 0.75
3232 }
3233 }
3234
3235 return true
3236 }
3237
3238 // If we don't have a specific expected type, fall back to coarser
3239 // object kind checks.
3240 if ci.objType == nil || isEmptyInterface(ci.objType) {
3241 // If we were able to apply type modifiers to our candidate type,
3242 // count that as a match. For example:
3243 //
3244 // var foo chan int
3245 // <-fo<>
3246 //
3247 // We were able to apply the "<-" type modifier to "foo", so "foo"
3248 // matches.
3249 if len(ci.modifiers) > 0 {
3250 return true
3251 }
3252
3253 // If we didn't have an exact type match, check if our object kind
3254 // matches.
3255 if ci.kindMatches(candType) {
3256 if ci.objKind == kindFunc {
3257 cand.mods = append(cand.mods, invoke)
3258 }
3259 return true
3260 }
3261 }
3262
3263 return false
3264 })
3265 }
3266
3267 // considerTypeConversion returns true if we should offer a completion
3268 // automatically converting "from" to "to".
3269 func considerTypeConversion(from, to types.Type, path []types.Object) bool {
3270 // Don't offer to convert deep completions from other packages.
3271 // Otherwise there are many random package level consts/vars that
3272 // pop up as candidates all the time.
3273 if len(path) > 0 && isPkgName(path[0]) {
3274 return false
3275 }
3276
3277 if _, ok := from.(*types.TypeParam); ok {
3278 return false
3279 }
3280
3281 if !convertibleTo(from, to) {
3282 return false
3283 }
3284
3285 // Don't offer to convert ints to strings since that probably
3286 // doesn't do what the user wants.
3287 if isBasicKind(from, types.IsInteger) && isBasicKind(to, types.IsString) {
3288 return false
3289 }
3290
3291 return true
3292 }
3293
3294 // typeMatches reports whether an object of candType makes a good
3295 // completion candidate given the expected type expType.
3296 func (ci *candidateInference) typeMatches(expType, candType types.Type) bool {
3297 // Handle untyped values specially since AssignableTo gives false negatives
3298 // for them (see https://golang.org/issue/32146).
3299 if candBasic, ok := candType.Underlying().(*types.Basic); ok {
3300 if expBasic, ok := expType.Underlying().(*types.Basic); ok {
3301 // Note that the candidate and/or the expected can be untyped.
3302 // In "fo<> == 100" the expected type is untyped, and the
3303 // candidate could also be an untyped constant.
3304
3305 // Sort by is_untyped and then by is_int to simplify below logic.
3306 a, b := candBasic.Info(), expBasic.Info()
3307 if a&types.IsUntyped == 0 || (b&types.IsInteger > 0 && b&types.IsUntyped > 0) {
3308 a, b = b, a
3309 }
3310
3311 // If at least one is untyped...
3312 if a&types.IsUntyped > 0 {
3313 switch {
3314 // Untyped integers are compatible with floats.
3315 case a&types.IsInteger > 0 && b&types.IsFloat > 0:
3316 return true
3317
3318 // Check if their constant kind (bool|int|float|complex|string) matches.
3319 // This doesn't take into account the constant value, so there will be some
3320 // false positives due to integer sign and overflow.
3321 case a&types.IsConstType == b&types.IsConstType:
3322 return true
3323 }
3324 }
3325 }
3326 }
3327
3328 // AssignableTo covers the case where the types are equal, but also handles
3329 // cases like assigning a concrete type to an interface type.
3330 return assignableTo(candType, expType)
3331 }
3332
3333 // kindMatches reports whether candType's kind matches our expected
3334 // kind (e.g. slice, map, etc.).
3335 func (ci *candidateInference) kindMatches(candType types.Type) bool {
3336 return ci.objKind > 0 && ci.objKind&candKind(candType) > 0
3337 }
3338
3339 // assigneesMatch reports whether an invocation of sig matches the
3340 // number and type of any assignees.
3341 func (ci *candidateInference) assigneesMatch(cand *candidate, sig *types.Signature) bool {
3342 if len(ci.assignees) == 0 {
3343 return false
3344 }
3345
3346 // Uniresult functions are always usable and are handled by the
3347 // normal, non-assignees type matching logic.
3348 if sig.Results().Len() == 1 {
3349 return false
3350 }
3351
3352 // Don't prefer completing into func(...interface{}) calls since all
3353 // functions would match.
3354 if ci.variadicAssignees && len(ci.assignees) == 1 && isEmptyInterface(deslice(ci.assignees[0])) {
3355 return false
3356 }
3357
3358 var numberOfResultsCouldMatch bool
3359 if ci.variadicAssignees {
3360 numberOfResultsCouldMatch = sig.Results().Len() >= len(ci.assignees)-1
3361 } else {
3362 numberOfResultsCouldMatch = sig.Results().Len() == len(ci.assignees)
3363 }
3364
3365 // If our signature doesn't return the right number of values, it's
3366 // not a match, so downrank it. For example:
3367 //
3368 // var foo func() (int, int)
3369 // a, b, c := <> // downrank "foo()" since it only returns two values
3370 if !numberOfResultsCouldMatch {
3371 cand.score /= 2
3372 return false
3373 }
3374
3375 // If at least one assignee has a valid type, and all valid
3376 // assignees match the corresponding sig result value, the signature
3377 // is a match.
3378 allMatch := false
3379 for i := range sig.Results().Len() {
3380 var assignee types.Type
3381
3382 // If we are completing into variadic parameters, deslice the
3383 // expected variadic type.
3384 if ci.variadicAssignees && i >= len(ci.assignees)-1 {
3385 assignee = ci.assignees[len(ci.assignees)-1]
3386 if elem := deslice(assignee); elem != nil {
3387 assignee = elem
3388 }
3389 } else {
3390 assignee = ci.assignees[i]
3391 }
3392
3393 if assignee == nil || assignee == types.Typ[types.Invalid] {
3394 continue
3395 }
3396
3397 allMatch = ci.typeMatches(assignee, sig.Results().At(i).Type())
3398 if !allMatch {
3399 break
3400 }
3401 }
3402 return allMatch
3403 }
3404
3405 func (c *completer) matchingTypeName(cand *candidate) bool {
3406 if !c.wantTypeName() {
3407 return false
3408 }
3409
3410 wantExactTypeParam := c.inference.typeName.isTypeParam &&
3411 c.inference.typeName.wantTypeName && c.inference.needsExactType
3412
3413 typeMatches := func(candType types.Type) bool {
3414 // Take into account any type name modifier prefixes.
3415 candType = c.inference.applyTypeNameModifiers(candType)
3416
3417 if from := c.inference.typeName.assertableFrom; from != nil {
3418 // Don't suggest the starting type in type assertions. For example,
3419 // if "foo" is an io.Writer, don't suggest "foo.(io.Writer)".
3420 if types.Identical(from, candType) {
3421 return false
3422 }
3423
3424 if intf, ok := from.Underlying().(*types.Interface); ok {
3425 if !types.AssertableTo(intf, candType) {
3426 return false
3427 }
3428 }
3429 }
3430
3431 // Suggest the exact type when performing reverse type inference.
3432 // x = Foo[<>]()
3433 // Where x is an interface kind, only suggest the interface type rather than its implementors
3434 if wantExactTypeParam && types.Identical(candType, c.inference.objType) {
3435 return true
3436 }
3437
3438 if c.inference.typeName.wantComparable && !types.Comparable(candType) {
3439 return false
3440 }
3441
3442 // Skip this type if it has already been used in another type
3443 // switch case.
3444 for _, seen := range c.inference.typeName.seenTypeSwitchCases {
3445 if types.Identical(candType, seen) {
3446 return false
3447 }
3448 }
3449
3450 // We can expect a type name and have an expected type in cases like:
3451 //
3452 // var foo []int
3453 // foo = []i<>
3454 //
3455 // Where our expected type is "[]int", and we expect a type name.
3456 if c.inference.objType != nil {
3457 return assignableTo(candType, c.inference.objType)
3458 }
3459
3460 // Default to saying any type name is a match.
3461 return true
3462 }
3463
3464 t := cand.obj.Type()
3465
3466 if typeMatches(t) {
3467 return true
3468 }
3469
3470 if !types.IsInterface(t) && typeMatches(types.NewPointer(t)) {
3471 if c.inference.typeName.compLitType {
3472 // If we are completing a composite literal type as in
3473 // "foo<>{}", to make a pointer we must prepend "&".
3474 cand.mods = append(cand.mods, reference)
3475 } else {
3476 // If we are completing a normal type name such as "foo<>", to
3477 // make a pointer we must prepend "*".
3478 cand.mods = append(cand.mods, dereference)
3479 }
3480 return true
3481 }
3482
3483 return false
3484 }
3485
3486 var (
3487 // "interface { Error() string }" (i.e. error)
3488 errorIntf = types.Universe.Lookup("error").Type().Underlying().(*types.Interface)
3489
3490 // "interface { String() string }" (i.e. fmt.Stringer)
3491 stringerIntf = types.NewInterfaceType([]*types.Func{
3492 types.NewFunc(token.NoPos, nil, "String", types.NewSignatureType(
3493 nil, nil,
3494 nil, nil,
3495 types.NewTuple(types.NewParam(token.NoPos, nil, "", types.Typ[types.String])),
3496 false,
3497 )),
3498 }, nil).Complete()
3499
3500 byteType = types.Universe.Lookup("byte").Type()
3501
3502 boolType = types.Universe.Lookup("bool").Type()
3503 )
3504
3505 // candKind returns the objKind of candType, if any.
3506 func candKind(candType types.Type) objKind {
3507 var kind objKind
3508
3509 switch t := candType.Underlying().(type) {
3510 case *types.Array:
3511 kind |= kindArray
3512 if t.Elem() == byteType {
3513 kind |= kindBytes
3514 }
3515 case *types.Slice:
3516 kind |= kindSlice
3517 if t.Elem() == byteType {
3518 kind |= kindBytes
3519 }
3520 case *types.Chan:
3521 kind |= kindChan
3522 case *types.Map:
3523 kind |= kindMap
3524 case *types.Pointer:
3525 kind |= kindPtr
3526
3527 // Some builtins handle array pointers as arrays, so just report a pointer
3528 // to an array as an array.
3529 if _, isArray := t.Elem().Underlying().(*types.Array); isArray {
3530 kind |= kindArray
3531 }
3532 case *types.Interface:
3533 kind |= kindInterface
3534 case *types.Basic:
3535 switch info := t.Info(); {
3536 case info&types.IsString > 0:
3537 kind |= kindString
3538 case info&types.IsInteger > 0:
3539 kind |= kindInt
3540 case info&types.IsFloat > 0:
3541 kind |= kindFloat
3542 case info&types.IsComplex > 0:
3543 kind |= kindComplex
3544 case info&types.IsBoolean > 0:
3545 kind |= kindBool
3546 }
3547 case *types.Signature:
3548 kind |= kindFunc
3549
3550 switch rangeFuncParamCount(t) {
3551 case 0:
3552 kind |= kindRange0Func
3553 case 1:
3554 kind |= kindRange1Func
3555 case 2:
3556 kind |= kindRange2Func
3557 }
3558 }
3559
3560 if types.Implements(candType, errorIntf) {
3561 kind |= kindError
3562 }
3563
3564 if types.Implements(candType, stringerIntf) {
3565 kind |= kindStringer
3566 }
3567
3568 return kind
3569 }
3570
3571 // If sig looks like a range func, return param count, else return -1.
3572 func rangeFuncParamCount(sig *types.Signature) int {
3573 if sig.Results().Len() != 0 || sig.Params().Len() != 1 {
3574 return -1
3575 }
3576
3577 yieldSig, _ := sig.Params().At(0).Type().Underlying().(*types.Signature)
3578 if yieldSig == nil {
3579 return -1
3580 }
3581
3582 if yieldSig.Results().Len() != 1 || yieldSig.Results().At(0).Type() != boolType {
3583 return -1
3584 }
3585
3586 return yieldSig.Params().Len()
3587 }
3588
3589 // innermostScope returns the innermost scope for c.pos.
3590 func (c *completer) innermostScope() *types.Scope {
3591 for _, s := range c.scopes {
3592 if s != nil {
3593 return s
3594 }
3595 }
3596 return nil
3597 }
3598
3599 // isSlice reports whether the object's underlying type is a slice.
3600 func isSlice(obj types.Object) bool {
3601 if obj != nil && obj.Type() != nil {
3602 if _, ok := obj.Type().Underlying().(*types.Slice); ok {
3603 return true
3604 }
3605 }
3606 return false
3607 }
3608
3609 func is[T any](x any) bool {
3610 _, ok := x.(T)
3611 return ok
3612 }