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.
5 // Package completion provides core functionality for code completion in Go
25 "golang.org/x/tools/go/ast/astutil"
26 "golang.org/x/tools/internal/event"
27 "golang.org/x/tools/internal/imports"
28 "golang.org/x/tools/internal/lsp/fuzzy"
29 "golang.org/x/tools/internal/lsp/protocol"
30 "golang.org/x/tools/internal/lsp/snippet"
31 "golang.org/x/tools/internal/lsp/source"
32 errors "golang.org/x/xerrors"
35 type CompletionItem struct {
36 // Label is the primary text the user sees for this completion item.
39 // Detail is supplemental information to present to the user.
40 // This often contains the type or return type of the completion item.
43 // InsertText is the text to insert if this item is selected.
44 // Any of the prefix that has already been typed is not trimmed.
45 // The insert text does not contain snippets.
48 Kind protocol.CompletionItemKind
50 // An optional array of additional TextEdits that are applied when
51 // selecting this completion.
53 // Additional text edits should be used to change text unrelated to the current cursor position
54 // (for example adding an import statement at the top of the file if the completion item will
55 // insert an unqualified type).
56 AdditionalTextEdits []protocol.TextEdit
58 // Depth is how many levels were searched to find this completion.
59 // For example when completing "foo<>", "fooBar" is depth 0, and
60 // "fooBar.Baz" is depth 1.
63 // Score is the internal relevance score.
64 // A higher score indicates that this completion item is more relevant.
67 // snippet is the LSP snippet for the completion item. The LSP
68 // specification contains details about LSP snippets. For example, a
69 // snippet for a function with the following signature:
71 // func foo(a, b, c int)
75 // foo(${1:a int}, ${2: b int}, ${3: c int})
77 // If Placeholders is false in the CompletionOptions, the above
78 // snippet would instead be:
81 snippet *snippet.Builder
83 // Documentation is the documentation for the completion item.
86 // obj is the object from which this candidate was derived, if any.
87 // obj is for internal use only.
91 // completionOptions holds completion specific configuration.
92 type completionOptions struct {
95 fullDocumentation bool
99 matcher source.Matcher
103 // Snippet is a convenience returns the snippet if available, otherwise
105 // used for an item, depending on if the callee wants placeholders or not.
106 func (i *CompletionItem) Snippet() string {
107 if i.snippet != nil {
108 return i.snippet.String()
113 // Scoring constants are used for weighting the relevance of different candidates.
115 // stdScore is the base score for all completion items.
116 stdScore float64 = 1.0
118 // highScore indicates a very relevant completion item.
119 highScore float64 = 10.0
121 // lowScore indicates an irrelevant or not useful completion item.
122 lowScore float64 = 0.01
125 // matcher matches a candidate's label against the user input. The
126 // returned score reflects the quality of the match. A score of zero
127 // indicates no match, and a score of one means a perfect match.
128 type matcher interface {
129 Score(candidateLabel string) (score float32)
132 // prefixMatcher implements case sensitive prefix matching.
133 type prefixMatcher string
135 func (pm prefixMatcher) Score(candidateLabel string) float32 {
136 if strings.HasPrefix(candidateLabel, string(pm)) {
142 // insensitivePrefixMatcher implements case insensitive prefix matching.
143 type insensitivePrefixMatcher string
145 func (ipm insensitivePrefixMatcher) Score(candidateLabel string) float32 {
146 if strings.HasPrefix(strings.ToLower(candidateLabel), string(ipm)) {
152 // completer contains the necessary information for a single completion request.
153 type completer struct {
154 snapshot source.Snapshot
157 opts *completionOptions
159 // completionContext contains information about the trigger for this
160 // completion request.
161 completionContext completionContext
163 // fh is a handle to the file associated with this completion request.
166 // filename is the name of the file associated with this completion request.
169 // file is the AST of the file associated with this completion request.
172 // pos is the position at which the request was triggered.
175 // path is the path of AST nodes enclosing the position.
178 // seen is the map that ensures we do not return duplicate results.
179 seen map[types.Object]bool
181 // items is the list of completion items returned.
182 items []CompletionItem
184 // completionCallbacks is a list of callbacks to collect completions that
185 // require expensive operations. This includes operations where we search
186 // through the entire module cache.
187 completionCallbacks []func(opts *imports.Options) error
189 // surrounding describes the identifier surrounding the position.
190 surrounding *Selection
192 // inference contains information we've inferred about ideal
193 // candidates such as the candidate's type.
194 inference candidateInference
196 // enclosingFunc contains information about the function enclosing
198 enclosingFunc *funcInfo
200 // enclosingCompositeLiteral contains information about the composite literal
201 // enclosing the position.
202 enclosingCompositeLiteral *compLitInfo
204 // deepState contains the current state of our deep completion search.
205 deepState deepCompletionState
207 // matcher matches the candidates against the surrounding prefix.
210 // methodSetCache caches the types.NewMethodSet call, which is relatively
211 // expensive and can be called many times for the same type while searching
212 // for deep completions.
213 methodSetCache map[methodSetKey]*types.MethodSet
215 // mapper converts the positions in the file from which the completion originated.
216 mapper *protocol.ColumnMapper
218 // startTime is when we started processing this completion request. It does
219 // not include any time the request spent in the queue.
223 // funcInfo holds info about a function object.
224 type funcInfo struct {
225 // sig is the function declaration enclosing the position.
228 // body is the function's body.
232 type compLitInfo struct {
233 // cl is the *ast.CompositeLit enclosing the position.
236 // clType is the type of cl.
239 // kv is the *ast.KeyValueExpr enclosing the position, if any.
242 // inKey is true if we are certain the position is in the key side
243 // of a key-value pair.
246 // maybeInFieldName is true if inKey is false and it is possible
247 // we are completing a struct field name. For example,
248 // "SomeStruct{<>}" will be inKey=false, but maybeInFieldName=true
249 // because we _could_ be completing a field name.
250 maybeInFieldName bool
253 type importInfo struct {
259 type methodSetKey struct {
264 type completionContext struct {
265 // triggerCharacter is the character used to trigger completion at current
267 triggerCharacter string
269 // triggerKind is information about how a completion was triggered.
270 triggerKind protocol.CompletionTriggerKind
272 // commentCompletion is true if we are completing a comment.
273 commentCompletion bool
275 // packageCompletion is true if we are completing a package name.
276 packageCompletion bool
279 // A Selection represents the cursor position and surrounding identifier.
280 type Selection struct {
286 func (p Selection) Content() string {
290 func (p Selection) Start() token.Pos {
291 return p.MappedRange.SpanRange().Start
294 func (p Selection) End() token.Pos {
295 return p.MappedRange.SpanRange().End
298 func (p Selection) Prefix() string {
299 return p.content[:p.cursor-p.SpanRange().Start]
302 func (p Selection) Suffix() string {
303 return p.content[p.cursor-p.SpanRange().Start:]
306 func (c *completer) setSurrounding(ident *ast.Ident) {
307 if c.surrounding != nil {
310 if !(ident.Pos() <= c.pos && c.pos <= ident.End()) {
314 c.surrounding = &Selection{
317 // Overwrite the prefix only.
318 MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, ident.Pos(), ident.End()),
321 c.setMatcherFromPrefix(c.surrounding.Prefix())
324 func (c *completer) setMatcherFromPrefix(prefix string) {
325 switch c.opts.matcher {
327 c.matcher = fuzzy.NewMatcher(prefix)
328 case source.CaseSensitive:
329 c.matcher = prefixMatcher(prefix)
331 c.matcher = insensitivePrefixMatcher(strings.ToLower(prefix))
335 func (c *completer) getSurrounding() *Selection {
336 if c.surrounding == nil {
337 c.surrounding = &Selection{
340 MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, c.pos, c.pos),
346 // candidate represents a completion candidate.
347 type candidate struct {
348 // obj is the types.Object to complete to.
351 // score is used to rank candidates.
354 // name is the deep object name path, e.g. "foo.bar"
357 // detail is additional information about this item. If not specified,
358 // defaults to type string for the object.
361 // path holds the path from the search root (excluding the candidate
362 // itself) for a deep candidate.
365 // names tracks the names of objects from search root (excluding the
366 // candidate itself) for a deep candidate. This also includes
367 // expanded calls for function invocations.
370 // expandFuncCall is true if obj should be invoked in the completion.
371 // For example, expandFuncCall=true yields "foo()", expandFuncCall=false yields "foo".
374 // takeAddress is true if the completion should take a pointer to obj.
375 // For example, takeAddress=true yields "&foo", takeAddress=false yields "foo".
378 // addressable is true if a pointer can be taken to the candidate.
381 // makePointer is true if the candidate type name T should be made into *T.
384 // dereference is a count of how many times to dereference the candidate obj.
385 // For example, dereference=2 turns "foo" into "**foo" when formatting.
388 // variadic is true if this candidate fills a variadic param and
389 // needs "..." appended.
392 // convertTo is a type that this candidate should be cast to. For
393 // example, if convertTo is float64, "foo" should be formatted as
397 // imp is the import that needs to be added to this package in order
398 // for this candidate to be valid. nil if no import needed.
402 // ErrIsDefinition is an error that informs the user they got no
403 // completions because they tried to complete the name of a new object
405 type ErrIsDefinition struct {
409 func (e ErrIsDefinition) Error() string {
410 msg := "this is a definition"
412 msg += " of " + e.objStr
417 // Completion returns a list of possible candidates for completion, given a
418 // a file and a position.
420 // The selection is computed based on the preceding identifier and can be used by
421 // the client to score the quality of the completion. For instance, some clients
422 // may tolerate imperfect matches as valid completion results, since users may make typos.
423 func Completion(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle, protoPos protocol.Position, protoContext protocol.CompletionContext) ([]CompletionItem, *Selection, error) {
424 ctx, done := event.Start(ctx, "completion.Completion")
427 startTime := time.Now()
429 pkg, pgf, err := source.GetParsedFile(ctx, snapshot, fh, source.NarrowestPackage)
430 if err != nil || pgf.File.Package == token.NoPos {
431 // If we can't parse this file or find position for the package
432 // keyword, it may be missing a package declaration. Try offering
433 // suggestions for the package declaration.
434 // Note that this would be the case even if the keyword 'package' is
435 // present but no package name exists.
436 items, surrounding, innerErr := packageClauseCompletions(ctx, snapshot, fh, protoPos)
438 // return the error for GetParsedFile since it's more relevant in this situation.
439 return nil, nil, errors.Errorf("getting file for Completion: %w (package completions: %v)", err, innerErr)
441 return items, surrounding, nil
443 spn, err := pgf.Mapper.PointSpan(protoPos)
447 rng, err := spn.Range(pgf.Mapper.Converter)
451 // Completion is based on what precedes the cursor.
452 // Find the path to the position before pos.
453 path, _ := astutil.PathEnclosingInterval(pgf.File, rng.Start-1, rng.Start-1)
455 return nil, nil, errors.Errorf("cannot find node enclosing position")
460 // Check if completion at this position is valid. If not, return early.
461 switch n := path[0].(type) {
463 // Skip completion inside literals except for ImportSpec
465 if _, ok := path[1].(*ast.ImportSpec); ok {
471 if n.Ellipsis.IsValid() && pos > n.Ellipsis && pos <= n.Ellipsis+token.Pos(len("...")) {
472 // Don't offer completions inside or directly after "...". For
473 // example, don't offer completions at "<>" in "foo(bar...<>").
477 // reject defining identifiers
478 if obj, ok := pkg.GetTypesInfo().Defs[n]; ok {
479 if v, ok := obj.(*types.Var); ok && v.IsField() && v.Embedded() {
480 // An anonymous field is also a reference to a type.
481 } else if pgf.File.Name == n {
482 // Don't skip completions if Ident is for package name.
487 qual := types.RelativeTo(pkg.GetTypes())
488 objStr = types.ObjectString(obj, qual)
490 return nil, nil, ErrIsDefinition{objStr: objStr}
495 opts := snapshot.View().Options()
499 qf: source.Qualifier(pgf.File, pkg.GetTypes(), pkg.GetTypesInfo()),
500 completionContext: completionContext{
501 triggerCharacter: protoContext.TriggerCharacter,
502 triggerKind: protoContext.TriggerKind,
505 filename: fh.URI().Filename(),
509 seen: make(map[types.Object]bool),
510 enclosingFunc: enclosingFunction(path, pkg.GetTypesInfo()),
511 enclosingCompositeLiteral: enclosingCompositeLiteral(path, rng.Start, pkg.GetTypesInfo()),
512 deepState: deepCompletionState{
513 enabled: opts.DeepCompletion,
515 opts: &completionOptions{
516 matcher: opts.Matcher,
517 unimported: opts.CompleteUnimported,
518 documentation: opts.CompletionDocumentation && opts.HoverKind != source.NoDocumentation,
519 fullDocumentation: opts.HoverKind == source.FullDocumentation,
520 placeholders: opts.UsePlaceholders,
521 literal: opts.LiteralCompletions && opts.InsertTextFormat == protocol.SnippetTextFormat,
522 budget: opts.CompletionBudget,
523 snippets: opts.InsertTextFormat == protocol.SnippetTextFormat,
525 // default to a matcher that always matches
526 matcher: prefixMatcher(""),
527 methodSetCache: make(map[methodSetKey]*types.MethodSet),
529 startTime: startTime,
532 var cancel context.CancelFunc
533 if c.opts.budget == 0 {
534 ctx, cancel = context.WithCancel(ctx)
536 // timeoutDuration is the completion budget remaining. If less than
538 timeoutDuration := time.Until(c.startTime.Add(c.opts.budget))
539 if timeoutDuration < 10*time.Millisecond {
540 timeoutDuration = 10 * time.Millisecond
542 ctx, cancel = context.WithTimeout(ctx, timeoutDuration)
546 if surrounding := c.containingIdent(pgf.Src); surrounding != nil {
547 c.setSurrounding(surrounding)
550 c.inference = expectedCandidate(ctx, c)
552 err = c.collectCompletions(ctx)
557 // Deep search collected candidates and their members for more candidates.
559 c.deepState.searchQueue = nil
561 for _, callback := range c.completionCallbacks {
562 if err := c.snapshot.RunProcessEnvFunc(ctx, callback); err != nil {
567 // Search candidates populated by expensive operations like
568 // unimportedMembers etc. for more completion items.
571 // Statement candidates offer an entire statement in certain contexts, as
572 // opposed to a single object. Add statement candidates last because they
573 // depend on other candidates having already been collected.
574 c.addStatementCandidates()
577 return c.items, c.getSurrounding(), nil
580 // collectCompletions adds possible completion candidates to either the deep
581 // search queue or completion items directly for different completion contexts.
582 func (c *completer) collectCompletions(ctx context.Context) error {
583 // Inside import blocks, return completions for unimported packages.
584 for _, importSpec := range c.file.Imports {
585 if !(importSpec.Path.Pos() <= c.pos && c.pos <= importSpec.Path.End()) {
588 return c.populateImportCompletions(ctx, importSpec)
591 // Inside comments, offer completions for the name of the relevant symbol.
592 for _, comment := range c.file.Comments {
593 if comment.Pos() < c.pos && c.pos <= comment.End() {
594 c.populateCommentCompletions(ctx, comment)
599 // Struct literals are handled entirely separately.
600 if c.wantStructFieldCompletions() {
601 // If we are definitely completing a struct field name, deep completions
603 if c.enclosingCompositeLiteral.inKey {
604 c.deepState.enabled = false
606 return c.structLiteralFieldName(ctx)
609 if lt := c.wantLabelCompletion(); lt != labelNone {
614 if c.emptySwitchStmt() {
615 // Empty switch statements only admit "default" and "case" keywords.
616 c.addKeywordItems(map[string]bool{}, highScore, CASE, DEFAULT)
620 switch n := c.path[0].(type) {
622 if c.file.Name == n {
623 return c.packageNameCompletions(ctx, c.fh.URI(), n)
624 } else if sel, ok := c.path[1].(*ast.SelectorExpr); ok && sel.Sel == n {
625 // Is this the Sel part of a selector?
626 return c.selector(ctx, sel)
628 return c.lexical(ctx)
629 // The function name hasn't been typed yet, but the parens are there:
631 case *ast.TypeAssertExpr:
632 // Create a fake selector expression.
633 return c.selector(ctx, &ast.SelectorExpr{X: n.X})
634 case *ast.SelectorExpr:
635 return c.selector(ctx, n)
636 // At the file scope, only keywords are allowed.
637 case *ast.BadDecl, *ast.File:
638 c.addKeywordCompletions()
640 // fallback to lexical completions
641 return c.lexical(ctx)
647 // containingIdent returns the *ast.Ident containing pos, if any. It
648 // synthesizes an *ast.Ident to allow completion in the face of
649 // certain syntax errors.
650 func (c *completer) containingIdent(src []byte) *ast.Ident {
651 // In the normal case, our leaf AST node is the identifer being completed.
652 if ident, ok := c.path[0].(*ast.Ident); ok {
656 pos, tkn, lit := c.scanToken(src)
661 fakeIdent := &ast.Ident{Name: lit, NamePos: pos}
663 if _, isBadDecl := c.path[0].(*ast.BadDecl); isBadDecl {
664 // You don't get *ast.Idents at the file level, so look for bad
665 // decls and use the manually extracted token.
667 } else if c.emptySwitchStmt() {
668 // Only keywords are allowed in empty switch statements.
669 // *ast.Idents are not parsed, so we must use the manually
672 } else if tkn.IsKeyword() {
673 // Otherwise, manually extract the prefix if our containing token
674 // is a keyword. This improves completion after an "accidental
675 // keyword", e.g. completing to "variance" in "someFunc(var<>)".
682 // scanToken scans pgh's contents for the token containing pos.
683 func (c *completer) scanToken(contents []byte) (token.Pos, token.Token, string) {
684 tok := c.snapshot.FileSet().File(c.pos)
686 var s scanner.Scanner
687 s.Init(tok, contents, nil, 0)
689 tknPos, tkn, lit := s.Scan()
690 if tkn == token.EOF || tknPos >= c.pos {
691 return token.NoPos, token.ILLEGAL, ""
694 if len(lit) > 0 && tknPos <= c.pos && c.pos <= tknPos+token.Pos(len(lit)) {
695 return tknPos, tkn, lit
700 func (c *completer) sortItems() {
701 sort.SliceStable(c.items, func(i, j int) bool {
702 // Sort by score first.
703 if c.items[i].Score != c.items[j].Score {
704 return c.items[i].Score > c.items[j].Score
707 // Then sort by label so order stays consistent. This also has the
708 // effect of preferring shorter candidates.
709 return c.items[i].Label < c.items[j].Label
713 // emptySwitchStmt reports whether pos is in an empty switch or select
715 func (c *completer) emptySwitchStmt() bool {
716 block, ok := c.path[0].(*ast.BlockStmt)
717 if !ok || len(block.List) > 0 || len(c.path) == 1 {
721 switch c.path[1].(type) {
722 case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt:
729 // populateImportCompletions yields completions for an import path around the cursor.
731 // Completions are suggested at the directory depth of the given import path so
732 // that we don't overwhelm the user with a large list of possibilities. As an
733 // example, a completion for the prefix "golang" results in "golang.org/".
734 // Completions for "golang.org/" yield its subdirectories
735 // (i.e. "golang.org/x/"). The user is meant to accept completion suggestions
736 // until they reach a complete import path.
737 func (c *completer) populateImportCompletions(ctx context.Context, searchImport *ast.ImportSpec) error {
738 if !strings.HasPrefix(searchImport.Path.Value, `"`) {
742 // deepSearch is not valuable for import completions.
743 c.deepState.enabled = false
745 importPath := searchImport.Path.Value
747 // Extract the text between the quotes (if any) in an import spec.
748 // prefix is the part of import path before the cursor.
749 prefixEnd := c.pos - searchImport.Path.Pos()
750 prefix := strings.Trim(importPath[:prefixEnd], `"`)
752 // The number of directories in the import path gives us the depth at
754 depth := len(strings.Split(prefix, "/")) - 1
756 content := importPath
757 start, end := searchImport.Path.Pos(), searchImport.Path.End()
758 namePrefix, nameSuffix := `"`, `"`
759 // If a starting quote is present, adjust surrounding to either after the
760 // cursor or after the first slash (/), except if cursor is at the starting
761 // quote. Otherwise we provide a completion including the starting quote.
762 if strings.HasPrefix(importPath, `"`) && c.pos > searchImport.Path.Pos() {
763 content = content[1:]
766 // Adjust textEdit start to replacement range. For ex: if current
767 // path was "golang.or/x/to<>ols/internal/", where <> is the cursor
768 // position, start of the replacement range would be after
770 path := strings.SplitAfter(prefix, "/")
771 numChars := len(strings.Join(path[:len(path)-1], ""))
772 content = content[numChars:]
773 start += token.Pos(numChars)
778 // We won't provide an ending quote if one is already present, except if
779 // cursor is after the ending quote but still in import spec. This is
780 // because cursor has to be in our textEdit range.
781 if strings.HasSuffix(importPath, `"`) && c.pos < searchImport.Path.End() {
783 content = content[:len(content)-1]
787 c.surrounding = &Selection{
790 MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, start, end),
793 seenImports := make(map[string]struct{})
794 for _, importSpec := range c.file.Imports {
795 if importSpec.Path.Value == importPath {
798 seenImportPath, err := strconv.Unquote(importSpec.Path.Value)
802 seenImports[seenImportPath] = struct{}{}
805 var mu sync.Mutex // guard c.items locally, since searchImports is called in parallel
806 seen := make(map[string]struct{})
807 searchImports := func(pkg imports.ImportFix) {
808 path := pkg.StmtInfo.ImportPath
809 if _, ok := seenImports[path]; ok {
813 // Any package path containing fewer directories than the search
814 // prefix is not a match.
815 pkgDirList := strings.Split(path, "/")
816 if len(pkgDirList) < depth+1 {
819 pkgToConsider := strings.Join(pkgDirList[:depth+1], "/")
821 name := pkgDirList[depth]
822 // if we're adding an opening quote to completion too, set name to full
823 // package path since we'll need to overwrite that range.
824 if namePrefix == `"` {
828 score := pkg.Relevance
829 if len(pkgDirList)-1 == depth {
832 // For incomplete package paths, add a terminal slash to indicate that the
833 // user should keep triggering completions.
838 if _, ok := seen[pkgToConsider]; ok {
841 seen[pkgToConsider] = struct{}{}
846 name = namePrefix + name + nameSuffix
847 obj := types.NewPkgName(0, nil, name, types.NewPackage(pkgToConsider, name))
848 c.deepState.enqueue(candidate{
850 detail: fmt.Sprintf("%q", pkgToConsider),
855 c.completionCallbacks = append(c.completionCallbacks, func(opts *imports.Options) error {
856 return imports.GetImportPaths(ctx, searchImports, prefix, c.filename, c.pkg.GetTypes().Name(), opts.Env)
861 // populateCommentCompletions yields completions for comments preceding or in declarations.
862 func (c *completer) populateCommentCompletions(ctx context.Context, comment *ast.CommentGroup) {
863 // If the completion was triggered by a period, ignore it. These types of
864 // completions will not be useful in comments.
865 if c.completionContext.triggerCharacter == "." {
869 // Using the comment position find the line after
870 file := c.snapshot.FileSet().File(comment.End())
875 // Deep completion doesn't work properly in comments since we don't
876 // have a type object to complete further.
877 c.deepState.enabled = false
878 c.completionContext.commentCompletion = true
880 // Documentation isn't useful in comments, since it might end up being the
882 c.opts.documentation = false
884 commentLine := file.Line(comment.End())
886 // comment is valid, set surrounding as word boundaries around cursor
887 c.setSurroundingForComment(comment)
889 // Using the next line pos, grab and parse the exported symbol on that line
890 for _, n := range c.file.Decls {
891 declLine := file.Line(n.Pos())
892 // if the comment is not in, directly above or on the same line as a declaration
893 if declLine != commentLine && declLine != commentLine+1 &&
894 !(n.Pos() <= comment.Pos() && comment.End() <= n.End()) {
897 switch node := n.(type) {
898 // handle const, vars, and types
900 for _, spec := range node.Specs {
901 switch spec := spec.(type) {
903 for _, name := range spec.Names {
904 if name.String() == "_" {
907 obj := c.pkg.GetTypesInfo().ObjectOf(name)
908 c.deepState.enqueue(candidate{obj: obj, score: stdScore})
911 // add TypeSpec fields to completion
912 switch typeNode := spec.Type.(type) {
913 case *ast.StructType:
914 c.addFieldItems(ctx, typeNode.Fields)
916 c.addFieldItems(ctx, typeNode.Params)
917 c.addFieldItems(ctx, typeNode.Results)
918 case *ast.InterfaceType:
919 c.addFieldItems(ctx, typeNode.Methods)
922 if spec.Name.String() == "_" {
926 obj := c.pkg.GetTypesInfo().ObjectOf(spec.Name)
927 // Type name should get a higher score than fields but not highScore by default
928 // since field near a comment cursor gets a highScore
929 score := stdScore * 1.1
930 // If type declaration is on the line after comment, give it a highScore.
931 if declLine == commentLine+1 {
935 c.deepState.enqueue(candidate{obj: obj, score: score})
940 c.addFieldItems(ctx, node.Recv)
941 c.addFieldItems(ctx, node.Type.Params)
942 c.addFieldItems(ctx, node.Type.Results)
944 // collect receiver struct fields
945 if node.Recv != nil {
946 for _, fields := range node.Recv.List {
947 for _, name := range fields.Names {
948 obj := c.pkg.GetTypesInfo().ObjectOf(name)
953 recvType := obj.Type().Underlying()
954 if ptr, ok := recvType.(*types.Pointer); ok {
955 recvType = ptr.Elem()
957 recvStruct, ok := recvType.Underlying().(*types.Struct)
961 for i := 0; i < recvStruct.NumFields(); i++ {
962 field := recvStruct.Field(i)
963 c.deepState.enqueue(candidate{obj: field, score: lowScore})
969 if node.Name.String() == "_" {
973 obj := c.pkg.GetTypesInfo().ObjectOf(node.Name)
974 if obj == nil || obj.Pkg() != nil && obj.Pkg() != c.pkg.GetTypes() {
978 c.deepState.enqueue(candidate{obj: obj, score: highScore})
983 // sets word boundaries surrounding a cursor for a comment
984 func (c *completer) setSurroundingForComment(comments *ast.CommentGroup) {
985 var cursorComment *ast.Comment
986 for _, comment := range comments.List {
987 if c.pos >= comment.Pos() && c.pos <= comment.End() {
988 cursorComment = comment
992 // if cursor isn't in the comment
993 if cursorComment == nil {
997 // index of cursor in comment text
998 cursorOffset := int(c.pos - cursorComment.Pos())
999 start, end := cursorOffset, cursorOffset
1000 for start > 0 && isValidIdentifierChar(cursorComment.Text[start-1]) {
1003 for end < len(cursorComment.Text) && isValidIdentifierChar(cursorComment.Text[end]) {
1007 c.surrounding = &Selection{
1008 content: cursorComment.Text[start:end],
1010 MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper,
1011 token.Pos(int(cursorComment.Slash)+start), token.Pos(int(cursorComment.Slash)+end)),
1013 c.setMatcherFromPrefix(c.surrounding.Prefix())
1016 // isValidIdentifierChar returns true if a byte is a valid go identifier
1017 // character, i.e. unicode letter or digit or underscore.
1018 func isValidIdentifierChar(char byte) bool {
1019 charRune := rune(char)
1020 return unicode.In(charRune, unicode.Letter, unicode.Digit) || char == '_'
1023 // adds struct fields, interface methods, function declaration fields to completion
1024 func (c *completer) addFieldItems(ctx context.Context, fields *ast.FieldList) {
1029 cursor := c.surrounding.cursor
1030 for _, field := range fields.List {
1031 for _, name := range field.Names {
1032 if name.String() == "_" {
1035 obj := c.pkg.GetTypesInfo().ObjectOf(name)
1040 // if we're in a field comment/doc, score that field as more relevant
1042 if field.Comment != nil && field.Comment.Pos() <= cursor && cursor <= field.Comment.End() {
1044 } else if field.Doc != nil && field.Doc.Pos() <= cursor && cursor <= field.Doc.End() {
1048 c.deepState.enqueue(candidate{obj: obj, score: score})
1053 func (c *completer) wantStructFieldCompletions() bool {
1054 clInfo := c.enclosingCompositeLiteral
1059 return clInfo.isStruct() && (clInfo.inKey || clInfo.maybeInFieldName)
1062 func (c *completer) wantTypeName() bool {
1063 return !c.completionContext.commentCompletion && c.inference.typeName.wantTypeName
1066 // See https://golang.org/issue/36001. Unimported completions are expensive.
1068 maxUnimportedPackageNames = 5
1069 unimportedMemberTarget = 100
1072 // selector finds completions for the specified selector expression.
1073 func (c *completer) selector(ctx context.Context, sel *ast.SelectorExpr) error {
1074 c.inference.objChain = objChain(c.pkg.GetTypesInfo(), sel.X)
1076 // Is sel a qualified identifier?
1077 if id, ok := sel.X.(*ast.Ident); ok {
1078 if pkgName, ok := c.pkg.GetTypesInfo().Uses[id].(*types.PkgName); ok {
1079 var pkg source.Package
1080 for _, imp := range c.pkg.Imports() {
1081 if imp.PkgPath() == pkgName.Imported().Path() {
1085 // If the package is not imported, try searching for unimported
1087 if pkg == nil && c.opts.unimported {
1088 if err := c.unimportedMembers(ctx, id); err != nil {
1092 candidates := c.packageMembers(pkgName.Imported(), stdScore, nil)
1093 for _, cand := range candidates {
1094 c.deepState.enqueue(cand)
1100 // Invariant: sel is a true selector.
1101 tv, ok := c.pkg.GetTypesInfo().Types[sel.X]
1103 candidates := c.methodsAndFields(tv.Type, tv.Addressable(), nil)
1104 for _, cand := range candidates {
1105 c.deepState.enqueue(cand)
1110 // Try unimported packages.
1111 if id, ok := sel.X.(*ast.Ident); ok && c.opts.unimported {
1112 if err := c.unimportedMembers(ctx, id); err != nil {
1119 func (c *completer) unimportedMembers(ctx context.Context, id *ast.Ident) error {
1120 // Try loaded packages first. They're relevant, fast, and fully typed.
1121 known, err := c.snapshot.CachedImportPaths(ctx)
1127 for path, pkg := range known {
1128 if pkg.GetTypes().Name() != id.Name {
1131 paths = append(paths, path)
1134 var relevances map[string]float64
1135 if len(paths) != 0 {
1136 if err := c.snapshot.RunProcessEnvFunc(ctx, func(opts *imports.Options) error {
1138 relevances, err = imports.ScoreImportPaths(ctx, opts.Env, paths)
1144 sort.Slice(paths, func(i, j int) bool {
1145 return relevances[paths[i]] > relevances[paths[j]]
1148 for _, path := range paths {
1150 if pkg.GetTypes().Name() != id.Name {
1157 if imports.ImportPathToAssumedName(path) != pkg.GetTypes().Name() {
1158 imp.name = pkg.GetTypes().Name()
1160 candidates := c.packageMembers(pkg.GetTypes(), unimportedScore(relevances[path]), imp)
1161 for _, cand := range candidates {
1162 c.deepState.enqueue(cand)
1164 if len(c.items) >= unimportedMemberTarget {
1169 ctx, cancel := context.WithCancel(ctx)
1172 add := func(pkgExport imports.PackageExport) {
1175 if _, ok := known[pkgExport.Fix.StmtInfo.ImportPath]; ok {
1176 return // We got this one above.
1179 // Continue with untyped proposals.
1180 pkg := types.NewPackage(pkgExport.Fix.StmtInfo.ImportPath, pkgExport.Fix.IdentName)
1181 for _, export := range pkgExport.Exports {
1182 score := unimportedScore(pkgExport.Fix.Relevance)
1183 c.deepState.enqueue(candidate{
1184 obj: types.NewVar(0, pkg, export, nil),
1187 importPath: pkgExport.Fix.StmtInfo.ImportPath,
1188 name: pkgExport.Fix.StmtInfo.Name,
1192 if len(c.items) >= unimportedMemberTarget {
1197 c.completionCallbacks = append(c.completionCallbacks, func(opts *imports.Options) error {
1199 return imports.GetPackageExports(ctx, add, id.Name, c.filename, c.pkg.GetTypes().Name(), opts.Env)
1204 // unimportedScore returns a score for an unimported package that is generally
1205 // lower than other candidates.
1206 func unimportedScore(relevance float64) float64 {
1207 return (stdScore + .1*relevance) / 2
1210 func (c *completer) packageMembers(pkg *types.Package, score float64, imp *importInfo) []candidate {
1211 var candidates []candidate
1212 scope := pkg.Scope()
1213 for _, name := range scope.Names() {
1214 obj := scope.Lookup(name)
1215 candidates = append(candidates, candidate{
1219 addressable: isVar(obj),
1225 func (c *completer) methodsAndFields(typ types.Type, addressable bool, imp *importInfo) []candidate {
1226 mset := c.methodSetCache[methodSetKey{typ, addressable}]
1228 if addressable && !types.IsInterface(typ) && !isPointer(typ) {
1229 // Add methods of *T, which includes methods with receiver T.
1230 mset = types.NewMethodSet(types.NewPointer(typ))
1232 // Add methods of T.
1233 mset = types.NewMethodSet(typ)
1235 c.methodSetCache[methodSetKey{typ, addressable}] = mset
1238 var candidates []candidate
1239 for i := 0; i < mset.Len(); i++ {
1240 candidates = append(candidates, candidate{
1241 obj: mset.At(i).Obj(),
1244 addressable: addressable || isPointer(typ),
1249 eachField(typ, func(v *types.Var) {
1250 candidates = append(candidates, candidate{
1252 score: stdScore - 0.01,
1254 addressable: addressable || isPointer(typ),
1261 // lexical finds completions in the lexical environment.
1262 func (c *completer) lexical(ctx context.Context) error {
1263 scopes := source.CollectScopes(c.pkg.GetTypesInfo(), c.path, c.pos)
1264 scopes = append(scopes, c.pkg.GetTypes().Scope(), types.Universe)
1267 builtinIota = types.Universe.Lookup("iota")
1268 builtinNil = types.Universe.Lookup("nil")
1269 // comparable is an interface that exists on the dev.typeparams Go branch.
1270 // Filter it out from completion results to stabilize tests.
1271 // TODO(rFindley) update (or remove) our handling for comparable once the
1272 // type parameter API has stabilized.
1273 builtinComparable = types.Universe.Lookup("comparable")
1276 // Track seen variables to avoid showing completions for shadowed variables.
1277 // This works since we look at scopes from innermost to outermost.
1278 seen := make(map[string]struct{})
1280 // Process scopes innermost first.
1281 for i, scope := range scopes {
1287 for _, name := range scope.Names() {
1288 declScope, obj := scope.LookupParent(name, c.pos)
1289 if declScope != scope {
1290 continue // Name was declared in some enclosing scope, or not at all.
1292 if obj == builtinComparable {
1296 // If obj's type is invalid, find the AST node that defines the lexical block
1297 // containing the declaration of obj. Don't resolve types for packages.
1298 if !isPkgName(obj) && !typeIsValid(obj.Type()) {
1299 // Match the scope to its ast.Node. If the scope is the package scope,
1300 // use the *ast.File as the starting node.
1302 if i < len(c.path) {
1304 } else if i == len(c.path) { // use the *ast.File for package scope
1308 if resolved := resolveInvalid(c.snapshot.FileSet(), obj, node, c.pkg.GetTypesInfo()); resolved != nil {
1314 // Don't use LHS of decl in RHS.
1315 for _, ident := range enclosingDeclLHS(c.path) {
1316 if obj.Pos() == ident.Pos() {
1321 // Don't suggest "iota" outside of const decls.
1322 if obj == builtinIota && !c.inConstDecl() {
1326 // Rank outer scopes lower than inner.
1327 score := stdScore * math.Pow(.99, float64(i))
1329 // Dowrank "nil" a bit so it is ranked below more interesting candidates.
1330 if obj == builtinNil {
1334 // If we haven't already added a candidate for an object with this name.
1335 if _, ok := seen[obj.Name()]; !ok {
1336 seen[obj.Name()] = struct{}{}
1337 c.deepState.enqueue(candidate{
1340 addressable: isVar(obj),
1346 if c.inference.objType != nil {
1347 if named, _ := source.Deref(c.inference.objType).(*types.Named); named != nil {
1348 // If we expected a named type, check the type's package for
1349 // completion items. This is useful when the current file hasn't
1350 // imported the type's package yet.
1352 if named.Obj() != nil && named.Obj().Pkg() != nil {
1353 pkg := named.Obj().Pkg()
1355 // Make sure the package name isn't already in use by another
1356 // object, and that this file doesn't import the package yet.
1357 if _, ok := seen[pkg.Name()]; !ok && pkg != c.pkg.GetTypes() && !alreadyImports(c.file, pkg.Path()) {
1358 seen[pkg.Name()] = struct{}{}
1359 obj := types.NewPkgName(0, nil, pkg.Name(), pkg)
1361 importPath: pkg.Path(),
1363 if imports.ImportPathToAssumedName(pkg.Path()) != pkg.Name() {
1364 imp.name = pkg.Name()
1366 c.deepState.enqueue(candidate{
1376 if c.opts.unimported {
1377 if err := c.unimportedPackages(ctx, seen); err != nil {
1382 if t := c.inference.objType; t != nil {
1385 // If we have an expected type and it is _not_ a named type,
1386 // handle it specially. Non-named types like "[]int" will never be
1387 // considered via a lexical search, so we need to directly inject
1389 if _, named := t.(*types.Named); !named {
1390 // If our expected type is "[]int", this will add a literal
1391 // candidate of "[]int{}".
1392 c.literal(ctx, t, nil)
1394 if _, isBasic := t.(*types.Basic); !isBasic {
1395 // If we expect a non-basic type name (e.g. "[]int"), hack up
1396 // a named type whose name is literally "[]int". This allows
1397 // us to reuse our object based completion machinery.
1398 fakeNamedType := candidate{
1399 obj: types.NewTypeName(token.NoPos, nil, types.TypeString(t, c.qf), t),
1402 // Make sure the type name matches before considering
1403 // candidate. This cuts down on useless candidates.
1404 if c.matchingTypeName(&fakeNamedType) {
1405 c.deepState.enqueue(fakeNamedType)
1411 // Add keyword completion items appropriate in the current context.
1412 c.addKeywordCompletions()
1417 func (c *completer) unimportedPackages(ctx context.Context, seen map[string]struct{}) error {
1419 if c.surrounding != nil {
1420 prefix = c.surrounding.Prefix()
1424 known, err := c.snapshot.CachedImportPaths(ctx)
1429 for path, pkg := range known {
1430 if !strings.HasPrefix(pkg.GetTypes().Name(), prefix) {
1433 paths = append(paths, path)
1436 var relevances map[string]float64
1437 if len(paths) != 0 {
1438 if err := c.snapshot.RunProcessEnvFunc(ctx, func(opts *imports.Options) error {
1440 relevances, err = imports.ScoreImportPaths(ctx, opts.Env, paths)
1446 sort.Slice(paths, func(i, j int) bool {
1447 return relevances[paths[i]] > relevances[paths[j]]
1450 for _, path := range paths {
1452 if _, ok := seen[pkg.GetTypes().Name()]; ok {
1459 if imports.ImportPathToAssumedName(path) != pkg.GetTypes().Name() {
1460 imp.name = pkg.GetTypes().Name()
1462 if count >= maxUnimportedPackageNames {
1465 c.deepState.enqueue(candidate{
1466 obj: types.NewPkgName(0, nil, pkg.GetTypes().Name(), pkg.GetTypes()),
1467 score: unimportedScore(relevances[path]),
1473 ctx, cancel := context.WithCancel(ctx)
1476 add := func(pkg imports.ImportFix) {
1479 if _, ok := seen[pkg.IdentName]; ok {
1482 if _, ok := relevances[pkg.StmtInfo.ImportPath]; ok {
1486 if count >= maxUnimportedPackageNames {
1491 // Do not add the unimported packages to seen, since we can have
1492 // multiple packages of the same name as completion suggestions, since
1493 // only one will be chosen.
1494 obj := types.NewPkgName(0, nil, pkg.IdentName, types.NewPackage(pkg.StmtInfo.ImportPath, pkg.IdentName))
1495 c.deepState.enqueue(candidate{
1497 score: unimportedScore(pkg.Relevance),
1499 importPath: pkg.StmtInfo.ImportPath,
1500 name: pkg.StmtInfo.Name,
1505 c.completionCallbacks = append(c.completionCallbacks, func(opts *imports.Options) error {
1507 return imports.GetAllCandidates(ctx, add, prefix, c.filename, c.pkg.GetTypes().Name(), opts.Env)
1512 // alreadyImports reports whether f has an import with the specified path.
1513 func alreadyImports(f *ast.File, path string) bool {
1514 for _, s := range f.Imports {
1515 if source.ImportPath(s) == path {
1522 func (c *completer) inConstDecl() bool {
1523 for _, n := range c.path {
1524 if decl, ok := n.(*ast.GenDecl); ok && decl.Tok == token.CONST {
1531 // structLiteralFieldName finds completions for struct field names inside a struct literal.
1532 func (c *completer) structLiteralFieldName(ctx context.Context) error {
1533 clInfo := c.enclosingCompositeLiteral
1535 // Mark fields of the composite literal that have already been set,
1536 // except for the current field.
1537 addedFields := make(map[*types.Var]bool)
1538 for _, el := range clInfo.cl.Elts {
1539 if kvExpr, ok := el.(*ast.KeyValueExpr); ok {
1540 if clInfo.kv == kvExpr {
1544 if key, ok := kvExpr.Key.(*ast.Ident); ok {
1545 if used, ok := c.pkg.GetTypesInfo().Uses[key]; ok {
1546 if usedVar, ok := used.(*types.Var); ok {
1547 addedFields[usedVar] = true
1554 deltaScore := 0.0001
1555 switch t := clInfo.clType.(type) {
1557 for i := 0; i < t.NumFields(); i++ {
1559 if !addedFields[field] {
1560 c.deepState.enqueue(candidate{
1562 score: highScore - float64(i)*deltaScore,
1567 // Add lexical completions if we aren't certain we are in the key part of a
1569 if clInfo.maybeInFieldName {
1570 return c.lexical(ctx)
1573 return c.lexical(ctx)
1579 func (cl *compLitInfo) isStruct() bool {
1580 _, ok := cl.clType.(*types.Struct)
1584 // enclosingCompositeLiteral returns information about the composite literal enclosing the
1586 func enclosingCompositeLiteral(path []ast.Node, pos token.Pos, info *types.Info) *compLitInfo {
1587 for _, n := range path {
1588 switch n := n.(type) {
1589 case *ast.CompositeLit:
1590 // The enclosing node will be a composite literal if the user has just
1591 // opened the curly brace (e.g. &x{<>) or the completion request is triggered
1592 // from an already completed composite literal expression (e.g. &x{foo: 1, <>})
1594 // The position is not part of the composite literal unless it falls within the
1595 // curly braces (e.g. "foo.Foo<>Struct{}").
1596 if !(n.Lbrace < pos && pos <= n.Rbrace) {
1597 // Keep searching since we may yet be inside a composite literal.
1598 // For example "Foo{B: Ba<>{}}".
1602 tv, ok := info.Types[n]
1607 clInfo := compLitInfo{
1609 clType: source.Deref(tv.Type).Underlying(),
1616 for _, el := range n.Elts {
1617 // Remember the expression that the position falls in, if any.
1618 if el.Pos() <= pos && pos <= el.End() {
1622 if kv, ok := el.(*ast.KeyValueExpr); ok {
1624 // If expr == el then we know the position falls in this expression,
1625 // so also record kv as the enclosing *ast.KeyValueExpr.
1633 if clInfo.kv != nil {
1634 // If in a *ast.KeyValueExpr, we know we are in the key if the position
1635 // is to the left of the colon (e.g. "Foo{F<>: V}".
1636 clInfo.inKey = pos <= clInfo.kv.Colon
1638 // If we aren't in a *ast.KeyValueExpr but the composite literal has
1639 // other *ast.KeyValueExprs, we must be on the key side of a new
1640 // *ast.KeyValueExpr (e.g. "Foo{F: V, <>}").
1643 switch clInfo.clType.(type) {
1645 if len(n.Elts) == 0 {
1646 // If the struct literal is empty, next could be a struct field
1647 // name or an expression (e.g. "Foo{<>}" could become "Foo{F:}"
1648 // or "Foo{someVar}").
1649 clInfo.maybeInFieldName = true
1650 } else if len(n.Elts) == 1 {
1651 // If there is one expression and the position is in that expression
1652 // and the expression is an identifier, we may be writing a field
1653 // name or an expression (e.g. "Foo{F<>}").
1654 _, clInfo.maybeInFieldName = expr.(*ast.Ident)
1657 // If we aren't in a *ast.KeyValueExpr we must be adding a new key
1665 if breaksExpectedTypeInference(n, pos) {
1674 // enclosingFunction returns the signature and body of the function
1675 // enclosing the given position.
1676 func enclosingFunction(path []ast.Node, info *types.Info) *funcInfo {
1677 for _, node := range path {
1678 switch t := node.(type) {
1680 if obj, ok := info.Defs[t.Name]; ok {
1682 sig: obj.Type().(*types.Signature),
1687 if typ, ok := info.Types[t]; ok {
1689 sig: typ.Type.(*types.Signature),
1698 func (c *completer) expectedCompositeLiteralType() types.Type {
1699 clInfo := c.enclosingCompositeLiteral
1700 switch t := clInfo.clType.(type) {
1703 return types.Typ[types.UntypedInt]
1708 return types.Typ[types.UntypedInt]
1717 // If we are completing a key (i.e. field name), there is no expected type.
1722 // If we are in a key-value pair, but not in the key, then we must be on the
1723 // value side. The expected type of the value will be determined from the key.
1724 if clInfo.kv != nil {
1725 if key, ok := clInfo.kv.Key.(*ast.Ident); ok {
1726 for i := 0; i < t.NumFields(); i++ {
1727 if field := t.Field(i); field.Name() == key.Name {
1733 // If we aren't in a key-value pair and aren't in the key, we must be using
1734 // implicit field names.
1736 // The order of the literal fields must match the order in the struct definition.
1737 // Find the element that the position belongs to and suggest that field's type.
1738 if i := exprAtPos(c.pos, clInfo.cl.Elts); i < t.NumFields() {
1739 return t.Field(i).Type()
1746 // typeModifier represents an operator that changes the expected type.
1747 type typeModifier struct {
1755 dereference typeMod = iota // pointer indirection: "*"
1756 reference // adds level of pointer: "&" for values, "*" for type names
1757 chanRead // channel read operator ("<-")
1758 slice // make a slice type ("[]" in "[]int")
1759 array // make an array type ("[2]" in "[2]int")
1766 kindArray objKind = 1 << iota
1783 // penalizedObj represents an object that should be disfavored as a
1784 // completion candidate.
1785 type penalizedObj struct {
1786 // objChain is the full "chain", e.g. "foo.bar().baz" becomes
1787 // []types.Object{foo, bar, baz}.
1788 objChain []types.Object
1789 // penalty is score penalty in the range (0, 1).
1793 // candidateInference holds information we have inferred about a type that can be
1794 // used at the current position.
1795 type candidateInference struct {
1796 // objType is the desired type of an object used at the query position.
1799 // objKind is a mask of expected kinds of types such as "map", "slice", etc.
1802 // variadic is true if we are completing the initial variadic
1803 // parameter. For example:
1804 // append([]T{}, <>) // objType=T variadic=true
1805 // append([]T{}, T{}, <>) // objType=T variadic=false
1808 // modifiers are prefixes such as "*", "&" or "<-" that influence how
1809 // a candidate type relates to the expected type.
1810 modifiers []typeModifier
1812 // convertibleTo is a type our candidate type must be convertible to.
1813 convertibleTo types.Type
1815 // typeName holds information about the expected type name at
1816 // position, if any.
1817 typeName typeNameInference
1819 // assignees are the types that would receive a function call's
1820 // results at the position. For example:
1825 // at "<>", the assignees are [int, <invalid>].
1826 assignees []types.Type
1828 // variadicAssignees is true if we could be completing an inner
1829 // function call that fills out an outer function call's variadic
1830 // params. For example:
1832 // func foo(int, ...string) {}
1834 // foo(<>) // variadicAssignees=true
1835 // foo(bar<>) // variadicAssignees=true
1836 // foo(bar, baz<>) // variadicAssignees=false
1837 variadicAssignees bool
1839 // penalized holds expressions that should be disfavored as
1840 // candidates. For example, it tracks expressions already used in a
1841 // switch statement's other cases. Each expression is tracked using
1842 // its entire object "chain" allowing differentiation between
1843 // "a.foo" and "b.foo" when "a" and "b" are the same type.
1844 penalized []penalizedObj
1846 // objChain contains the chain of objects representing the
1847 // surrounding *ast.SelectorExpr. For example, if we are completing
1848 // "foo.bar.ba<>", objChain will contain []types.Object{foo, bar}.
1849 objChain []types.Object
1852 // typeNameInference holds information about the expected type name at
1854 type typeNameInference struct {
1855 // wantTypeName is true if we expect the name of a type.
1858 // modifiers are prefixes such as "*", "&" or "<-" that influence how
1859 // a candidate type relates to the expected type.
1860 modifiers []typeModifier
1862 // assertableFrom is a type that must be assertable to our candidate type.
1863 assertableFrom types.Type
1865 // wantComparable is true if we want a comparable type.
1868 // seenTypeSwitchCases tracks types that have already been used by
1869 // the containing type switch.
1870 seenTypeSwitchCases []types.Type
1872 // compLitType is true if we are completing a composite literal type
1873 // name, e.g "foo<>{}".
1877 // expectedCandidate returns information about the expected candidate
1878 // for an expression at the query position.
1879 func expectedCandidate(ctx context.Context, c *completer) (inf candidateInference) {
1880 inf.typeName = expectTypeName(c)
1882 if c.enclosingCompositeLiteral != nil {
1883 inf.objType = c.expectedCompositeLiteralType()
1887 for i, node := range c.path {
1888 switch node := node.(type) {
1889 case *ast.BinaryExpr:
1890 // Determine if query position comes from left or right of op.
1892 if c.pos < node.OpPos {
1895 if tv, ok := c.pkg.GetTypesInfo().Types[e]; ok {
1897 case token.LAND, token.LOR:
1898 // Don't infer "bool" type for "&&" or "||". Often you want
1899 // to compose a boolean expression from non-boolean
1902 inf.objType = tv.Type
1906 case *ast.AssignStmt:
1907 // Only rank completions if you are on the right side of the token.
1908 if c.pos > node.TokPos {
1909 i := exprAtPos(c.pos, node.Rhs)
1910 if i >= len(node.Lhs) {
1911 i = len(node.Lhs) - 1
1913 if tv, ok := c.pkg.GetTypesInfo().Types[node.Lhs[i]]; ok {
1914 inf.objType = tv.Type
1917 // If we have a single expression on the RHS, record the LHS
1918 // assignees so we can favor multi-return function calls with
1919 // matching result values.
1920 if len(node.Rhs) <= 1 {
1921 for _, lhs := range node.Lhs {
1922 inf.assignees = append(inf.assignees, c.pkg.GetTypesInfo().TypeOf(lhs))
1925 // Otherwse, record our single assignee, even if its type is
1926 // not available. We use this info to downrank functions
1927 // with the wrong number of result values.
1928 inf.assignees = append(inf.assignees, c.pkg.GetTypesInfo().TypeOf(node.Lhs[i]))
1932 case *ast.ValueSpec:
1933 if node.Type != nil && c.pos > node.Type.End() {
1934 inf.objType = c.pkg.GetTypesInfo().TypeOf(node.Type)
1938 // Only consider CallExpr args if position falls between parens.
1939 if node.Lparen < c.pos && c.pos <= node.Rparen {
1940 // For type conversions like "int64(foo)" we can only infer our
1941 // desired type is convertible to int64.
1942 if typ := typeConversion(node, c.pkg.GetTypesInfo()); typ != nil {
1943 inf.convertibleTo = typ
1947 if tv, ok := c.pkg.GetTypesInfo().Types[node.Fun]; ok {
1948 if sig, ok := tv.Type.(*types.Signature); ok {
1949 numParams := sig.Params().Len()
1954 exprIdx := exprAtPos(c.pos, node.Args)
1956 // If we have one or zero arg expressions, we may be
1957 // completing to a function call that returns multiple
1958 // values, in turn getting passed in to the surrounding
1959 // call. Record the assignees so we can favor function
1960 // calls that return matching values.
1961 if len(node.Args) <= 1 && exprIdx == 0 {
1962 for i := 0; i < sig.Params().Len(); i++ {
1963 inf.assignees = append(inf.assignees, sig.Params().At(i).Type())
1966 // Record that we may be completing into variadic parameters.
1967 inf.variadicAssignees = sig.Variadic()
1970 // Make sure not to run past the end of expected parameters.
1971 if exprIdx >= numParams {
1972 inf.objType = sig.Params().At(numParams - 1).Type()
1974 inf.objType = sig.Params().At(exprIdx).Type()
1977 if sig.Variadic() && exprIdx >= (numParams-1) {
1978 // If we are completing a variadic param, deslice the variadic type.
1979 inf.objType = deslice(inf.objType)
1980 // Record whether we are completing the initial variadic param.
1981 inf.variadic = exprIdx == numParams-1 && len(node.Args) <= numParams
1983 // Check if we can infer object kind from printf verb.
1984 inf.objKind |= printfArgKind(c.pkg.GetTypesInfo(), node, exprIdx)
1989 if funIdent, ok := node.Fun.(*ast.Ident); ok {
1990 obj := c.pkg.GetTypesInfo().ObjectOf(funIdent)
1992 if obj != nil && obj.Parent() == types.Universe {
1993 // Defer call to builtinArgType so we can provide it the
1994 // inferred type from its parent node.
1996 inf = c.builtinArgType(obj, node, inf)
1997 inf.objKind = c.builtinArgKind(ctx, obj, node)
2000 // The expected type of builtin arguments like append() is
2001 // the expected type of the builtin call itself. For
2004 // var foo []int = append(<>)
2006 // To find the expected type at <> we "skip" the append()
2007 // node and get the expected type one level up, which is
2015 case *ast.ReturnStmt:
2016 if c.enclosingFunc != nil {
2017 sig := c.enclosingFunc.sig
2018 // Find signature result that corresponds to our return statement.
2019 if resultIdx := exprAtPos(c.pos, node.Results); resultIdx < len(node.Results) {
2020 if resultIdx < sig.Results().Len() {
2021 inf.objType = sig.Results().At(resultIdx).Type()
2026 case *ast.CaseClause:
2027 if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, node).(*ast.SwitchStmt); ok {
2028 if tv, ok := c.pkg.GetTypesInfo().Types[swtch.Tag]; ok {
2029 inf.objType = tv.Type
2031 // Record which objects have already been used in the case
2032 // statements so we don't suggest them again.
2033 for _, cc := range swtch.Body.List {
2034 for _, caseExpr := range cc.(*ast.CaseClause).List {
2035 // Don't record the expression we are currently completing.
2036 if caseExpr.Pos() < c.pos && c.pos <= caseExpr.End() {
2040 if objs := objChain(c.pkg.GetTypesInfo(), caseExpr); len(objs) > 0 {
2041 inf.penalized = append(inf.penalized, penalizedObj{objChain: objs, penalty: 0.1})
2048 case *ast.SliceExpr:
2049 // Make sure position falls within the brackets (e.g. "foo[a:<>]").
2050 if node.Lbrack < c.pos && c.pos <= node.Rbrack {
2051 inf.objType = types.Typ[types.UntypedInt]
2054 case *ast.IndexExpr:
2055 // Make sure position falls within the brackets (e.g. "foo[<>]").
2056 if node.Lbrack < c.pos && c.pos <= node.Rbrack {
2057 if tv, ok := c.pkg.GetTypesInfo().Types[node.X]; ok {
2058 switch t := tv.Type.Underlying().(type) {
2060 inf.objType = t.Key()
2061 case *types.Slice, *types.Array:
2062 inf.objType = types.Typ[types.UntypedInt]
2068 // Make sure we are on right side of arrow (e.g. "foo <- <>").
2069 if c.pos > node.Arrow+1 {
2070 if tv, ok := c.pkg.GetTypesInfo().Types[node.Chan]; ok {
2071 if ch, ok := tv.Type.Underlying().(*types.Chan); ok {
2072 inf.objType = ch.Elem()
2077 case *ast.RangeStmt:
2078 if source.NodeContains(node.X, c.pos) {
2079 inf.objKind |= kindSlice | kindArray | kindMap | kindString
2080 if node.Value == nil {
2081 inf.objKind |= kindChan
2086 inf.modifiers = append(inf.modifiers, typeModifier{mod: dereference})
2087 case *ast.UnaryExpr:
2090 inf.modifiers = append(inf.modifiers, typeModifier{mod: reference})
2092 inf.modifiers = append(inf.modifiers, typeModifier{mod: chanRead})
2094 case *ast.DeferStmt, *ast.GoStmt:
2095 inf.objKind |= kindFunc
2098 if breaksExpectedTypeInference(node, c.pos) {
2107 // objChain decomposes e into a chain of objects if possible. For
2108 // example, "foo.bar().baz" will yield []types.Object{foo, bar, baz}.
2109 // If any part can't be turned into an object, return nil.
2110 func objChain(info *types.Info, e ast.Expr) []types.Object {
2111 var objs []types.Object
2114 switch n := e.(type) {
2116 obj := info.ObjectOf(n)
2120 objs = append(objs, obj)
2122 case *ast.SelectorExpr:
2123 obj := info.ObjectOf(n.Sel)
2127 objs = append(objs, obj)
2130 if len(n.Args) > 0 {
2139 // Reverse order so the layout matches the syntactic order.
2140 for i := 0; i < len(objs)/2; i++ {
2141 objs[i], objs[len(objs)-1-i] = objs[len(objs)-1-i], objs[i]
2147 // applyTypeModifiers applies the list of type modifiers to a type.
2148 // It returns nil if the modifiers could not be applied.
2149 func (ci candidateInference) applyTypeModifiers(typ types.Type, addressable bool) types.Type {
2150 for _, mod := range ci.modifiers {
2153 // For every "*" indirection operator, remove a pointer layer
2154 // from candidate type.
2155 if ptr, ok := typ.Underlying().(*types.Pointer); ok {
2161 // For every "&" address operator, add another pointer layer to
2162 // candidate type, if the candidate is addressable.
2164 typ = types.NewPointer(typ)
2169 // For every "<-" operator, remove a layer of channelness.
2170 if ch, ok := typ.(*types.Chan); ok {
2181 // applyTypeNameModifiers applies the list of type modifiers to a type name.
2182 func (ci candidateInference) applyTypeNameModifiers(typ types.Type) types.Type {
2183 for _, mod := range ci.typeName.modifiers {
2186 typ = types.NewPointer(typ)
2188 typ = types.NewArray(typ, mod.arrayLen)
2190 typ = types.NewSlice(typ)
2196 // matchesVariadic returns true if we are completing a variadic
2197 // parameter and candType is a compatible slice type.
2198 func (ci candidateInference) matchesVariadic(candType types.Type) bool {
2199 return ci.variadic && ci.objType != nil && types.AssignableTo(candType, types.NewSlice(ci.objType))
2202 // findSwitchStmt returns an *ast.CaseClause's corresponding *ast.SwitchStmt or
2203 // *ast.TypeSwitchStmt. path should start from the case clause's first ancestor.
2204 func findSwitchStmt(path []ast.Node, pos token.Pos, c *ast.CaseClause) ast.Stmt {
2205 // Make sure position falls within a "case <>:" clause.
2206 if exprAtPos(pos, c.List) >= len(c.List) {
2209 // A case clause is always nested within a block statement in a switch statement.
2213 if _, ok := path[0].(*ast.BlockStmt); !ok {
2216 switch s := path[1].(type) {
2217 case *ast.SwitchStmt:
2219 case *ast.TypeSwitchStmt:
2226 // breaksExpectedTypeInference reports if an expression node's type is unrelated
2227 // to its child expression node types. For example, "Foo{Bar: x.Baz(<>)}" should
2228 // expect a function argument, not a composite literal value.
2229 func breaksExpectedTypeInference(n ast.Node, pos token.Pos) bool {
2230 switch n := n.(type) {
2231 case *ast.CompositeLit:
2232 // Doesn't break inference if pos is in type name.
2233 // For example: "Foo<>{Bar: 123}"
2234 return !source.NodeContains(n.Type, pos)
2236 // Doesn't break inference if pos is in func name.
2237 // For example: "Foo<>(123)"
2238 return !source.NodeContains(n.Fun, pos)
2239 case *ast.FuncLit, *ast.IndexExpr, *ast.SliceExpr:
2246 // expectTypeName returns information about the expected type name at position.
2247 func expectTypeName(c *completer) typeNameInference {
2248 var inf typeNameInference
2251 for i, p := range c.path {
2252 switch n := p.(type) {
2253 case *ast.FieldList:
2254 // Expect a type name if pos is in a FieldList. This applies to
2255 // FuncType params/results, FuncDecl receiver, StructType, and
2256 // InterfaceType. We don't need to worry about the field name
2257 // because completion bails out early if pos is in an *ast.Ident
2258 // that defines an object.
2259 inf.wantTypeName = true
2261 case *ast.CaseClause:
2262 // Expect type names in type switch case clauses.
2263 if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, n).(*ast.TypeSwitchStmt); ok {
2264 // The case clause types must be assertable from the type switch parameter.
2265 ast.Inspect(swtch.Assign, func(n ast.Node) bool {
2266 if ta, ok := n.(*ast.TypeAssertExpr); ok {
2267 inf.assertableFrom = c.pkg.GetTypesInfo().TypeOf(ta.X)
2272 inf.wantTypeName = true
2274 // Track the types that have already been used in this
2275 // switch's case statements so we don't recommend them.
2276 for _, e := range swtch.Body.List {
2277 for _, typeExpr := range e.(*ast.CaseClause).List {
2278 // Skip if type expression contains pos. We don't want to
2279 // count it as already used if the user is completing it.
2280 if typeExpr.Pos() < c.pos && c.pos <= typeExpr.End() {
2284 if t := c.pkg.GetTypesInfo().TypeOf(typeExpr); t != nil {
2285 inf.seenTypeSwitchCases = append(inf.seenTypeSwitchCases, t)
2292 return typeNameInference{}
2293 case *ast.TypeAssertExpr:
2294 // Expect type names in type assert expressions.
2295 if n.Lparen < c.pos && c.pos <= n.Rparen {
2296 // The type in parens must be assertable from the expression type.
2297 inf.assertableFrom = c.pkg.GetTypesInfo().TypeOf(n.X)
2298 inf.wantTypeName = true
2301 return typeNameInference{}
2303 inf.modifiers = append(inf.modifiers, typeModifier{mod: reference})
2304 case *ast.CompositeLit:
2305 // We want a type name if position is in the "Type" part of a
2306 // composite literal (e.g. "Foo<>{}").
2307 if n.Type != nil && n.Type.Pos() <= c.pos && c.pos <= n.Type.End() {
2308 inf.wantTypeName = true
2309 inf.compLitType = true
2311 if i < len(c.path)-1 {
2312 // Track preceding "&" operator. Technically it applies to
2313 // the composite literal and not the type name, but if
2314 // affects our type completion nonetheless.
2315 if u, ok := c.path[i+1].(*ast.UnaryExpr); ok && u.Op == token.AND {
2316 inf.modifiers = append(inf.modifiers, typeModifier{mod: reference})
2321 case *ast.ArrayType:
2322 // If we are inside the "Elt" part of an array type, we want a type name.
2323 if n.Elt.Pos() <= c.pos && c.pos <= n.Elt.End() {
2324 inf.wantTypeName = true
2326 // No "Len" expression means a slice type.
2327 inf.modifiers = append(inf.modifiers, typeModifier{mod: slice})
2329 // Try to get the array type using the constant value of "Len".
2330 tv, ok := c.pkg.GetTypesInfo().Types[n.Len]
2331 if ok && tv.Value != nil && tv.Value.Kind() == constant.Int {
2332 if arrayLen, ok := constant.Int64Val(tv.Value); ok {
2333 inf.modifiers = append(inf.modifiers, typeModifier{mod: array, arrayLen: arrayLen})
2338 // ArrayTypes can be nested, so keep going if our parent is an
2340 if i < len(c.path)-1 {
2341 if _, ok := c.path[i+1].(*ast.ArrayType); ok {
2349 inf.wantTypeName = true
2351 inf.wantComparable = source.NodeContains(n.Key, c.pos)
2353 // If the key is empty, assume we are completing the key if
2354 // pos is directly after the "map[".
2355 inf.wantComparable = c.pos == n.Pos()+token.Pos(len("map["))
2358 case *ast.ValueSpec:
2359 inf.wantTypeName = source.NodeContains(n.Type, c.pos)
2362 inf.wantTypeName = source.NodeContains(n.Type, c.pos)
2364 if breaksExpectedTypeInference(p, c.pos) {
2365 return typeNameInference{}
2373 func (c *completer) fakeObj(T types.Type) *types.Var {
2374 return types.NewVar(token.NoPos, c.pkg.GetTypes(), "", T)
2377 // anyCandType reports whether f returns true for any candidate type
2378 // derivable from c. For example, from "foo" we might derive "&foo",
2380 func (c *candidate) anyCandType(f func(t types.Type, addressable bool) bool) bool {
2381 if c.obj == nil || c.obj.Type() == nil {
2385 objType := c.obj.Type()
2387 if f(objType, c.addressable) {
2391 // If c is a func type with a single result, offer the result type.
2392 if sig, ok := objType.Underlying().(*types.Signature); ok {
2393 if sig.Results().Len() == 1 && f(sig.Results().At(0).Type(), false) {
2394 // Mark the candidate so we know to append "()" when formatting.
2395 c.expandFuncCall = true
2401 seenPtrTypes map[types.Type]bool
2406 // Check if dereferencing c would match our type inference. We loop
2407 // since c could have arbitrary levels of pointerness.
2409 ptr, ok := ptrType.Underlying().(*types.Pointer)
2416 // Avoid pointer type cycles.
2417 if seenPtrTypes[ptrType] {
2421 if _, named := ptrType.(*types.Named); named {
2422 // Lazily allocate "seen" since it isn't used normally.
2423 if seenPtrTypes == nil {
2424 seenPtrTypes = make(map[types.Type]bool)
2427 // Track named pointer types we have seen to detect cycles.
2428 seenPtrTypes[ptrType] = true
2431 if f(ptr.Elem(), false) {
2432 // Mark the candidate so we know to prepend "*" when formatting.
2433 c.dereference = ptrDepth
2437 ptrType = ptr.Elem()
2440 // Check if c is addressable and a pointer to c matches our type inference.
2441 if c.addressable && f(types.NewPointer(objType), false) {
2442 // Mark the candidate so we know to prepend "&" when formatting.
2443 c.takeAddress = true
2450 // matchingCandidate reports whether cand matches our type inferences.
2451 // It mutates cand's score in certain cases.
2452 func (c *completer) matchingCandidate(cand *candidate) bool {
2453 if c.completionContext.commentCompletion {
2457 // Bail out early if we are completing a field name in a composite literal.
2458 if v, ok := cand.obj.(*types.Var); ok && v.IsField() && c.wantStructFieldCompletions() {
2462 if isTypeName(cand.obj) {
2463 return c.matchingTypeName(cand)
2464 } else if c.wantTypeName() {
2465 // If we want a type, a non-type object never matches.
2469 if c.inference.candTypeMatches(cand) {
2473 candType := cand.obj.Type()
2474 if candType == nil {
2478 if sig, ok := candType.Underlying().(*types.Signature); ok {
2479 if c.inference.assigneesMatch(cand, sig) {
2480 // Invoke the candidate if its results are multi-assignable.
2481 cand.expandFuncCall = true
2486 // Default to invoking *types.Func candidates. This is so function
2487 // completions in an empty statement (or other cases with no expected type)
2488 // are invoked by default.
2489 cand.expandFuncCall = isFunc(cand.obj)
2494 // candTypeMatches reports whether cand makes a good completion
2495 // candidate given the candidate inference. cand's score may be
2496 // mutated to downrank the candidate in certain situations.
2497 func (ci *candidateInference) candTypeMatches(cand *candidate) bool {
2499 expTypes = make([]types.Type, 0, 2)
2500 variadicType types.Type
2502 if ci.objType != nil {
2503 expTypes = append(expTypes, ci.objType)
2506 variadicType = types.NewSlice(ci.objType)
2507 expTypes = append(expTypes, variadicType)
2511 return cand.anyCandType(func(candType types.Type, addressable bool) bool {
2512 // Take into account any type modifiers on the expected type.
2513 candType = ci.applyTypeModifiers(candType, addressable)
2514 if candType == nil {
2518 if ci.convertibleTo != nil && types.ConvertibleTo(candType, ci.convertibleTo) {
2522 for _, expType := range expTypes {
2523 if isEmptyInterface(expType) {
2527 matches := ci.typeMatches(expType, candType)
2529 // If candType doesn't otherwise match, consider if we can
2530 // convert candType directly to expType.
2531 if considerTypeConversion(candType, expType, cand.path) {
2532 cand.convertTo = expType
2533 // Give a major score penalty so we always prefer directly
2534 // assignable candidates, all else equal.
2542 if expType == variadicType {
2543 cand.variadic = true
2546 // Lower candidate score for untyped conversions. This avoids
2547 // ranking untyped constants above candidates with an exact type
2548 // match. Don't lower score of builtin constants, e.g. "true".
2549 if isUntyped(candType) && !types.Identical(candType, expType) && cand.obj.Parent() != types.Universe {
2550 // Bigger penalty for deep completions into other packages to
2551 // avoid random constants from other packages popping up all
2553 if len(cand.path) > 0 && isPkgName(cand.path[0]) {
2563 // If we don't have a specific expected type, fall back to coarser
2564 // object kind checks.
2565 if ci.objType == nil || isEmptyInterface(ci.objType) {
2566 // If we were able to apply type modifiers to our candidate type,
2567 // count that as a match. For example:
2572 // We were able to apply the "<-" type modifier to "foo", so "foo"
2574 if len(ci.modifiers) > 0 {
2578 // If we didn't have an exact type match, check if our object kind
2580 if ci.kindMatches(candType) {
2581 if ci.objKind == kindFunc {
2582 cand.expandFuncCall = true
2592 // considerTypeConversion returns true if we should offer a completion
2593 // automatically converting "from" to "to".
2594 func considerTypeConversion(from, to types.Type, path []types.Object) bool {
2595 // Don't offer to convert deep completions from other packages.
2596 // Otherwise there are many random package level consts/vars that
2597 // pop up as candidates all the time.
2598 if len(path) > 0 && isPkgName(path[0]) {
2602 if !types.ConvertibleTo(from, to) {
2606 // Don't offer to convert ints to strings since that probably
2607 // doesn't do what the user wants.
2608 if isBasicKind(from, types.IsInteger) && isBasicKind(to, types.IsString) {
2615 // typeMatches reports whether an object of candType makes a good
2616 // completion candidate given the expected type expType.
2617 func (ci *candidateInference) typeMatches(expType, candType types.Type) bool {
2618 // Handle untyped values specially since AssignableTo gives false negatives
2619 // for them (see https://golang.org/issue/32146).
2620 if candBasic, ok := candType.Underlying().(*types.Basic); ok {
2621 if expBasic, ok := expType.Underlying().(*types.Basic); ok {
2622 // Note that the candidate and/or the expected can be untyped.
2623 // In "fo<> == 100" the expected type is untyped, and the
2624 // candidate could also be an untyped constant.
2626 // Sort by is_untyped and then by is_int to simplify below logic.
2627 a, b := candBasic.Info(), expBasic.Info()
2628 if a&types.IsUntyped == 0 || (b&types.IsInteger > 0 && b&types.IsUntyped > 0) {
2632 // If at least one is untyped...
2633 if a&types.IsUntyped > 0 {
2635 // Untyped integers are compatible with floats.
2636 case a&types.IsInteger > 0 && b&types.IsFloat > 0:
2639 // Check if their constant kind (bool|int|float|complex|string) matches.
2640 // This doesn't take into account the constant value, so there will be some
2641 // false positives due to integer sign and overflow.
2642 case a&types.IsConstType == b&types.IsConstType:
2649 // AssignableTo covers the case where the types are equal, but also handles
2650 // cases like assigning a concrete type to an interface type.
2651 return types.AssignableTo(candType, expType)
2654 // kindMatches reports whether candType's kind matches our expected
2655 // kind (e.g. slice, map, etc.).
2656 func (ci *candidateInference) kindMatches(candType types.Type) bool {
2657 return ci.objKind > 0 && ci.objKind&candKind(candType) > 0
2660 // assigneesMatch reports whether an invocation of sig matches the
2661 // number and type of any assignees.
2662 func (ci *candidateInference) assigneesMatch(cand *candidate, sig *types.Signature) bool {
2663 if len(ci.assignees) == 0 {
2667 // Uniresult functions are always usable and are handled by the
2668 // normal, non-assignees type matching logic.
2669 if sig.Results().Len() == 1 {
2673 var numberOfResultsCouldMatch bool
2674 if ci.variadicAssignees {
2675 numberOfResultsCouldMatch = sig.Results().Len() >= len(ci.assignees)-1
2677 numberOfResultsCouldMatch = sig.Results().Len() == len(ci.assignees)
2680 // If our signature doesn't return the right number of values, it's
2681 // not a match, so downrank it. For example:
2683 // var foo func() (int, int)
2684 // a, b, c := <> // downrank "foo()" since it only returns two values
2685 if !numberOfResultsCouldMatch {
2690 // If at least one assignee has a valid type, and all valid
2691 // assignees match the corresponding sig result value, the signature
2694 for i := 0; i < sig.Results().Len(); i++ {
2695 var assignee types.Type
2697 // If we are completing into variadic parameters, deslice the
2698 // expected variadic type.
2699 if ci.variadicAssignees && i >= len(ci.assignees)-1 {
2700 assignee = ci.assignees[len(ci.assignees)-1]
2701 if elem := deslice(assignee); elem != nil {
2705 assignee = ci.assignees[i]
2708 if assignee == nil {
2712 allMatch = ci.typeMatches(assignee, sig.Results().At(i).Type())
2720 func (c *completer) matchingTypeName(cand *candidate) bool {
2721 if !c.wantTypeName() {
2725 typeMatches := func(candType types.Type) bool {
2726 // Take into account any type name modifier prefixes.
2727 candType = c.inference.applyTypeNameModifiers(candType)
2729 if from := c.inference.typeName.assertableFrom; from != nil {
2730 // Don't suggest the starting type in type assertions. For example,
2731 // if "foo" is an io.Writer, don't suggest "foo.(io.Writer)".
2732 if types.Identical(from, candType) {
2736 if intf, ok := from.Underlying().(*types.Interface); ok {
2737 if !types.AssertableTo(intf, candType) {
2743 if c.inference.typeName.wantComparable && !types.Comparable(candType) {
2747 // Skip this type if it has already been used in another type
2749 for _, seen := range c.inference.typeName.seenTypeSwitchCases {
2750 if types.Identical(candType, seen) {
2755 // We can expect a type name and have an expected type in cases like:
2760 // Where our expected type is "[]int", and we expect a type name.
2761 if c.inference.objType != nil {
2762 return types.AssignableTo(candType, c.inference.objType)
2765 // Default to saying any type name is a match.
2769 t := cand.obj.Type()
2775 if !source.IsInterface(t) && typeMatches(types.NewPointer(t)) {
2776 if c.inference.typeName.compLitType {
2777 // If we are completing a composite literal type as in
2778 // "foo<>{}", to make a pointer we must prepend "&".
2779 cand.takeAddress = true
2781 // If we are completing a normal type name such as "foo<>", to
2782 // make a pointer we must prepend "*".
2783 cand.makePointer = true
2792 // "interface { Error() string }" (i.e. error)
2793 errorIntf = types.Universe.Lookup("error").Type().Underlying().(*types.Interface)
2795 // "interface { String() string }" (i.e. fmt.Stringer)
2796 stringerIntf = types.NewInterfaceType([]*types.Func{
2797 types.NewFunc(token.NoPos, nil, "String", types.NewSignature(
2800 types.NewTuple(types.NewParam(token.NoPos, nil, "", types.Typ[types.String])),
2805 byteType = types.Universe.Lookup("byte").Type()
2808 // candKind returns the objKind of candType, if any.
2809 func candKind(candType types.Type) objKind {
2812 switch t := candType.Underlying().(type) {
2815 if t.Elem() == byteType {
2820 if t.Elem() == byteType {
2827 case *types.Pointer:
2830 // Some builtins handle array pointers as arrays, so just report a pointer
2831 // to an array as an array.
2832 if _, isArray := t.Elem().Underlying().(*types.Array); isArray {
2836 switch info := t.Info(); {
2837 case info&types.IsString > 0:
2839 case info&types.IsInteger > 0:
2841 case info&types.IsFloat > 0:
2843 case info&types.IsComplex > 0:
2845 case info&types.IsBoolean > 0:
2848 case *types.Signature:
2852 if types.Implements(candType, errorIntf) {
2856 if types.Implements(candType, stringerIntf) {
2857 kind |= kindStringer