.gitignore added
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.1.1-0.20210319172145-bda8f5cee399 / internal / lsp / source / completion / completion.go
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         "math"
18         "sort"
19         "strconv"
20         "strings"
21         "sync"
22         "time"
23         "unicode"
24
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"
33 )
34
35 type CompletionItem struct {
36         // Label is the primary text the user sees for this completion item.
37         Label string
38
39         // Detail is supplemental information to present to the user.
40         // This often contains the type or return type of the completion item.
41         Detail string
42
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.
46         InsertText string
47
48         Kind protocol.CompletionItemKind
49
50         // An optional array of additional TextEdits that are applied when
51         // selecting this completion.
52         //
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
57
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.
61         Depth int
62
63         // Score is the internal relevance score.
64         // A higher score indicates that this completion item is more relevant.
65         Score float64
66
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:
70         //
71         //     func foo(a, b, c int)
72         //
73         // would be:
74         //
75         //     foo(${1:a int}, ${2: b int}, ${3: c int})
76         //
77         // If Placeholders is false in the CompletionOptions, the above
78         // snippet would instead be:
79         //
80         //     foo(${1:})
81         snippet *snippet.Builder
82
83         // Documentation is the documentation for the completion item.
84         Documentation string
85
86         // obj is the object from which this candidate was derived, if any.
87         // obj is for internal use only.
88         obj types.Object
89 }
90
91 // completionOptions holds completion specific configuration.
92 type completionOptions struct {
93         unimported        bool
94         documentation     bool
95         fullDocumentation bool
96         placeholders      bool
97         literal           bool
98         snippets          bool
99         matcher           source.Matcher
100         budget            time.Duration
101 }
102
103 // Snippet is a convenience returns the snippet if available, otherwise
104 // the InsertText.
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()
109         }
110         return i.InsertText
111 }
112
113 // Scoring constants are used for weighting the relevance of different candidates.
114 const (
115         // stdScore is the base score for all completion items.
116         stdScore float64 = 1.0
117
118         // highScore indicates a very relevant completion item.
119         highScore float64 = 10.0
120
121         // lowScore indicates an irrelevant or not useful completion item.
122         lowScore float64 = 0.01
123 )
124
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)
130 }
131
132 // prefixMatcher implements case sensitive prefix matching.
133 type prefixMatcher string
134
135 func (pm prefixMatcher) Score(candidateLabel string) float32 {
136         if strings.HasPrefix(candidateLabel, string(pm)) {
137                 return 1
138         }
139         return -1
140 }
141
142 // insensitivePrefixMatcher implements case insensitive prefix matching.
143 type insensitivePrefixMatcher string
144
145 func (ipm insensitivePrefixMatcher) Score(candidateLabel string) float32 {
146         if strings.HasPrefix(strings.ToLower(candidateLabel), string(ipm)) {
147                 return 1
148         }
149         return -1
150 }
151
152 // completer contains the necessary information for a single completion request.
153 type completer struct {
154         snapshot source.Snapshot
155         pkg      source.Package
156         qf       types.Qualifier
157         opts     *completionOptions
158
159         // completionContext contains information about the trigger for this
160         // completion request.
161         completionContext completionContext
162
163         // fh is a handle to the file associated with this completion request.
164         fh source.FileHandle
165
166         // filename is the name of the file associated with this completion request.
167         filename string
168
169         // file is the AST of the file associated with this completion request.
170         file *ast.File
171
172         // pos is the position at which the request was triggered.
173         pos token.Pos
174
175         // path is the path of AST nodes enclosing the position.
176         path []ast.Node
177
178         // seen is the map that ensures we do not return duplicate results.
179         seen map[types.Object]bool
180
181         // items is the list of completion items returned.
182         items []CompletionItem
183
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
188
189         // surrounding describes the identifier surrounding the position.
190         surrounding *Selection
191
192         // inference contains information we've inferred about ideal
193         // candidates such as the candidate's type.
194         inference candidateInference
195
196         // enclosingFunc contains information about the function enclosing
197         // the position.
198         enclosingFunc *funcInfo
199
200         // enclosingCompositeLiteral contains information about the composite literal
201         // enclosing the position.
202         enclosingCompositeLiteral *compLitInfo
203
204         // deepState contains the current state of our deep completion search.
205         deepState deepCompletionState
206
207         // matcher matches the candidates against the surrounding prefix.
208         matcher matcher
209
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
214
215         // mapper converts the positions in the file from which the completion originated.
216         mapper *protocol.ColumnMapper
217
218         // startTime is when we started processing this completion request. It does
219         // not include any time the request spent in the queue.
220         startTime time.Time
221 }
222
223 // funcInfo holds info about a function object.
224 type funcInfo struct {
225         // sig is the function declaration enclosing the position.
226         sig *types.Signature
227
228         // body is the function's body.
229         body *ast.BlockStmt
230 }
231
232 type compLitInfo struct {
233         // cl is the *ast.CompositeLit enclosing the position.
234         cl *ast.CompositeLit
235
236         // clType is the type of cl.
237         clType types.Type
238
239         // kv is the *ast.KeyValueExpr enclosing the position, if any.
240         kv *ast.KeyValueExpr
241
242         // inKey is true if we are certain the position is in the key side
243         // of a key-value pair.
244         inKey bool
245
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
251 }
252
253 type importInfo struct {
254         importPath string
255         name       string
256         pkg        source.Package
257 }
258
259 type methodSetKey struct {
260         typ         types.Type
261         addressable bool
262 }
263
264 type completionContext struct {
265         // triggerCharacter is the character used to trigger completion at current
266         // position, if any.
267         triggerCharacter string
268
269         // triggerKind is information about how a completion was triggered.
270         triggerKind protocol.CompletionTriggerKind
271
272         // commentCompletion is true if we are completing a comment.
273         commentCompletion bool
274
275         // packageCompletion is true if we are completing a package name.
276         packageCompletion bool
277 }
278
279 // A Selection represents the cursor position and surrounding identifier.
280 type Selection struct {
281         content string
282         cursor  token.Pos
283         source.MappedRange
284 }
285
286 func (p Selection) Content() string {
287         return p.content
288 }
289
290 func (p Selection) Start() token.Pos {
291         return p.MappedRange.SpanRange().Start
292 }
293
294 func (p Selection) End() token.Pos {
295         return p.MappedRange.SpanRange().End
296 }
297
298 func (p Selection) Prefix() string {
299         return p.content[:p.cursor-p.SpanRange().Start]
300 }
301
302 func (p Selection) Suffix() string {
303         return p.content[p.cursor-p.SpanRange().Start:]
304 }
305
306 func (c *completer) setSurrounding(ident *ast.Ident) {
307         if c.surrounding != nil {
308                 return
309         }
310         if !(ident.Pos() <= c.pos && c.pos <= ident.End()) {
311                 return
312         }
313
314         c.surrounding = &Selection{
315                 content: ident.Name,
316                 cursor:  c.pos,
317                 // Overwrite the prefix only.
318                 MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, ident.Pos(), ident.End()),
319         }
320
321         c.setMatcherFromPrefix(c.surrounding.Prefix())
322 }
323
324 func (c *completer) setMatcherFromPrefix(prefix string) {
325         switch c.opts.matcher {
326         case source.Fuzzy:
327                 c.matcher = fuzzy.NewMatcher(prefix)
328         case source.CaseSensitive:
329                 c.matcher = prefixMatcher(prefix)
330         default:
331                 c.matcher = insensitivePrefixMatcher(strings.ToLower(prefix))
332         }
333 }
334
335 func (c *completer) getSurrounding() *Selection {
336         if c.surrounding == nil {
337                 c.surrounding = &Selection{
338                         content:     "",
339                         cursor:      c.pos,
340                         MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, c.pos, c.pos),
341                 }
342         }
343         return c.surrounding
344 }
345
346 // candidate represents a completion candidate.
347 type candidate struct {
348         // obj is the types.Object to complete to.
349         obj types.Object
350
351         // score is used to rank candidates.
352         score float64
353
354         // name is the deep object name path, e.g. "foo.bar"
355         name string
356
357         // detail is additional information about this item. If not specified,
358         // defaults to type string for the object.
359         detail string
360
361         // path holds the path from the search root (excluding the candidate
362         // itself) for a deep candidate.
363         path []types.Object
364
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.
368         names []string
369
370         // expandFuncCall is true if obj should be invoked in the completion.
371         // For example, expandFuncCall=true yields "foo()", expandFuncCall=false yields "foo".
372         expandFuncCall bool
373
374         // takeAddress is true if the completion should take a pointer to obj.
375         // For example, takeAddress=true yields "&foo", takeAddress=false yields "foo".
376         takeAddress bool
377
378         // addressable is true if a pointer can be taken to the candidate.
379         addressable bool
380
381         // makePointer is true if the candidate type name T should be made into *T.
382         makePointer bool
383
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.
386         dereference int
387
388         // variadic is true if this candidate fills a variadic param and
389         // needs "..." appended.
390         variadic bool
391
392         // convertTo is a type that this candidate should be cast to. For
393         // example, if convertTo is float64, "foo" should be formatted as
394         // "float64(foo)".
395         convertTo types.Type
396
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.
399         imp *importInfo
400 }
401
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
404 // being defined.
405 type ErrIsDefinition struct {
406         objStr string
407 }
408
409 func (e ErrIsDefinition) Error() string {
410         msg := "this is a definition"
411         if e.objStr != "" {
412                 msg += " of " + e.objStr
413         }
414         return msg
415 }
416
417 // Completion returns a list of possible candidates for completion, given a
418 // a file and a position.
419 //
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")
425         defer done()
426
427         startTime := time.Now()
428
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)
437                 if innerErr != nil {
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)
440                 }
441                 return items, surrounding, nil
442         }
443         spn, err := pgf.Mapper.PointSpan(protoPos)
444         if err != nil {
445                 return nil, nil, err
446         }
447         rng, err := spn.Range(pgf.Mapper.Converter)
448         if err != nil {
449                 return nil, nil, err
450         }
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)
454         if path == nil {
455                 return nil, nil, errors.Errorf("cannot find node enclosing position")
456         }
457
458         pos := rng.Start
459
460         // Check if completion at this position is valid. If not, return early.
461         switch n := path[0].(type) {
462         case *ast.BasicLit:
463                 // Skip completion inside literals except for ImportSpec
464                 if len(path) > 1 {
465                         if _, ok := path[1].(*ast.ImportSpec); ok {
466                                 break
467                         }
468                 }
469                 return nil, nil, nil
470         case *ast.CallExpr:
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...<>").
474                         return nil, nil, nil
475                 }
476         case *ast.Ident:
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.
483                                 break
484                         } else {
485                                 objStr := ""
486                                 if obj != nil {
487                                         qual := types.RelativeTo(pkg.GetTypes())
488                                         objStr = types.ObjectString(obj, qual)
489                                 }
490                                 return nil, nil, ErrIsDefinition{objStr: objStr}
491                         }
492                 }
493         }
494
495         opts := snapshot.View().Options()
496         c := &completer{
497                 pkg:      pkg,
498                 snapshot: snapshot,
499                 qf:       source.Qualifier(pgf.File, pkg.GetTypes(), pkg.GetTypesInfo()),
500                 completionContext: completionContext{
501                         triggerCharacter: protoContext.TriggerCharacter,
502                         triggerKind:      protoContext.TriggerKind,
503                 },
504                 fh:                        fh,
505                 filename:                  fh.URI().Filename(),
506                 file:                      pgf.File,
507                 path:                      path,
508                 pos:                       pos,
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,
514                 },
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,
524                 },
525                 // default to a matcher that always matches
526                 matcher:        prefixMatcher(""),
527                 methodSetCache: make(map[methodSetKey]*types.MethodSet),
528                 mapper:         pgf.Mapper,
529                 startTime:      startTime,
530         }
531
532         var cancel context.CancelFunc
533         if c.opts.budget == 0 {
534                 ctx, cancel = context.WithCancel(ctx)
535         } else {
536                 // timeoutDuration is the completion budget remaining. If less than
537                 // 10ms, set to 10ms
538                 timeoutDuration := time.Until(c.startTime.Add(c.opts.budget))
539                 if timeoutDuration < 10*time.Millisecond {
540                         timeoutDuration = 10 * time.Millisecond
541                 }
542                 ctx, cancel = context.WithTimeout(ctx, timeoutDuration)
543         }
544         defer cancel()
545
546         if surrounding := c.containingIdent(pgf.Src); surrounding != nil {
547                 c.setSurrounding(surrounding)
548         }
549
550         c.inference = expectedCandidate(ctx, c)
551
552         err = c.collectCompletions(ctx)
553         if err != nil {
554                 return nil, nil, err
555         }
556
557         // Deep search collected candidates and their members for more candidates.
558         c.deepSearch(ctx)
559         c.deepState.searchQueue = nil
560
561         for _, callback := range c.completionCallbacks {
562                 if err := c.snapshot.RunProcessEnvFunc(ctx, callback); err != nil {
563                         return nil, nil, err
564                 }
565         }
566
567         // Search candidates populated by expensive operations like
568         // unimportedMembers etc. for more completion items.
569         c.deepSearch(ctx)
570
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()
575
576         c.sortItems()
577         return c.items, c.getSurrounding(), nil
578 }
579
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()) {
586                         continue
587                 }
588                 return c.populateImportCompletions(ctx, importSpec)
589         }
590
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)
595                         return nil
596                 }
597         }
598
599         // Struct literals are handled entirely separately.
600         if c.wantStructFieldCompletions() {
601                 // If we are definitely completing a struct field name, deep completions
602                 // don't make sense.
603                 if c.enclosingCompositeLiteral.inKey {
604                         c.deepState.enabled = false
605                 }
606                 return c.structLiteralFieldName(ctx)
607         }
608
609         if lt := c.wantLabelCompletion(); lt != labelNone {
610                 c.labels(lt)
611                 return nil
612         }
613
614         if c.emptySwitchStmt() {
615                 // Empty switch statements only admit "default" and "case" keywords.
616                 c.addKeywordItems(map[string]bool{}, highScore, CASE, DEFAULT)
617                 return nil
618         }
619
620         switch n := c.path[0].(type) {
621         case *ast.Ident:
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)
627                 }
628                 return c.lexical(ctx)
629         // The function name hasn't been typed yet, but the parens are there:
630         //   recv.‸(arg)
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()
639         default:
640                 // fallback to lexical completions
641                 return c.lexical(ctx)
642         }
643
644         return nil
645 }
646
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 {
653                 return ident
654         }
655
656         pos, tkn, lit := c.scanToken(src)
657         if !pos.IsValid() {
658                 return nil
659         }
660
661         fakeIdent := &ast.Ident{Name: lit, NamePos: pos}
662
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.
666                 return fakeIdent
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
670                 // extracted token.
671                 return fakeIdent
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<>)".
676                 return fakeIdent
677         }
678
679         return nil
680 }
681
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)
685
686         var s scanner.Scanner
687         s.Init(tok, contents, nil, 0)
688         for {
689                 tknPos, tkn, lit := s.Scan()
690                 if tkn == token.EOF || tknPos >= c.pos {
691                         return token.NoPos, token.ILLEGAL, ""
692                 }
693
694                 if len(lit) > 0 && tknPos <= c.pos && c.pos <= tknPos+token.Pos(len(lit)) {
695                         return tknPos, tkn, lit
696                 }
697         }
698 }
699
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
705                 }
706
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
710         })
711 }
712
713 // emptySwitchStmt reports whether pos is in an empty switch or select
714 // statement.
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 {
718                 return false
719         }
720
721         switch c.path[1].(type) {
722         case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt:
723                 return true
724         default:
725                 return false
726         }
727 }
728
729 // populateImportCompletions yields completions for an import path around the cursor.
730 //
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, `"`) {
739                 return nil
740         }
741
742         // deepSearch is not valuable for import completions.
743         c.deepState.enabled = false
744
745         importPath := searchImport.Path.Value
746
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], `"`)
751
752         // The number of directories in the import path gives us the depth at
753         // which to search.
754         depth := len(strings.Split(prefix, "/")) - 1
755
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:]
764                 start++
765                 if depth > 0 {
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
769                         // "golang.org/x/".
770                         path := strings.SplitAfter(prefix, "/")
771                         numChars := len(strings.Join(path[:len(path)-1], ""))
772                         content = content[numChars:]
773                         start += token.Pos(numChars)
774                 }
775                 namePrefix = ""
776         }
777
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() {
782                 end--
783                 content = content[:len(content)-1]
784                 nameSuffix = ""
785         }
786
787         c.surrounding = &Selection{
788                 content:     content,
789                 cursor:      c.pos,
790                 MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, start, end),
791         }
792
793         seenImports := make(map[string]struct{})
794         for _, importSpec := range c.file.Imports {
795                 if importSpec.Path.Value == importPath {
796                         continue
797                 }
798                 seenImportPath, err := strconv.Unquote(importSpec.Path.Value)
799                 if err != nil {
800                         return err
801                 }
802                 seenImports[seenImportPath] = struct{}{}
803         }
804
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 {
810                         return
811                 }
812
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 {
817                         return
818                 }
819                 pkgToConsider := strings.Join(pkgDirList[:depth+1], "/")
820
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 == `"` {
825                         name = pkgToConsider
826                 }
827
828                 score := pkg.Relevance
829                 if len(pkgDirList)-1 == depth {
830                         score *= highScore
831                 } else {
832                         // For incomplete package paths, add a terminal slash to indicate that the
833                         // user should keep triggering completions.
834                         name += "/"
835                         pkgToConsider += "/"
836                 }
837
838                 if _, ok := seen[pkgToConsider]; ok {
839                         return
840                 }
841                 seen[pkgToConsider] = struct{}{}
842
843                 mu.Lock()
844                 defer mu.Unlock()
845
846                 name = namePrefix + name + nameSuffix
847                 obj := types.NewPkgName(0, nil, name, types.NewPackage(pkgToConsider, name))
848                 c.deepState.enqueue(candidate{
849                         obj:    obj,
850                         detail: fmt.Sprintf("%q", pkgToConsider),
851                         score:  score,
852                 })
853         }
854
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)
857         })
858         return nil
859 }
860
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 == "." {
866                 return
867         }
868
869         // Using the comment position find the line after
870         file := c.snapshot.FileSet().File(comment.End())
871         if file == nil {
872                 return
873         }
874
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
879
880         // Documentation isn't useful in comments, since it might end up being the
881         // comment itself.
882         c.opts.documentation = false
883
884         commentLine := file.Line(comment.End())
885
886         // comment is valid, set surrounding as word boundaries around cursor
887         c.setSurroundingForComment(comment)
888
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()) {
895                         continue
896                 }
897                 switch node := n.(type) {
898                 // handle const, vars, and types
899                 case *ast.GenDecl:
900                         for _, spec := range node.Specs {
901                                 switch spec := spec.(type) {
902                                 case *ast.ValueSpec:
903                                         for _, name := range spec.Names {
904                                                 if name.String() == "_" {
905                                                         continue
906                                                 }
907                                                 obj := c.pkg.GetTypesInfo().ObjectOf(name)
908                                                 c.deepState.enqueue(candidate{obj: obj, score: stdScore})
909                                         }
910                                 case *ast.TypeSpec:
911                                         // add TypeSpec fields to completion
912                                         switch typeNode := spec.Type.(type) {
913                                         case *ast.StructType:
914                                                 c.addFieldItems(ctx, typeNode.Fields)
915                                         case *ast.FuncType:
916                                                 c.addFieldItems(ctx, typeNode.Params)
917                                                 c.addFieldItems(ctx, typeNode.Results)
918                                         case *ast.InterfaceType:
919                                                 c.addFieldItems(ctx, typeNode.Methods)
920                                         }
921
922                                         if spec.Name.String() == "_" {
923                                                 continue
924                                         }
925
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 {
932                                                 score = highScore
933                                         }
934
935                                         c.deepState.enqueue(candidate{obj: obj, score: score})
936                                 }
937                         }
938                 // handle functions
939                 case *ast.FuncDecl:
940                         c.addFieldItems(ctx, node.Recv)
941                         c.addFieldItems(ctx, node.Type.Params)
942                         c.addFieldItems(ctx, node.Type.Results)
943
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)
949                                                 if obj == nil {
950                                                         continue
951                                                 }
952
953                                                 recvType := obj.Type().Underlying()
954                                                 if ptr, ok := recvType.(*types.Pointer); ok {
955                                                         recvType = ptr.Elem()
956                                                 }
957                                                 recvStruct, ok := recvType.Underlying().(*types.Struct)
958                                                 if !ok {
959                                                         continue
960                                                 }
961                                                 for i := 0; i < recvStruct.NumFields(); i++ {
962                                                         field := recvStruct.Field(i)
963                                                         c.deepState.enqueue(candidate{obj: field, score: lowScore})
964                                                 }
965                                         }
966                                 }
967                         }
968
969                         if node.Name.String() == "_" {
970                                 continue
971                         }
972
973                         obj := c.pkg.GetTypesInfo().ObjectOf(node.Name)
974                         if obj == nil || obj.Pkg() != nil && obj.Pkg() != c.pkg.GetTypes() {
975                                 continue
976                         }
977
978                         c.deepState.enqueue(candidate{obj: obj, score: highScore})
979                 }
980         }
981 }
982
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
989                         break
990                 }
991         }
992         // if cursor isn't in the comment
993         if cursorComment == nil {
994                 return
995         }
996
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]) {
1001                 start--
1002         }
1003         for end < len(cursorComment.Text) && isValidIdentifierChar(cursorComment.Text[end]) {
1004                 end++
1005         }
1006
1007         c.surrounding = &Selection{
1008                 content: cursorComment.Text[start:end],
1009                 cursor:  c.pos,
1010                 MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper,
1011                         token.Pos(int(cursorComment.Slash)+start), token.Pos(int(cursorComment.Slash)+end)),
1012         }
1013         c.setMatcherFromPrefix(c.surrounding.Prefix())
1014 }
1015
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 == '_'
1021 }
1022
1023 // adds struct fields, interface methods, function declaration fields to completion
1024 func (c *completer) addFieldItems(ctx context.Context, fields *ast.FieldList) {
1025         if fields == nil {
1026                 return
1027         }
1028
1029         cursor := c.surrounding.cursor
1030         for _, field := range fields.List {
1031                 for _, name := range field.Names {
1032                         if name.String() == "_" {
1033                                 continue
1034                         }
1035                         obj := c.pkg.GetTypesInfo().ObjectOf(name)
1036                         if obj == nil {
1037                                 continue
1038                         }
1039
1040                         // if we're in a field comment/doc, score that field as more relevant
1041                         score := stdScore
1042                         if field.Comment != nil && field.Comment.Pos() <= cursor && cursor <= field.Comment.End() {
1043                                 score = highScore
1044                         } else if field.Doc != nil && field.Doc.Pos() <= cursor && cursor <= field.Doc.End() {
1045                                 score = highScore
1046                         }
1047
1048                         c.deepState.enqueue(candidate{obj: obj, score: score})
1049                 }
1050         }
1051 }
1052
1053 func (c *completer) wantStructFieldCompletions() bool {
1054         clInfo := c.enclosingCompositeLiteral
1055         if clInfo == nil {
1056                 return false
1057         }
1058
1059         return clInfo.isStruct() && (clInfo.inKey || clInfo.maybeInFieldName)
1060 }
1061
1062 func (c *completer) wantTypeName() bool {
1063         return !c.completionContext.commentCompletion && c.inference.typeName.wantTypeName
1064 }
1065
1066 // See https://golang.org/issue/36001. Unimported completions are expensive.
1067 const (
1068         maxUnimportedPackageNames = 5
1069         unimportedMemberTarget    = 100
1070 )
1071
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)
1075
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() {
1082                                         pkg = imp
1083                                 }
1084                         }
1085                         // If the package is not imported, try searching for unimported
1086                         // completions.
1087                         if pkg == nil && c.opts.unimported {
1088                                 if err := c.unimportedMembers(ctx, id); err != nil {
1089                                         return err
1090                                 }
1091                         }
1092                         candidates := c.packageMembers(pkgName.Imported(), stdScore, nil)
1093                         for _, cand := range candidates {
1094                                 c.deepState.enqueue(cand)
1095                         }
1096                         return nil
1097                 }
1098         }
1099
1100         // Invariant: sel is a true selector.
1101         tv, ok := c.pkg.GetTypesInfo().Types[sel.X]
1102         if ok {
1103                 candidates := c.methodsAndFields(tv.Type, tv.Addressable(), nil)
1104                 for _, cand := range candidates {
1105                         c.deepState.enqueue(cand)
1106                 }
1107                 return nil
1108         }
1109
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 {
1113                         return err
1114                 }
1115         }
1116         return nil
1117 }
1118
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)
1122         if err != nil {
1123                 return err
1124         }
1125
1126         var paths []string
1127         for path, pkg := range known {
1128                 if pkg.GetTypes().Name() != id.Name {
1129                         continue
1130                 }
1131                 paths = append(paths, path)
1132         }
1133
1134         var relevances map[string]float64
1135         if len(paths) != 0 {
1136                 if err := c.snapshot.RunProcessEnvFunc(ctx, func(opts *imports.Options) error {
1137                         var err error
1138                         relevances, err = imports.ScoreImportPaths(ctx, opts.Env, paths)
1139                         return err
1140                 }); err != nil {
1141                         return err
1142                 }
1143         }
1144         sort.Slice(paths, func(i, j int) bool {
1145                 return relevances[paths[i]] > relevances[paths[j]]
1146         })
1147
1148         for _, path := range paths {
1149                 pkg := known[path]
1150                 if pkg.GetTypes().Name() != id.Name {
1151                         continue
1152                 }
1153                 imp := &importInfo{
1154                         importPath: path,
1155                         pkg:        pkg,
1156                 }
1157                 if imports.ImportPathToAssumedName(path) != pkg.GetTypes().Name() {
1158                         imp.name = pkg.GetTypes().Name()
1159                 }
1160                 candidates := c.packageMembers(pkg.GetTypes(), unimportedScore(relevances[path]), imp)
1161                 for _, cand := range candidates {
1162                         c.deepState.enqueue(cand)
1163                 }
1164                 if len(c.items) >= unimportedMemberTarget {
1165                         return nil
1166                 }
1167         }
1168
1169         ctx, cancel := context.WithCancel(ctx)
1170
1171         var mu sync.Mutex
1172         add := func(pkgExport imports.PackageExport) {
1173                 mu.Lock()
1174                 defer mu.Unlock()
1175                 if _, ok := known[pkgExport.Fix.StmtInfo.ImportPath]; ok {
1176                         return // We got this one above.
1177                 }
1178
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),
1185                                 score: score,
1186                                 imp: &importInfo{
1187                                         importPath: pkgExport.Fix.StmtInfo.ImportPath,
1188                                         name:       pkgExport.Fix.StmtInfo.Name,
1189                                 },
1190                         })
1191                 }
1192                 if len(c.items) >= unimportedMemberTarget {
1193                         cancel()
1194                 }
1195         }
1196
1197         c.completionCallbacks = append(c.completionCallbacks, func(opts *imports.Options) error {
1198                 defer cancel()
1199                 return imports.GetPackageExports(ctx, add, id.Name, c.filename, c.pkg.GetTypes().Name(), opts.Env)
1200         })
1201         return nil
1202 }
1203
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
1208 }
1209
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{
1216                         obj:         obj,
1217                         score:       score,
1218                         imp:         imp,
1219                         addressable: isVar(obj),
1220                 })
1221         }
1222         return candidates
1223 }
1224
1225 func (c *completer) methodsAndFields(typ types.Type, addressable bool, imp *importInfo) []candidate {
1226         mset := c.methodSetCache[methodSetKey{typ, addressable}]
1227         if mset == nil {
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))
1231                 } else {
1232                         // Add methods of T.
1233                         mset = types.NewMethodSet(typ)
1234                 }
1235                 c.methodSetCache[methodSetKey{typ, addressable}] = mset
1236         }
1237
1238         var candidates []candidate
1239         for i := 0; i < mset.Len(); i++ {
1240                 candidates = append(candidates, candidate{
1241                         obj:         mset.At(i).Obj(),
1242                         score:       stdScore,
1243                         imp:         imp,
1244                         addressable: addressable || isPointer(typ),
1245                 })
1246         }
1247
1248         // Add fields of T.
1249         eachField(typ, func(v *types.Var) {
1250                 candidates = append(candidates, candidate{
1251                         obj:         v,
1252                         score:       stdScore - 0.01,
1253                         imp:         imp,
1254                         addressable: addressable || isPointer(typ),
1255                 })
1256         })
1257
1258         return candidates
1259 }
1260
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)
1265
1266         var (
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")
1274         )
1275
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{})
1279
1280         // Process scopes innermost first.
1281         for i, scope := range scopes {
1282                 if scope == nil {
1283                         continue
1284                 }
1285
1286         Names:
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.
1291                         }
1292                         if obj == builtinComparable {
1293                                 continue
1294                         }
1295
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.
1301                                 var node ast.Node
1302                                 if i < len(c.path) {
1303                                         node = c.path[i]
1304                                 } else if i == len(c.path) { // use the *ast.File for package scope
1305                                         node = c.path[i-1]
1306                                 }
1307                                 if node != nil {
1308                                         if resolved := resolveInvalid(c.snapshot.FileSet(), obj, node, c.pkg.GetTypesInfo()); resolved != nil {
1309                                                 obj = resolved
1310                                         }
1311                                 }
1312                         }
1313
1314                         // Don't use LHS of decl in RHS.
1315                         for _, ident := range enclosingDeclLHS(c.path) {
1316                                 if obj.Pos() == ident.Pos() {
1317                                         continue Names
1318                                 }
1319                         }
1320
1321                         // Don't suggest "iota" outside of const decls.
1322                         if obj == builtinIota && !c.inConstDecl() {
1323                                 continue
1324                         }
1325
1326                         // Rank outer scopes lower than inner.
1327                         score := stdScore * math.Pow(.99, float64(i))
1328
1329                         // Dowrank "nil" a bit so it is ranked below more interesting candidates.
1330                         if obj == builtinNil {
1331                                 score /= 2
1332                         }
1333
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{
1338                                         obj:         obj,
1339                                         score:       score,
1340                                         addressable: isVar(obj),
1341                                 })
1342                         }
1343                 }
1344         }
1345
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.
1351
1352                         if named.Obj() != nil && named.Obj().Pkg() != nil {
1353                                 pkg := named.Obj().Pkg()
1354
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)
1360                                         imp := &importInfo{
1361                                                 importPath: pkg.Path(),
1362                                         }
1363                                         if imports.ImportPathToAssumedName(pkg.Path()) != pkg.Name() {
1364                                                 imp.name = pkg.Name()
1365                                         }
1366                                         c.deepState.enqueue(candidate{
1367                                                 obj:   obj,
1368                                                 score: stdScore,
1369                                                 imp:   imp,
1370                                         })
1371                                 }
1372                         }
1373                 }
1374         }
1375
1376         if c.opts.unimported {
1377                 if err := c.unimportedPackages(ctx, seen); err != nil {
1378                         return err
1379                 }
1380         }
1381
1382         if t := c.inference.objType; t != nil {
1383                 t = source.Deref(t)
1384
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
1388                 // them.
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)
1393
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),
1400                                         score: stdScore,
1401                                 }
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)
1406                                 }
1407                         }
1408                 }
1409         }
1410
1411         // Add keyword completion items appropriate in the current context.
1412         c.addKeywordCompletions()
1413
1414         return nil
1415 }
1416
1417 func (c *completer) unimportedPackages(ctx context.Context, seen map[string]struct{}) error {
1418         var prefix string
1419         if c.surrounding != nil {
1420                 prefix = c.surrounding.Prefix()
1421         }
1422         count := 0
1423
1424         known, err := c.snapshot.CachedImportPaths(ctx)
1425         if err != nil {
1426                 return err
1427         }
1428         var paths []string
1429         for path, pkg := range known {
1430                 if !strings.HasPrefix(pkg.GetTypes().Name(), prefix) {
1431                         continue
1432                 }
1433                 paths = append(paths, path)
1434         }
1435
1436         var relevances map[string]float64
1437         if len(paths) != 0 {
1438                 if err := c.snapshot.RunProcessEnvFunc(ctx, func(opts *imports.Options) error {
1439                         var err error
1440                         relevances, err = imports.ScoreImportPaths(ctx, opts.Env, paths)
1441                         return err
1442                 }); err != nil {
1443                         return err
1444                 }
1445         }
1446         sort.Slice(paths, func(i, j int) bool {
1447                 return relevances[paths[i]] > relevances[paths[j]]
1448         })
1449
1450         for _, path := range paths {
1451                 pkg := known[path]
1452                 if _, ok := seen[pkg.GetTypes().Name()]; ok {
1453                         continue
1454                 }
1455                 imp := &importInfo{
1456                         importPath: path,
1457                         pkg:        pkg,
1458                 }
1459                 if imports.ImportPathToAssumedName(path) != pkg.GetTypes().Name() {
1460                         imp.name = pkg.GetTypes().Name()
1461                 }
1462                 if count >= maxUnimportedPackageNames {
1463                         return nil
1464                 }
1465                 c.deepState.enqueue(candidate{
1466                         obj:   types.NewPkgName(0, nil, pkg.GetTypes().Name(), pkg.GetTypes()),
1467                         score: unimportedScore(relevances[path]),
1468                         imp:   imp,
1469                 })
1470                 count++
1471         }
1472
1473         ctx, cancel := context.WithCancel(ctx)
1474
1475         var mu sync.Mutex
1476         add := func(pkg imports.ImportFix) {
1477                 mu.Lock()
1478                 defer mu.Unlock()
1479                 if _, ok := seen[pkg.IdentName]; ok {
1480                         return
1481                 }
1482                 if _, ok := relevances[pkg.StmtInfo.ImportPath]; ok {
1483                         return
1484                 }
1485
1486                 if count >= maxUnimportedPackageNames {
1487                         cancel()
1488                         return
1489                 }
1490
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{
1496                         obj:   obj,
1497                         score: unimportedScore(pkg.Relevance),
1498                         imp: &importInfo{
1499                                 importPath: pkg.StmtInfo.ImportPath,
1500                                 name:       pkg.StmtInfo.Name,
1501                         },
1502                 })
1503                 count++
1504         }
1505         c.completionCallbacks = append(c.completionCallbacks, func(opts *imports.Options) error {
1506                 defer cancel()
1507                 return imports.GetAllCandidates(ctx, add, prefix, c.filename, c.pkg.GetTypes().Name(), opts.Env)
1508         })
1509         return nil
1510 }
1511
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 {
1516                         return true
1517                 }
1518         }
1519         return false
1520 }
1521
1522 func (c *completer) inConstDecl() bool {
1523         for _, n := range c.path {
1524                 if decl, ok := n.(*ast.GenDecl); ok && decl.Tok == token.CONST {
1525                         return true
1526                 }
1527         }
1528         return false
1529 }
1530
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
1534
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 {
1541                                 continue
1542                         }
1543
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
1548                                         }
1549                                 }
1550                         }
1551                 }
1552         }
1553
1554         deltaScore := 0.0001
1555         switch t := clInfo.clType.(type) {
1556         case *types.Struct:
1557                 for i := 0; i < t.NumFields(); i++ {
1558                         field := t.Field(i)
1559                         if !addedFields[field] {
1560                                 c.deepState.enqueue(candidate{
1561                                         obj:   field,
1562                                         score: highScore - float64(i)*deltaScore,
1563                                 })
1564                         }
1565                 }
1566
1567                 // Add lexical completions if we aren't certain we are in the key part of a
1568                 // key-value pair.
1569                 if clInfo.maybeInFieldName {
1570                         return c.lexical(ctx)
1571                 }
1572         default:
1573                 return c.lexical(ctx)
1574         }
1575
1576         return nil
1577 }
1578
1579 func (cl *compLitInfo) isStruct() bool {
1580         _, ok := cl.clType.(*types.Struct)
1581         return ok
1582 }
1583
1584 // enclosingCompositeLiteral returns information about the composite literal enclosing the
1585 // position.
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, <>})
1593                         //
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<>{}}".
1599                                 break
1600                         }
1601
1602                         tv, ok := info.Types[n]
1603                         if !ok {
1604                                 return nil
1605                         }
1606
1607                         clInfo := compLitInfo{
1608                                 cl:     n,
1609                                 clType: source.Deref(tv.Type).Underlying(),
1610                         }
1611
1612                         var (
1613                                 expr    ast.Expr
1614                                 hasKeys bool
1615                         )
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() {
1619                                         expr = el
1620                                 }
1621
1622                                 if kv, ok := el.(*ast.KeyValueExpr); ok {
1623                                         hasKeys = true
1624                                         // If expr == el then we know the position falls in this expression,
1625                                         // so also record kv as the enclosing *ast.KeyValueExpr.
1626                                         if expr == el {
1627                                                 clInfo.kv = kv
1628                                                 break
1629                                         }
1630                                 }
1631                         }
1632
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
1637                         } else if hasKeys {
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, <>}").
1641                                 clInfo.inKey = true
1642                         } else {
1643                                 switch clInfo.clType.(type) {
1644                                 case *types.Struct:
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)
1655                                         }
1656                                 case *types.Map:
1657                                         // If we aren't in a *ast.KeyValueExpr we must be adding a new key
1658                                         // to the map.
1659                                         clInfo.inKey = true
1660                                 }
1661                         }
1662
1663                         return &clInfo
1664                 default:
1665                         if breaksExpectedTypeInference(n, pos) {
1666                                 return nil
1667                         }
1668                 }
1669         }
1670
1671         return nil
1672 }
1673
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) {
1679                 case *ast.FuncDecl:
1680                         if obj, ok := info.Defs[t.Name]; ok {
1681                                 return &funcInfo{
1682                                         sig:  obj.Type().(*types.Signature),
1683                                         body: t.Body,
1684                                 }
1685                         }
1686                 case *ast.FuncLit:
1687                         if typ, ok := info.Types[t]; ok {
1688                                 return &funcInfo{
1689                                         sig:  typ.Type.(*types.Signature),
1690                                         body: t.Body,
1691                                 }
1692                         }
1693                 }
1694         }
1695         return nil
1696 }
1697
1698 func (c *completer) expectedCompositeLiteralType() types.Type {
1699         clInfo := c.enclosingCompositeLiteral
1700         switch t := clInfo.clType.(type) {
1701         case *types.Slice:
1702                 if clInfo.inKey {
1703                         return types.Typ[types.UntypedInt]
1704                 }
1705                 return t.Elem()
1706         case *types.Array:
1707                 if clInfo.inKey {
1708                         return types.Typ[types.UntypedInt]
1709                 }
1710                 return t.Elem()
1711         case *types.Map:
1712                 if clInfo.inKey {
1713                         return t.Key()
1714                 }
1715                 return t.Elem()
1716         case *types.Struct:
1717                 // If we are completing a key (i.e. field name), there is no expected type.
1718                 if clInfo.inKey {
1719                         return nil
1720                 }
1721
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 {
1728                                                 return field.Type()
1729                                         }
1730                                 }
1731                         }
1732                 } else {
1733                         // If we aren't in a key-value pair and aren't in the key, we must be using
1734                         // implicit field names.
1735
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()
1740                         }
1741                 }
1742         }
1743         return nil
1744 }
1745
1746 // typeModifier represents an operator that changes the expected type.
1747 type typeModifier struct {
1748         mod      typeMod
1749         arrayLen int64
1750 }
1751
1752 type typeMod int
1753
1754 const (
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")
1760 )
1761
1762 type objKind int
1763
1764 const (
1765         kindAny   objKind = 0
1766         kindArray objKind = 1 << iota
1767         kindSlice
1768         kindChan
1769         kindMap
1770         kindStruct
1771         kindString
1772         kindInt
1773         kindBool
1774         kindBytes
1775         kindPtr
1776         kindFloat
1777         kindComplex
1778         kindError
1779         kindStringer
1780         kindFunc
1781 )
1782
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).
1790         penalty float64
1791 }
1792
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.
1797         objType types.Type
1798
1799         // objKind is a mask of expected kinds of types such as "map", "slice", etc.
1800         objKind objKind
1801
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
1806         variadic bool
1807
1808         // modifiers are prefixes such as "*", "&" or "<-" that influence how
1809         // a candidate type relates to the expected type.
1810         modifiers []typeModifier
1811
1812         // convertibleTo is a type our candidate type must be convertible to.
1813         convertibleTo types.Type
1814
1815         // typeName holds information about the expected type name at
1816         // position, if any.
1817         typeName typeNameInference
1818
1819         // assignees are the types that would receive a function call's
1820         // results at the position. For example:
1821         //
1822         // foo := 123
1823         // foo, bar := <>
1824         //
1825         // at "<>", the assignees are [int, <invalid>].
1826         assignees []types.Type
1827
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:
1831         //
1832         // func foo(int, ...string) {}
1833         //
1834         // foo(<>)         // variadicAssignees=true
1835         // foo(bar<>)      // variadicAssignees=true
1836         // foo(bar, baz<>) // variadicAssignees=false
1837         variadicAssignees bool
1838
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
1845
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
1850 }
1851
1852 // typeNameInference holds information about the expected type name at
1853 // position.
1854 type typeNameInference struct {
1855         // wantTypeName is true if we expect the name of a type.
1856         wantTypeName bool
1857
1858         // modifiers are prefixes such as "*", "&" or "<-" that influence how
1859         // a candidate type relates to the expected type.
1860         modifiers []typeModifier
1861
1862         // assertableFrom is a type that must be assertable to our candidate type.
1863         assertableFrom types.Type
1864
1865         // wantComparable is true if we want a comparable type.
1866         wantComparable bool
1867
1868         // seenTypeSwitchCases tracks types that have already been used by
1869         // the containing type switch.
1870         seenTypeSwitchCases []types.Type
1871
1872         // compLitType is true if we are completing a composite literal type
1873         // name, e.g "foo<>{}".
1874         compLitType bool
1875 }
1876
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)
1881
1882         if c.enclosingCompositeLiteral != nil {
1883                 inf.objType = c.expectedCompositeLiteralType()
1884         }
1885
1886 Nodes:
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.
1891                         e := node.X
1892                         if c.pos < node.OpPos {
1893                                 e = node.Y
1894                         }
1895                         if tv, ok := c.pkg.GetTypesInfo().Types[e]; ok {
1896                                 switch node.Op {
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
1900                                         // candidates.
1901                                 default:
1902                                         inf.objType = tv.Type
1903                                 }
1904                                 break Nodes
1905                         }
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
1912                                 }
1913                                 if tv, ok := c.pkg.GetTypesInfo().Types[node.Lhs[i]]; ok {
1914                                         inf.objType = tv.Type
1915                                 }
1916
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))
1923                                         }
1924                                 } else {
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]))
1929                                 }
1930                         }
1931                         return inf
1932                 case *ast.ValueSpec:
1933                         if node.Type != nil && c.pos > node.Type.End() {
1934                                 inf.objType = c.pkg.GetTypesInfo().TypeOf(node.Type)
1935                         }
1936                         return inf
1937                 case *ast.CallExpr:
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
1944                                         break Nodes
1945                                 }
1946
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()
1950                                                 if numParams == 0 {
1951                                                         return inf
1952                                                 }
1953
1954                                                 exprIdx := exprAtPos(c.pos, node.Args)
1955
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())
1964                                                         }
1965
1966                                                         // Record that we may be completing into variadic parameters.
1967                                                         inf.variadicAssignees = sig.Variadic()
1968                                                 }
1969
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()
1973                                                 } else {
1974                                                         inf.objType = sig.Params().At(exprIdx).Type()
1975                                                 }
1976
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
1982
1983                                                         // Check if we can infer object kind from printf verb.
1984                                                         inf.objKind |= printfArgKind(c.pkg.GetTypesInfo(), node, exprIdx)
1985                                                 }
1986                                         }
1987                                 }
1988
1989                                 if funIdent, ok := node.Fun.(*ast.Ident); ok {
1990                                         obj := c.pkg.GetTypesInfo().ObjectOf(funIdent)
1991
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.
1995                                                 defer func() {
1996                                                         inf = c.builtinArgType(obj, node, inf)
1997                                                         inf.objKind = c.builtinArgKind(ctx, obj, node)
1998                                                 }()
1999
2000                                                 // The expected type of builtin arguments like append() is
2001                                                 // the expected type of the builtin call itself. For
2002                                                 // example:
2003                                                 //
2004                                                 // var foo []int = append(<>)
2005                                                 //
2006                                                 // To find the expected type at <> we "skip" the append()
2007                                                 // node and get the expected type one level up, which is
2008                                                 // []int.
2009                                                 continue Nodes
2010                                         }
2011                                 }
2012
2013                                 return inf
2014                         }
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()
2022                                         }
2023                                 }
2024                         }
2025                         return inf
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
2030
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() {
2037                                                                 continue
2038                                                         }
2039
2040                                                         if objs := objChain(c.pkg.GetTypesInfo(), caseExpr); len(objs) > 0 {
2041                                                                 inf.penalized = append(inf.penalized, penalizedObj{objChain: objs, penalty: 0.1})
2042                                                         }
2043                                                 }
2044                                         }
2045                                 }
2046                         }
2047                         return inf
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]
2052                         }
2053                         return inf
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) {
2059                                         case *types.Map:
2060                                                 inf.objType = t.Key()
2061                                         case *types.Slice, *types.Array:
2062                                                 inf.objType = types.Typ[types.UntypedInt]
2063                                         }
2064                                 }
2065                         }
2066                         return inf
2067                 case *ast.SendStmt:
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()
2073                                         }
2074                                 }
2075                         }
2076                         return inf
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
2082                                 }
2083                         }
2084                         return inf
2085                 case *ast.StarExpr:
2086                         inf.modifiers = append(inf.modifiers, typeModifier{mod: dereference})
2087                 case *ast.UnaryExpr:
2088                         switch node.Op {
2089                         case token.AND:
2090                                 inf.modifiers = append(inf.modifiers, typeModifier{mod: reference})
2091                         case token.ARROW:
2092                                 inf.modifiers = append(inf.modifiers, typeModifier{mod: chanRead})
2093                         }
2094                 case *ast.DeferStmt, *ast.GoStmt:
2095                         inf.objKind |= kindFunc
2096                         return inf
2097                 default:
2098                         if breaksExpectedTypeInference(node, c.pos) {
2099                                 return inf
2100                         }
2101                 }
2102         }
2103
2104         return inf
2105 }
2106
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
2112
2113         for e != nil {
2114                 switch n := e.(type) {
2115                 case *ast.Ident:
2116                         obj := info.ObjectOf(n)
2117                         if obj == nil {
2118                                 return nil
2119                         }
2120                         objs = append(objs, obj)
2121                         e = nil
2122                 case *ast.SelectorExpr:
2123                         obj := info.ObjectOf(n.Sel)
2124                         if obj == nil {
2125                                 return nil
2126                         }
2127                         objs = append(objs, obj)
2128                         e = n.X
2129                 case *ast.CallExpr:
2130                         if len(n.Args) > 0 {
2131                                 return nil
2132                         }
2133                         e = n.Fun
2134                 default:
2135                         return nil
2136                 }
2137         }
2138
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]
2142         }
2143
2144         return objs
2145 }
2146
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 {
2151                 switch mod.mod {
2152                 case dereference:
2153                         // For every "*" indirection operator, remove a pointer layer
2154                         // from candidate type.
2155                         if ptr, ok := typ.Underlying().(*types.Pointer); ok {
2156                                 typ = ptr.Elem()
2157                         } else {
2158                                 return nil
2159                         }
2160                 case reference:
2161                         // For every "&" address operator, add another pointer layer to
2162                         // candidate type, if the candidate is addressable.
2163                         if addressable {
2164                                 typ = types.NewPointer(typ)
2165                         } else {
2166                                 return nil
2167                         }
2168                 case chanRead:
2169                         // For every "<-" operator, remove a layer of channelness.
2170                         if ch, ok := typ.(*types.Chan); ok {
2171                                 typ = ch.Elem()
2172                         } else {
2173                                 return nil
2174                         }
2175                 }
2176         }
2177
2178         return typ
2179 }
2180
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 {
2184                 switch mod.mod {
2185                 case reference:
2186                         typ = types.NewPointer(typ)
2187                 case array:
2188                         typ = types.NewArray(typ, mod.arrayLen)
2189                 case slice:
2190                         typ = types.NewSlice(typ)
2191                 }
2192         }
2193         return typ
2194 }
2195
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))
2200 }
2201
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) {
2207                 return nil
2208         }
2209         // A case clause is always nested within a block statement in a switch statement.
2210         if len(path) < 2 {
2211                 return nil
2212         }
2213         if _, ok := path[0].(*ast.BlockStmt); !ok {
2214                 return nil
2215         }
2216         switch s := path[1].(type) {
2217         case *ast.SwitchStmt:
2218                 return s
2219         case *ast.TypeSwitchStmt:
2220                 return s
2221         default:
2222                 return nil
2223         }
2224 }
2225
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)
2235         case *ast.CallExpr:
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:
2240                 return true
2241         default:
2242                 return false
2243         }
2244 }
2245
2246 // expectTypeName returns information about the expected type name at position.
2247 func expectTypeName(c *completer) typeNameInference {
2248         var inf typeNameInference
2249
2250 Nodes:
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
2260                         break Nodes
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)
2268                                                 return false
2269                                         }
2270                                         return true
2271                                 })
2272                                 inf.wantTypeName = true
2273
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() {
2281                                                         continue
2282                                                 }
2283
2284                                                 if t := c.pkg.GetTypesInfo().TypeOf(typeExpr); t != nil {
2285                                                         inf.seenTypeSwitchCases = append(inf.seenTypeSwitchCases, t)
2286                                                 }
2287                                         }
2288                                 }
2289
2290                                 break Nodes
2291                         }
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
2299                                 break Nodes
2300                         }
2301                         return typeNameInference{}
2302                 case *ast.StarExpr:
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
2310
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})
2317                                         }
2318                                 }
2319                         }
2320                         break Nodes
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
2325                                 if n.Len == nil {
2326                                         // No "Len" expression means a slice type.
2327                                         inf.modifiers = append(inf.modifiers, typeModifier{mod: slice})
2328                                 } else {
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})
2334                                                 }
2335                                         }
2336                                 }
2337
2338                                 // ArrayTypes can be nested, so keep going if our parent is an
2339                                 // ArrayType.
2340                                 if i < len(c.path)-1 {
2341                                         if _, ok := c.path[i+1].(*ast.ArrayType); ok {
2342                                                 continue Nodes
2343                                         }
2344                                 }
2345
2346                                 break Nodes
2347                         }
2348                 case *ast.MapType:
2349                         inf.wantTypeName = true
2350                         if n.Key != nil {
2351                                 inf.wantComparable = source.NodeContains(n.Key, c.pos)
2352                         } else {
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["))
2356                         }
2357                         break Nodes
2358                 case *ast.ValueSpec:
2359                         inf.wantTypeName = source.NodeContains(n.Type, c.pos)
2360                         break Nodes
2361                 case *ast.TypeSpec:
2362                         inf.wantTypeName = source.NodeContains(n.Type, c.pos)
2363                 default:
2364                         if breaksExpectedTypeInference(p, c.pos) {
2365                                 return typeNameInference{}
2366                         }
2367                 }
2368         }
2369
2370         return inf
2371 }
2372
2373 func (c *completer) fakeObj(T types.Type) *types.Var {
2374         return types.NewVar(token.NoPos, c.pkg.GetTypes(), "", T)
2375 }
2376
2377 // anyCandType reports whether f returns true for any candidate type
2378 // derivable from c. For example, from "foo" we might derive "&foo",
2379 // and "foo()".
2380 func (c *candidate) anyCandType(f func(t types.Type, addressable bool) bool) bool {
2381         if c.obj == nil || c.obj.Type() == nil {
2382                 return false
2383         }
2384
2385         objType := c.obj.Type()
2386
2387         if f(objType, c.addressable) {
2388                 return true
2389         }
2390
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
2396                         return true
2397                 }
2398         }
2399
2400         var (
2401                 seenPtrTypes map[types.Type]bool
2402                 ptrType      = objType
2403                 ptrDepth     int
2404         )
2405
2406         // Check if dereferencing c would match our type inference. We loop
2407         // since c could have arbitrary levels of pointerness.
2408         for {
2409                 ptr, ok := ptrType.Underlying().(*types.Pointer)
2410                 if !ok {
2411                         break
2412                 }
2413
2414                 ptrDepth++
2415
2416                 // Avoid pointer type cycles.
2417                 if seenPtrTypes[ptrType] {
2418                         break
2419                 }
2420
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)
2425                         }
2426
2427                         // Track named pointer types we have seen to detect cycles.
2428                         seenPtrTypes[ptrType] = true
2429                 }
2430
2431                 if f(ptr.Elem(), false) {
2432                         // Mark the candidate so we know to prepend "*" when formatting.
2433                         c.dereference = ptrDepth
2434                         return true
2435                 }
2436
2437                 ptrType = ptr.Elem()
2438         }
2439
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
2444                 return true
2445         }
2446
2447         return false
2448 }
2449
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 {
2454                 return false
2455         }
2456
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() {
2459                 return true
2460         }
2461
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.
2466                 return false
2467         }
2468
2469         if c.inference.candTypeMatches(cand) {
2470                 return true
2471         }
2472
2473         candType := cand.obj.Type()
2474         if candType == nil {
2475                 return false
2476         }
2477
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
2482                         return true
2483                 }
2484         }
2485
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)
2490
2491         return false
2492 }
2493
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 {
2498         var (
2499                 expTypes     = make([]types.Type, 0, 2)
2500                 variadicType types.Type
2501         )
2502         if ci.objType != nil {
2503                 expTypes = append(expTypes, ci.objType)
2504
2505                 if ci.variadic {
2506                         variadicType = types.NewSlice(ci.objType)
2507                         expTypes = append(expTypes, variadicType)
2508                 }
2509         }
2510
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 {
2515                         return false
2516                 }
2517
2518                 if ci.convertibleTo != nil && types.ConvertibleTo(candType, ci.convertibleTo) {
2519                         return true
2520                 }
2521
2522                 for _, expType := range expTypes {
2523                         if isEmptyInterface(expType) {
2524                                 continue
2525                         }
2526
2527                         matches := ci.typeMatches(expType, candType)
2528                         if !matches {
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.
2535                                         cand.score *= 0.5
2536                                         return true
2537                                 }
2538
2539                                 continue
2540                         }
2541
2542                         if expType == variadicType {
2543                                 cand.variadic = true
2544                         }
2545
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
2552                                 // the time.
2553                                 if len(cand.path) > 0 && isPkgName(cand.path[0]) {
2554                                         cand.score *= 0.5
2555                                 } else {
2556                                         cand.score *= 0.75
2557                                 }
2558                         }
2559
2560                         return true
2561                 }
2562
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:
2568                         //
2569                         //   var foo chan int
2570                         //   <-fo<>
2571                         //
2572                         // We were able to apply the "<-" type modifier to "foo", so "foo"
2573                         // matches.
2574                         if len(ci.modifiers) > 0 {
2575                                 return true
2576                         }
2577
2578                         // If we didn't have an exact type match, check if our object kind
2579                         // matches.
2580                         if ci.kindMatches(candType) {
2581                                 if ci.objKind == kindFunc {
2582                                         cand.expandFuncCall = true
2583                                 }
2584                                 return true
2585                         }
2586                 }
2587
2588                 return false
2589         })
2590 }
2591
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]) {
2599                 return false
2600         }
2601
2602         if !types.ConvertibleTo(from, to) {
2603                 return false
2604         }
2605
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) {
2609                 return false
2610         }
2611
2612         return true
2613 }
2614
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.
2625
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) {
2629                                 a, b = b, a
2630                         }
2631
2632                         // If at least one is untyped...
2633                         if a&types.IsUntyped > 0 {
2634                                 switch {
2635                                 // Untyped integers are compatible with floats.
2636                                 case a&types.IsInteger > 0 && b&types.IsFloat > 0:
2637                                         return true
2638
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:
2643                                         return true
2644                                 }
2645                         }
2646                 }
2647         }
2648
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)
2652 }
2653
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
2658 }
2659
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 {
2664                 return false
2665         }
2666
2667         // Uniresult functions are always usable and are handled by the
2668         // normal, non-assignees type matching logic.
2669         if sig.Results().Len() == 1 {
2670                 return false
2671         }
2672
2673         var numberOfResultsCouldMatch bool
2674         if ci.variadicAssignees {
2675                 numberOfResultsCouldMatch = sig.Results().Len() >= len(ci.assignees)-1
2676         } else {
2677                 numberOfResultsCouldMatch = sig.Results().Len() == len(ci.assignees)
2678         }
2679
2680         // If our signature doesn't return the right number of values, it's
2681         // not a match, so downrank it. For example:
2682         //
2683         //  var foo func() (int, int)
2684         //  a, b, c := <> // downrank "foo()" since it only returns two values
2685         if !numberOfResultsCouldMatch {
2686                 cand.score /= 2
2687                 return false
2688         }
2689
2690         // If at least one assignee has a valid type, and all valid
2691         // assignees match the corresponding sig result value, the signature
2692         // is a match.
2693         allMatch := false
2694         for i := 0; i < sig.Results().Len(); i++ {
2695                 var assignee types.Type
2696
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 {
2702                                 assignee = elem
2703                         }
2704                 } else {
2705                         assignee = ci.assignees[i]
2706                 }
2707
2708                 if assignee == nil {
2709                         continue
2710                 }
2711
2712                 allMatch = ci.typeMatches(assignee, sig.Results().At(i).Type())
2713                 if !allMatch {
2714                         break
2715                 }
2716         }
2717         return allMatch
2718 }
2719
2720 func (c *completer) matchingTypeName(cand *candidate) bool {
2721         if !c.wantTypeName() {
2722                 return false
2723         }
2724
2725         typeMatches := func(candType types.Type) bool {
2726                 // Take into account any type name modifier prefixes.
2727                 candType = c.inference.applyTypeNameModifiers(candType)
2728
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) {
2733                                 return false
2734                         }
2735
2736                         if intf, ok := from.Underlying().(*types.Interface); ok {
2737                                 if !types.AssertableTo(intf, candType) {
2738                                         return false
2739                                 }
2740                         }
2741                 }
2742
2743                 if c.inference.typeName.wantComparable && !types.Comparable(candType) {
2744                         return false
2745                 }
2746
2747                 // Skip this type if it has already been used in another type
2748                 // switch case.
2749                 for _, seen := range c.inference.typeName.seenTypeSwitchCases {
2750                         if types.Identical(candType, seen) {
2751                                 return false
2752                         }
2753                 }
2754
2755                 // We can expect a type name and have an expected type in cases like:
2756                 //
2757                 //   var foo []int
2758                 //   foo = []i<>
2759                 //
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)
2763                 }
2764
2765                 // Default to saying any type name is a match.
2766                 return true
2767         }
2768
2769         t := cand.obj.Type()
2770
2771         if typeMatches(t) {
2772                 return true
2773         }
2774
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
2780                 } else {
2781                         // If we are completing a normal type name such as "foo<>", to
2782                         // make a pointer we must prepend "*".
2783                         cand.makePointer = true
2784                 }
2785                 return true
2786         }
2787
2788         return false
2789 }
2790
2791 var (
2792         // "interface { Error() string }" (i.e. error)
2793         errorIntf = types.Universe.Lookup("error").Type().Underlying().(*types.Interface)
2794
2795         // "interface { String() string }" (i.e. fmt.Stringer)
2796         stringerIntf = types.NewInterfaceType([]*types.Func{
2797                 types.NewFunc(token.NoPos, nil, "String", types.NewSignature(
2798                         nil,
2799                         nil,
2800                         types.NewTuple(types.NewParam(token.NoPos, nil, "", types.Typ[types.String])),
2801                         false,
2802                 )),
2803         }, nil).Complete()
2804
2805         byteType = types.Universe.Lookup("byte").Type()
2806 )
2807
2808 // candKind returns the objKind of candType, if any.
2809 func candKind(candType types.Type) objKind {
2810         var kind objKind
2811
2812         switch t := candType.Underlying().(type) {
2813         case *types.Array:
2814                 kind |= kindArray
2815                 if t.Elem() == byteType {
2816                         kind |= kindBytes
2817                 }
2818         case *types.Slice:
2819                 kind |= kindSlice
2820                 if t.Elem() == byteType {
2821                         kind |= kindBytes
2822                 }
2823         case *types.Chan:
2824                 kind |= kindChan
2825         case *types.Map:
2826                 kind |= kindMap
2827         case *types.Pointer:
2828                 kind |= kindPtr
2829
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 {
2833                         kind |= kindArray
2834                 }
2835         case *types.Basic:
2836                 switch info := t.Info(); {
2837                 case info&types.IsString > 0:
2838                         kind |= kindString
2839                 case info&types.IsInteger > 0:
2840                         kind |= kindInt
2841                 case info&types.IsFloat > 0:
2842                         kind |= kindFloat
2843                 case info&types.IsComplex > 0:
2844                         kind |= kindComplex
2845                 case info&types.IsBoolean > 0:
2846                         kind |= kindBool
2847                 }
2848         case *types.Signature:
2849                 return kindFunc
2850         }
2851
2852         if types.Implements(candType, errorIntf) {
2853                 kind |= kindError
2854         }
2855
2856         if types.Implements(candType, stringerIntf) {
2857                 kind |= kindStringer
2858         }
2859
2860         return kind
2861 }