github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/internal/lsp/source/completion/completion.go (about) 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 "github.com/powerman/golang-tools/go/ast/astutil" 26 "github.com/powerman/golang-tools/internal/event" 27 "github.com/powerman/golang-tools/internal/imports" 28 "github.com/powerman/golang-tools/internal/lsp/fuzzy" 29 "github.com/powerman/golang-tools/internal/lsp/protocol" 30 "github.com/powerman/golang-tools/internal/lsp/snippet" 31 "github.com/powerman/golang-tools/internal/lsp/source" 32 "github.com/powerman/golang-tools/internal/typeparams" 33 errors "golang.org/x/xerrors" 34 ) 35 36 type CompletionItem struct { 37 // Label is the primary text the user sees for this completion item. 38 Label string 39 40 // Detail is supplemental information to present to the user. 41 // This often contains the type or return type of the completion item. 42 Detail string 43 44 // InsertText is the text to insert if this item is selected. 45 // Any of the prefix that has already been typed is not trimmed. 46 // The insert text does not contain snippets. 47 InsertText string 48 49 Kind protocol.CompletionItemKind 50 Tags []protocol.CompletionItemTag 51 Deprecated bool // Deprecated, prefer Tags if available 52 53 // An optional array of additional TextEdits that are applied when 54 // selecting this completion. 55 // 56 // Additional text edits should be used to change text unrelated to the current cursor position 57 // (for example adding an import statement at the top of the file if the completion item will 58 // insert an unqualified type). 59 AdditionalTextEdits []protocol.TextEdit 60 61 // Depth is how many levels were searched to find this completion. 62 // For example when completing "foo<>", "fooBar" is depth 0, and 63 // "fooBar.Baz" is depth 1. 64 Depth int 65 66 // Score is the internal relevance score. 67 // A higher score indicates that this completion item is more relevant. 68 Score float64 69 70 // snippet is the LSP snippet for the completion item. The LSP 71 // specification contains details about LSP snippets. For example, a 72 // snippet for a function with the following signature: 73 // 74 // func foo(a, b, c int) 75 // 76 // would be: 77 // 78 // foo(${1:a int}, ${2: b int}, ${3: c int}) 79 // 80 // If Placeholders is false in the CompletionOptions, the above 81 // snippet would instead be: 82 // 83 // foo(${1:}) 84 snippet *snippet.Builder 85 86 // Documentation is the documentation for the completion item. 87 Documentation string 88 89 // obj is the object from which this candidate was derived, if any. 90 // obj is for internal use only. 91 obj types.Object 92 } 93 94 // completionOptions holds completion specific configuration. 95 type completionOptions struct { 96 unimported bool 97 documentation bool 98 fullDocumentation bool 99 placeholders bool 100 literal bool 101 snippets bool 102 postfix bool 103 matcher source.Matcher 104 budget time.Duration 105 } 106 107 // Snippet is a convenience returns the snippet if available, otherwise 108 // the InsertText. 109 // used for an item, depending on if the callee wants placeholders or not. 110 func (i *CompletionItem) Snippet() string { 111 if i.snippet != nil { 112 return i.snippet.String() 113 } 114 return i.InsertText 115 } 116 117 // Scoring constants are used for weighting the relevance of different candidates. 118 const ( 119 // stdScore is the base score for all completion items. 120 stdScore float64 = 1.0 121 122 // highScore indicates a very relevant completion item. 123 highScore float64 = 10.0 124 125 // lowScore indicates an irrelevant or not useful completion item. 126 lowScore float64 = 0.01 127 ) 128 129 // matcher matches a candidate's label against the user input. The 130 // returned score reflects the quality of the match. A score of zero 131 // indicates no match, and a score of one means a perfect match. 132 type matcher interface { 133 Score(candidateLabel string) (score float32) 134 } 135 136 // prefixMatcher implements case sensitive prefix matching. 137 type prefixMatcher string 138 139 func (pm prefixMatcher) Score(candidateLabel string) float32 { 140 if strings.HasPrefix(candidateLabel, string(pm)) { 141 return 1 142 } 143 return -1 144 } 145 146 // insensitivePrefixMatcher implements case insensitive prefix matching. 147 type insensitivePrefixMatcher string 148 149 func (ipm insensitivePrefixMatcher) Score(candidateLabel string) float32 { 150 if strings.HasPrefix(strings.ToLower(candidateLabel), string(ipm)) { 151 return 1 152 } 153 return -1 154 } 155 156 // completer contains the necessary information for a single completion request. 157 type completer struct { 158 snapshot source.Snapshot 159 pkg source.Package 160 qf types.Qualifier 161 opts *completionOptions 162 163 // completionContext contains information about the trigger for this 164 // completion request. 165 completionContext completionContext 166 167 // fh is a handle to the file associated with this completion request. 168 fh source.FileHandle 169 170 // filename is the name of the file associated with this completion request. 171 filename string 172 173 // file is the AST of the file associated with this completion request. 174 file *ast.File 175 176 // pos is the position at which the request was triggered. 177 pos token.Pos 178 179 // path is the path of AST nodes enclosing the position. 180 path []ast.Node 181 182 // seen is the map that ensures we do not return duplicate results. 183 seen map[types.Object]bool 184 185 // items is the list of completion items returned. 186 items []CompletionItem 187 188 // completionCallbacks is a list of callbacks to collect completions that 189 // require expensive operations. This includes operations where we search 190 // through the entire module cache. 191 completionCallbacks []func(opts *imports.Options) error 192 193 // surrounding describes the identifier surrounding the position. 194 surrounding *Selection 195 196 // inference contains information we've inferred about ideal 197 // candidates such as the candidate's type. 198 inference candidateInference 199 200 // enclosingFunc contains information about the function enclosing 201 // the position. 202 enclosingFunc *funcInfo 203 204 // enclosingCompositeLiteral contains information about the composite literal 205 // enclosing the position. 206 enclosingCompositeLiteral *compLitInfo 207 208 // deepState contains the current state of our deep completion search. 209 deepState deepCompletionState 210 211 // matcher matches the candidates against the surrounding prefix. 212 matcher matcher 213 214 // methodSetCache caches the types.NewMethodSet call, which is relatively 215 // expensive and can be called many times for the same type while searching 216 // for deep completions. 217 methodSetCache map[methodSetKey]*types.MethodSet 218 219 // mapper converts the positions in the file from which the completion originated. 220 mapper *protocol.ColumnMapper 221 222 // startTime is when we started processing this completion request. It does 223 // not include any time the request spent in the queue. 224 startTime time.Time 225 } 226 227 // funcInfo holds info about a function object. 228 type funcInfo struct { 229 // sig is the function declaration enclosing the position. 230 sig *types.Signature 231 232 // body is the function's body. 233 body *ast.BlockStmt 234 } 235 236 type compLitInfo struct { 237 // cl is the *ast.CompositeLit enclosing the position. 238 cl *ast.CompositeLit 239 240 // clType is the type of cl. 241 clType types.Type 242 243 // kv is the *ast.KeyValueExpr enclosing the position, if any. 244 kv *ast.KeyValueExpr 245 246 // inKey is true if we are certain the position is in the key side 247 // of a key-value pair. 248 inKey bool 249 250 // maybeInFieldName is true if inKey is false and it is possible 251 // we are completing a struct field name. For example, 252 // "SomeStruct{<>}" will be inKey=false, but maybeInFieldName=true 253 // because we _could_ be completing a field name. 254 maybeInFieldName bool 255 } 256 257 type importInfo struct { 258 importPath string 259 name string 260 pkg source.Package 261 } 262 263 type methodSetKey struct { 264 typ types.Type 265 addressable bool 266 } 267 268 type completionContext struct { 269 // triggerCharacter is the character used to trigger completion at current 270 // position, if any. 271 triggerCharacter string 272 273 // triggerKind is information about how a completion was triggered. 274 triggerKind protocol.CompletionTriggerKind 275 276 // commentCompletion is true if we are completing a comment. 277 commentCompletion bool 278 279 // packageCompletion is true if we are completing a package name. 280 packageCompletion bool 281 } 282 283 // A Selection represents the cursor position and surrounding identifier. 284 type Selection struct { 285 content string 286 cursor token.Pos 287 source.MappedRange 288 } 289 290 func (p Selection) Content() string { 291 return p.content 292 } 293 294 func (p Selection) Start() token.Pos { 295 return p.MappedRange.SpanRange().Start 296 } 297 298 func (p Selection) End() token.Pos { 299 return p.MappedRange.SpanRange().End 300 } 301 302 func (p Selection) Prefix() string { 303 return p.content[:p.cursor-p.SpanRange().Start] 304 } 305 306 func (p Selection) Suffix() string { 307 return p.content[p.cursor-p.SpanRange().Start:] 308 } 309 310 func (c *completer) setSurrounding(ident *ast.Ident) { 311 if c.surrounding != nil { 312 return 313 } 314 if !(ident.Pos() <= c.pos && c.pos <= ident.End()) { 315 return 316 } 317 318 c.surrounding = &Selection{ 319 content: ident.Name, 320 cursor: c.pos, 321 // Overwrite the prefix only. 322 MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, ident.Pos(), ident.End()), 323 } 324 325 c.setMatcherFromPrefix(c.surrounding.Prefix()) 326 } 327 328 func (c *completer) setMatcherFromPrefix(prefix string) { 329 switch c.opts.matcher { 330 case source.Fuzzy: 331 c.matcher = fuzzy.NewMatcher(prefix) 332 case source.CaseSensitive: 333 c.matcher = prefixMatcher(prefix) 334 default: 335 c.matcher = insensitivePrefixMatcher(strings.ToLower(prefix)) 336 } 337 } 338 339 func (c *completer) getSurrounding() *Selection { 340 if c.surrounding == nil { 341 c.surrounding = &Selection{ 342 content: "", 343 cursor: c.pos, 344 MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, c.pos, c.pos), 345 } 346 } 347 return c.surrounding 348 } 349 350 // candidate represents a completion candidate. 351 type candidate struct { 352 // obj is the types.Object to complete to. 353 obj types.Object 354 355 // score is used to rank candidates. 356 score float64 357 358 // name is the deep object name path, e.g. "foo.bar" 359 name string 360 361 // detail is additional information about this item. If not specified, 362 // defaults to type string for the object. 363 detail string 364 365 // path holds the path from the search root (excluding the candidate 366 // itself) for a deep candidate. 367 path []types.Object 368 369 // pathInvokeMask is a bit mask tracking whether each entry in path 370 // should be formatted with "()" (i.e. whether it is a function 371 // invocation). 372 pathInvokeMask uint16 373 374 // mods contains modifications that should be applied to the 375 // candidate when inserted. For example, "foo" may be inserted as 376 // "*foo" or "foo()". 377 mods []typeModKind 378 379 // addressable is true if a pointer can be taken to the candidate. 380 addressable bool 381 382 // convertTo is a type that this candidate should be cast to. For 383 // example, if convertTo is float64, "foo" should be formatted as 384 // "float64(foo)". 385 convertTo types.Type 386 387 // imp is the import that needs to be added to this package in order 388 // for this candidate to be valid. nil if no import needed. 389 imp *importInfo 390 } 391 392 func (c candidate) hasMod(mod typeModKind) bool { 393 for _, m := range c.mods { 394 if m == mod { 395 return true 396 } 397 } 398 return false 399 } 400 401 // ErrIsDefinition is an error that informs the user they got no 402 // completions because they tried to complete the name of a new object 403 // being defined. 404 type ErrIsDefinition struct { 405 objStr string 406 } 407 408 func (e ErrIsDefinition) Error() string { 409 msg := "this is a definition" 410 if e.objStr != "" { 411 msg += " of " + e.objStr 412 } 413 return msg 414 } 415 416 // Completion returns a list of possible candidates for completion, given a 417 // a file and a position. 418 // 419 // The selection is computed based on the preceding identifier and can be used by 420 // the client to score the quality of the completion. For instance, some clients 421 // may tolerate imperfect matches as valid completion results, since users may make typos. 422 func Completion(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle, protoPos protocol.Position, protoContext protocol.CompletionContext) ([]CompletionItem, *Selection, error) { 423 ctx, done := event.Start(ctx, "completion.Completion") 424 defer done() 425 426 startTime := time.Now() 427 428 pkg, pgf, err := source.GetParsedFile(ctx, snapshot, fh, source.NarrowestPackage) 429 if err != nil || pgf.File.Package == token.NoPos { 430 // If we can't parse this file or find position for the package 431 // keyword, it may be missing a package declaration. Try offering 432 // suggestions for the package declaration. 433 // Note that this would be the case even if the keyword 'package' is 434 // present but no package name exists. 435 items, surrounding, innerErr := packageClauseCompletions(ctx, snapshot, fh, protoPos) 436 if innerErr != nil { 437 // return the error for GetParsedFile since it's more relevant in this situation. 438 return nil, nil, errors.Errorf("getting file for Completion: %w (package completions: %v)", err, innerErr) 439 } 440 return items, surrounding, nil 441 } 442 spn, err := pgf.Mapper.PointSpan(protoPos) 443 if err != nil { 444 return nil, nil, err 445 } 446 rng, err := spn.Range(pgf.Mapper.Converter) 447 if err != nil { 448 return nil, nil, err 449 } 450 // Completion is based on what precedes the cursor. 451 // Find the path to the position before pos. 452 path, _ := astutil.PathEnclosingInterval(pgf.File, rng.Start-1, rng.Start-1) 453 if path == nil { 454 return nil, nil, errors.Errorf("cannot find node enclosing position") 455 } 456 457 pos := rng.Start 458 459 // Check if completion at this position is valid. If not, return early. 460 switch n := path[0].(type) { 461 case *ast.BasicLit: 462 // Skip completion inside literals except for ImportSpec 463 if len(path) > 1 { 464 if _, ok := path[1].(*ast.ImportSpec); ok { 465 break 466 } 467 } 468 return nil, nil, nil 469 case *ast.CallExpr: 470 if n.Ellipsis.IsValid() && pos > n.Ellipsis && pos <= n.Ellipsis+token.Pos(len("...")) { 471 // Don't offer completions inside or directly after "...". For 472 // example, don't offer completions at "<>" in "foo(bar...<>"). 473 return nil, nil, nil 474 } 475 case *ast.Ident: 476 // reject defining identifiers 477 if obj, ok := pkg.GetTypesInfo().Defs[n]; ok { 478 if v, ok := obj.(*types.Var); ok && v.IsField() && v.Embedded() { 479 // An anonymous field is also a reference to a type. 480 } else if pgf.File.Name == n { 481 // Don't skip completions if Ident is for package name. 482 break 483 } else { 484 objStr := "" 485 if obj != nil { 486 qual := types.RelativeTo(pkg.GetTypes()) 487 objStr = types.ObjectString(obj, qual) 488 } 489 ans, sel := definition(path, obj, snapshot.FileSet(), pgf.Mapper, fh) 490 if ans != nil { 491 sort.Slice(ans, func(i, j int) bool { 492 return ans[i].Score > ans[j].Score 493 }) 494 return ans, sel, nil 495 } 496 return nil, nil, ErrIsDefinition{objStr: objStr} 497 } 498 } 499 } 500 501 opts := snapshot.View().Options() 502 c := &completer{ 503 pkg: pkg, 504 snapshot: snapshot, 505 qf: source.Qualifier(pgf.File, pkg.GetTypes(), pkg.GetTypesInfo()), 506 completionContext: completionContext{ 507 triggerCharacter: protoContext.TriggerCharacter, 508 triggerKind: protoContext.TriggerKind, 509 }, 510 fh: fh, 511 filename: fh.URI().Filename(), 512 file: pgf.File, 513 path: path, 514 pos: pos, 515 seen: make(map[types.Object]bool), 516 enclosingFunc: enclosingFunction(path, pkg.GetTypesInfo()), 517 enclosingCompositeLiteral: enclosingCompositeLiteral(path, rng.Start, pkg.GetTypesInfo()), 518 deepState: deepCompletionState{ 519 enabled: opts.DeepCompletion, 520 }, 521 opts: &completionOptions{ 522 matcher: opts.Matcher, 523 unimported: opts.CompleteUnimported, 524 documentation: opts.CompletionDocumentation && opts.HoverKind != source.NoDocumentation, 525 fullDocumentation: opts.HoverKind == source.FullDocumentation, 526 placeholders: opts.UsePlaceholders, 527 literal: opts.LiteralCompletions && opts.InsertTextFormat == protocol.SnippetTextFormat, 528 budget: opts.CompletionBudget, 529 snippets: opts.InsertTextFormat == protocol.SnippetTextFormat, 530 postfix: opts.ExperimentalPostfixCompletions, 531 }, 532 // default to a matcher that always matches 533 matcher: prefixMatcher(""), 534 methodSetCache: make(map[methodSetKey]*types.MethodSet), 535 mapper: pgf.Mapper, 536 startTime: startTime, 537 } 538 539 var cancel context.CancelFunc 540 if c.opts.budget == 0 { 541 ctx, cancel = context.WithCancel(ctx) 542 } else { 543 // timeoutDuration is the completion budget remaining. If less than 544 // 10ms, set to 10ms 545 timeoutDuration := time.Until(c.startTime.Add(c.opts.budget)) 546 if timeoutDuration < 10*time.Millisecond { 547 timeoutDuration = 10 * time.Millisecond 548 } 549 ctx, cancel = context.WithTimeout(ctx, timeoutDuration) 550 } 551 defer cancel() 552 553 if surrounding := c.containingIdent(pgf.Src); surrounding != nil { 554 c.setSurrounding(surrounding) 555 } 556 557 c.inference = expectedCandidate(ctx, c) 558 559 err = c.collectCompletions(ctx) 560 if err != nil { 561 return nil, nil, err 562 } 563 564 // Deep search collected candidates and their members for more candidates. 565 c.deepSearch(ctx) 566 567 for _, callback := range c.completionCallbacks { 568 if err := c.snapshot.RunProcessEnvFunc(ctx, callback); err != nil { 569 return nil, nil, err 570 } 571 } 572 573 // Search candidates populated by expensive operations like 574 // unimportedMembers etc. for more completion items. 575 c.deepSearch(ctx) 576 577 // Statement candidates offer an entire statement in certain contexts, as 578 // opposed to a single object. Add statement candidates last because they 579 // depend on other candidates having already been collected. 580 c.addStatementCandidates() 581 582 c.sortItems() 583 return c.items, c.getSurrounding(), nil 584 } 585 586 // collectCompletions adds possible completion candidates to either the deep 587 // search queue or completion items directly for different completion contexts. 588 func (c *completer) collectCompletions(ctx context.Context) error { 589 // Inside import blocks, return completions for unimported packages. 590 for _, importSpec := range c.file.Imports { 591 if !(importSpec.Path.Pos() <= c.pos && c.pos <= importSpec.Path.End()) { 592 continue 593 } 594 return c.populateImportCompletions(ctx, importSpec) 595 } 596 597 // Inside comments, offer completions for the name of the relevant symbol. 598 for _, comment := range c.file.Comments { 599 if comment.Pos() < c.pos && c.pos <= comment.End() { 600 c.populateCommentCompletions(ctx, comment) 601 return nil 602 } 603 } 604 605 // Struct literals are handled entirely separately. 606 if c.wantStructFieldCompletions() { 607 // If we are definitely completing a struct field name, deep completions 608 // don't make sense. 609 if c.enclosingCompositeLiteral.inKey { 610 c.deepState.enabled = false 611 } 612 return c.structLiteralFieldName(ctx) 613 } 614 615 if lt := c.wantLabelCompletion(); lt != labelNone { 616 c.labels(lt) 617 return nil 618 } 619 620 if c.emptySwitchStmt() { 621 // Empty switch statements only admit "default" and "case" keywords. 622 c.addKeywordItems(map[string]bool{}, highScore, CASE, DEFAULT) 623 return nil 624 } 625 626 switch n := c.path[0].(type) { 627 case *ast.Ident: 628 if c.file.Name == n { 629 return c.packageNameCompletions(ctx, c.fh.URI(), n) 630 } else if sel, ok := c.path[1].(*ast.SelectorExpr); ok && sel.Sel == n { 631 // Is this the Sel part of a selector? 632 return c.selector(ctx, sel) 633 } 634 return c.lexical(ctx) 635 // The function name hasn't been typed yet, but the parens are there: 636 // recv.‸(arg) 637 case *ast.TypeAssertExpr: 638 // Create a fake selector expression. 639 return c.selector(ctx, &ast.SelectorExpr{X: n.X}) 640 case *ast.SelectorExpr: 641 return c.selector(ctx, n) 642 // At the file scope, only keywords are allowed. 643 case *ast.BadDecl, *ast.File: 644 c.addKeywordCompletions() 645 default: 646 // fallback to lexical completions 647 return c.lexical(ctx) 648 } 649 650 return nil 651 } 652 653 // containingIdent returns the *ast.Ident containing pos, if any. It 654 // synthesizes an *ast.Ident to allow completion in the face of 655 // certain syntax errors. 656 func (c *completer) containingIdent(src []byte) *ast.Ident { 657 // In the normal case, our leaf AST node is the identifier being completed. 658 if ident, ok := c.path[0].(*ast.Ident); ok { 659 return ident 660 } 661 662 pos, tkn, lit := c.scanToken(src) 663 if !pos.IsValid() { 664 return nil 665 } 666 667 fakeIdent := &ast.Ident{Name: lit, NamePos: pos} 668 669 if _, isBadDecl := c.path[0].(*ast.BadDecl); isBadDecl { 670 // You don't get *ast.Idents at the file level, so look for bad 671 // decls and use the manually extracted token. 672 return fakeIdent 673 } else if c.emptySwitchStmt() { 674 // Only keywords are allowed in empty switch statements. 675 // *ast.Idents are not parsed, so we must use the manually 676 // extracted token. 677 return fakeIdent 678 } else if tkn.IsKeyword() { 679 // Otherwise, manually extract the prefix if our containing token 680 // is a keyword. This improves completion after an "accidental 681 // keyword", e.g. completing to "variance" in "someFunc(var<>)". 682 return fakeIdent 683 } 684 685 return nil 686 } 687 688 // scanToken scans pgh's contents for the token containing pos. 689 func (c *completer) scanToken(contents []byte) (token.Pos, token.Token, string) { 690 tok := c.snapshot.FileSet().File(c.pos) 691 692 var s scanner.Scanner 693 s.Init(tok, contents, nil, 0) 694 for { 695 tknPos, tkn, lit := s.Scan() 696 if tkn == token.EOF || tknPos >= c.pos { 697 return token.NoPos, token.ILLEGAL, "" 698 } 699 700 if len(lit) > 0 && tknPos <= c.pos && c.pos <= tknPos+token.Pos(len(lit)) { 701 return tknPos, tkn, lit 702 } 703 } 704 } 705 706 func (c *completer) sortItems() { 707 sort.SliceStable(c.items, func(i, j int) bool { 708 // Sort by score first. 709 if c.items[i].Score != c.items[j].Score { 710 return c.items[i].Score > c.items[j].Score 711 } 712 713 // Then sort by label so order stays consistent. This also has the 714 // effect of preferring shorter candidates. 715 return c.items[i].Label < c.items[j].Label 716 }) 717 } 718 719 // emptySwitchStmt reports whether pos is in an empty switch or select 720 // statement. 721 func (c *completer) emptySwitchStmt() bool { 722 block, ok := c.path[0].(*ast.BlockStmt) 723 if !ok || len(block.List) > 0 || len(c.path) == 1 { 724 return false 725 } 726 727 switch c.path[1].(type) { 728 case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt: 729 return true 730 default: 731 return false 732 } 733 } 734 735 // populateImportCompletions yields completions for an import path around the cursor. 736 // 737 // Completions are suggested at the directory depth of the given import path so 738 // that we don't overwhelm the user with a large list of possibilities. As an 739 // example, a completion for the prefix "golang" results in "golang.org/". 740 // Completions for "golang.org/" yield its subdirectories 741 // (i.e. "golang.org/x/"). The user is meant to accept completion suggestions 742 // until they reach a complete import path. 743 func (c *completer) populateImportCompletions(ctx context.Context, searchImport *ast.ImportSpec) error { 744 if !strings.HasPrefix(searchImport.Path.Value, `"`) { 745 return nil 746 } 747 748 // deepSearch is not valuable for import completions. 749 c.deepState.enabled = false 750 751 importPath := searchImport.Path.Value 752 753 // Extract the text between the quotes (if any) in an import spec. 754 // prefix is the part of import path before the cursor. 755 prefixEnd := c.pos - searchImport.Path.Pos() 756 prefix := strings.Trim(importPath[:prefixEnd], `"`) 757 758 // The number of directories in the import path gives us the depth at 759 // which to search. 760 depth := len(strings.Split(prefix, "/")) - 1 761 762 content := importPath 763 start, end := searchImport.Path.Pos(), searchImport.Path.End() 764 namePrefix, nameSuffix := `"`, `"` 765 // If a starting quote is present, adjust surrounding to either after the 766 // cursor or after the first slash (/), except if cursor is at the starting 767 // quote. Otherwise we provide a completion including the starting quote. 768 if strings.HasPrefix(importPath, `"`) && c.pos > searchImport.Path.Pos() { 769 content = content[1:] 770 start++ 771 if depth > 0 { 772 // Adjust textEdit start to replacement range. For ex: if current 773 // path was "golang.or/x/to<>ols/internal/", where <> is the cursor 774 // position, start of the replacement range would be after 775 // "golang.org/x/". 776 path := strings.SplitAfter(prefix, "/") 777 numChars := len(strings.Join(path[:len(path)-1], "")) 778 content = content[numChars:] 779 start += token.Pos(numChars) 780 } 781 namePrefix = "" 782 } 783 784 // We won't provide an ending quote if one is already present, except if 785 // cursor is after the ending quote but still in import spec. This is 786 // because cursor has to be in our textEdit range. 787 if strings.HasSuffix(importPath, `"`) && c.pos < searchImport.Path.End() { 788 end-- 789 content = content[:len(content)-1] 790 nameSuffix = "" 791 } 792 793 c.surrounding = &Selection{ 794 content: content, 795 cursor: c.pos, 796 MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, start, end), 797 } 798 799 seenImports := make(map[string]struct{}) 800 for _, importSpec := range c.file.Imports { 801 if importSpec.Path.Value == importPath { 802 continue 803 } 804 seenImportPath, err := strconv.Unquote(importSpec.Path.Value) 805 if err != nil { 806 return err 807 } 808 seenImports[seenImportPath] = struct{}{} 809 } 810 811 var mu sync.Mutex // guard c.items locally, since searchImports is called in parallel 812 seen := make(map[string]struct{}) 813 searchImports := func(pkg imports.ImportFix) { 814 path := pkg.StmtInfo.ImportPath 815 if _, ok := seenImports[path]; ok { 816 return 817 } 818 819 // Any package path containing fewer directories than the search 820 // prefix is not a match. 821 pkgDirList := strings.Split(path, "/") 822 if len(pkgDirList) < depth+1 { 823 return 824 } 825 pkgToConsider := strings.Join(pkgDirList[:depth+1], "/") 826 827 name := pkgDirList[depth] 828 // if we're adding an opening quote to completion too, set name to full 829 // package path since we'll need to overwrite that range. 830 if namePrefix == `"` { 831 name = pkgToConsider 832 } 833 834 score := pkg.Relevance 835 if len(pkgDirList)-1 == depth { 836 score *= highScore 837 } else { 838 // For incomplete package paths, add a terminal slash to indicate that the 839 // user should keep triggering completions. 840 name += "/" 841 pkgToConsider += "/" 842 } 843 844 if _, ok := seen[pkgToConsider]; ok { 845 return 846 } 847 seen[pkgToConsider] = struct{}{} 848 849 mu.Lock() 850 defer mu.Unlock() 851 852 name = namePrefix + name + nameSuffix 853 obj := types.NewPkgName(0, nil, name, types.NewPackage(pkgToConsider, name)) 854 c.deepState.enqueue(candidate{ 855 obj: obj, 856 detail: fmt.Sprintf("%q", pkgToConsider), 857 score: score, 858 }) 859 } 860 861 c.completionCallbacks = append(c.completionCallbacks, func(opts *imports.Options) error { 862 return imports.GetImportPaths(ctx, searchImports, prefix, c.filename, c.pkg.GetTypes().Name(), opts.Env) 863 }) 864 return nil 865 } 866 867 // populateCommentCompletions yields completions for comments preceding or in declarations. 868 func (c *completer) populateCommentCompletions(ctx context.Context, comment *ast.CommentGroup) { 869 // If the completion was triggered by a period, ignore it. These types of 870 // completions will not be useful in comments. 871 if c.completionContext.triggerCharacter == "." { 872 return 873 } 874 875 // Using the comment position find the line after 876 file := c.snapshot.FileSet().File(comment.End()) 877 if file == nil { 878 return 879 } 880 881 // Deep completion doesn't work properly in comments since we don't 882 // have a type object to complete further. 883 c.deepState.enabled = false 884 c.completionContext.commentCompletion = true 885 886 // Documentation isn't useful in comments, since it might end up being the 887 // comment itself. 888 c.opts.documentation = false 889 890 commentLine := file.Line(comment.End()) 891 892 // comment is valid, set surrounding as word boundaries around cursor 893 c.setSurroundingForComment(comment) 894 895 // Using the next line pos, grab and parse the exported symbol on that line 896 for _, n := range c.file.Decls { 897 declLine := file.Line(n.Pos()) 898 // if the comment is not in, directly above or on the same line as a declaration 899 if declLine != commentLine && declLine != commentLine+1 && 900 !(n.Pos() <= comment.Pos() && comment.End() <= n.End()) { 901 continue 902 } 903 switch node := n.(type) { 904 // handle const, vars, and types 905 case *ast.GenDecl: 906 for _, spec := range node.Specs { 907 switch spec := spec.(type) { 908 case *ast.ValueSpec: 909 for _, name := range spec.Names { 910 if name.String() == "_" { 911 continue 912 } 913 obj := c.pkg.GetTypesInfo().ObjectOf(name) 914 c.deepState.enqueue(candidate{obj: obj, score: stdScore}) 915 } 916 case *ast.TypeSpec: 917 // add TypeSpec fields to completion 918 switch typeNode := spec.Type.(type) { 919 case *ast.StructType: 920 c.addFieldItems(ctx, typeNode.Fields) 921 case *ast.FuncType: 922 c.addFieldItems(ctx, typeNode.Params) 923 c.addFieldItems(ctx, typeNode.Results) 924 case *ast.InterfaceType: 925 c.addFieldItems(ctx, typeNode.Methods) 926 } 927 928 if spec.Name.String() == "_" { 929 continue 930 } 931 932 obj := c.pkg.GetTypesInfo().ObjectOf(spec.Name) 933 // Type name should get a higher score than fields but not highScore by default 934 // since field near a comment cursor gets a highScore 935 score := stdScore * 1.1 936 // If type declaration is on the line after comment, give it a highScore. 937 if declLine == commentLine+1 { 938 score = highScore 939 } 940 941 c.deepState.enqueue(candidate{obj: obj, score: score}) 942 } 943 } 944 // handle functions 945 case *ast.FuncDecl: 946 c.addFieldItems(ctx, node.Recv) 947 c.addFieldItems(ctx, node.Type.Params) 948 c.addFieldItems(ctx, node.Type.Results) 949 950 // collect receiver struct fields 951 if node.Recv != nil { 952 for _, fields := range node.Recv.List { 953 for _, name := range fields.Names { 954 obj := c.pkg.GetTypesInfo().ObjectOf(name) 955 if obj == nil { 956 continue 957 } 958 959 recvType := obj.Type().Underlying() 960 if ptr, ok := recvType.(*types.Pointer); ok { 961 recvType = ptr.Elem() 962 } 963 recvStruct, ok := recvType.Underlying().(*types.Struct) 964 if !ok { 965 continue 966 } 967 for i := 0; i < recvStruct.NumFields(); i++ { 968 field := recvStruct.Field(i) 969 c.deepState.enqueue(candidate{obj: field, score: lowScore}) 970 } 971 } 972 } 973 } 974 975 if node.Name.String() == "_" { 976 continue 977 } 978 979 obj := c.pkg.GetTypesInfo().ObjectOf(node.Name) 980 if obj == nil || obj.Pkg() != nil && obj.Pkg() != c.pkg.GetTypes() { 981 continue 982 } 983 984 c.deepState.enqueue(candidate{obj: obj, score: highScore}) 985 } 986 } 987 } 988 989 // sets word boundaries surrounding a cursor for a comment 990 func (c *completer) setSurroundingForComment(comments *ast.CommentGroup) { 991 var cursorComment *ast.Comment 992 for _, comment := range comments.List { 993 if c.pos >= comment.Pos() && c.pos <= comment.End() { 994 cursorComment = comment 995 break 996 } 997 } 998 // if cursor isn't in the comment 999 if cursorComment == nil { 1000 return 1001 } 1002 1003 // index of cursor in comment text 1004 cursorOffset := int(c.pos - cursorComment.Pos()) 1005 start, end := cursorOffset, cursorOffset 1006 for start > 0 && isValidIdentifierChar(cursorComment.Text[start-1]) { 1007 start-- 1008 } 1009 for end < len(cursorComment.Text) && isValidIdentifierChar(cursorComment.Text[end]) { 1010 end++ 1011 } 1012 1013 c.surrounding = &Selection{ 1014 content: cursorComment.Text[start:end], 1015 cursor: c.pos, 1016 MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, 1017 token.Pos(int(cursorComment.Slash)+start), token.Pos(int(cursorComment.Slash)+end)), 1018 } 1019 c.setMatcherFromPrefix(c.surrounding.Prefix()) 1020 } 1021 1022 // isValidIdentifierChar returns true if a byte is a valid go identifier 1023 // character, i.e. unicode letter or digit or underscore. 1024 func isValidIdentifierChar(char byte) bool { 1025 charRune := rune(char) 1026 return unicode.In(charRune, unicode.Letter, unicode.Digit) || char == '_' 1027 } 1028 1029 // adds struct fields, interface methods, function declaration fields to completion 1030 func (c *completer) addFieldItems(ctx context.Context, fields *ast.FieldList) { 1031 if fields == nil { 1032 return 1033 } 1034 1035 cursor := c.surrounding.cursor 1036 for _, field := range fields.List { 1037 for _, name := range field.Names { 1038 if name.String() == "_" { 1039 continue 1040 } 1041 obj := c.pkg.GetTypesInfo().ObjectOf(name) 1042 if obj == nil { 1043 continue 1044 } 1045 1046 // if we're in a field comment/doc, score that field as more relevant 1047 score := stdScore 1048 if field.Comment != nil && field.Comment.Pos() <= cursor && cursor <= field.Comment.End() { 1049 score = highScore 1050 } else if field.Doc != nil && field.Doc.Pos() <= cursor && cursor <= field.Doc.End() { 1051 score = highScore 1052 } 1053 1054 c.deepState.enqueue(candidate{obj: obj, score: score}) 1055 } 1056 } 1057 } 1058 1059 func (c *completer) wantStructFieldCompletions() bool { 1060 clInfo := c.enclosingCompositeLiteral 1061 if clInfo == nil { 1062 return false 1063 } 1064 1065 return clInfo.isStruct() && (clInfo.inKey || clInfo.maybeInFieldName) 1066 } 1067 1068 func (c *completer) wantTypeName() bool { 1069 return !c.completionContext.commentCompletion && c.inference.typeName.wantTypeName 1070 } 1071 1072 // See https://golang.org/issue/36001. Unimported completions are expensive. 1073 const ( 1074 maxUnimportedPackageNames = 5 1075 unimportedMemberTarget = 100 1076 ) 1077 1078 // selector finds completions for the specified selector expression. 1079 func (c *completer) selector(ctx context.Context, sel *ast.SelectorExpr) error { 1080 c.inference.objChain = objChain(c.pkg.GetTypesInfo(), sel.X) 1081 1082 // Is sel a qualified identifier? 1083 if id, ok := sel.X.(*ast.Ident); ok { 1084 if pkgName, ok := c.pkg.GetTypesInfo().Uses[id].(*types.PkgName); ok { 1085 var pkg source.Package 1086 for _, imp := range c.pkg.Imports() { 1087 if imp.PkgPath() == pkgName.Imported().Path() { 1088 pkg = imp 1089 } 1090 } 1091 // If the package is not imported, try searching for unimported 1092 // completions. 1093 if pkg == nil && c.opts.unimported { 1094 if err := c.unimportedMembers(ctx, id); err != nil { 1095 return err 1096 } 1097 } 1098 c.packageMembers(pkgName.Imported(), stdScore, nil, func(cand candidate) { 1099 c.deepState.enqueue(cand) 1100 }) 1101 return nil 1102 } 1103 } 1104 1105 // Invariant: sel is a true selector. 1106 tv, ok := c.pkg.GetTypesInfo().Types[sel.X] 1107 if ok { 1108 c.methodsAndFields(tv.Type, tv.Addressable(), nil, func(cand candidate) { 1109 c.deepState.enqueue(cand) 1110 }) 1111 1112 c.addPostfixSnippetCandidates(ctx, sel) 1113 1114 return nil 1115 } 1116 1117 // Try unimported packages. 1118 if id, ok := sel.X.(*ast.Ident); ok && c.opts.unimported { 1119 if err := c.unimportedMembers(ctx, id); err != nil { 1120 return err 1121 } 1122 } 1123 return nil 1124 } 1125 1126 func (c *completer) unimportedMembers(ctx context.Context, id *ast.Ident) error { 1127 // Try loaded packages first. They're relevant, fast, and fully typed. 1128 known, err := c.snapshot.CachedImportPaths(ctx) 1129 if err != nil { 1130 return err 1131 } 1132 1133 var paths []string 1134 for path, pkg := range known { 1135 if pkg.GetTypes().Name() != id.Name { 1136 continue 1137 } 1138 paths = append(paths, path) 1139 } 1140 1141 var relevances map[string]float64 1142 if len(paths) != 0 { 1143 if err := c.snapshot.RunProcessEnvFunc(ctx, func(opts *imports.Options) error { 1144 var err error 1145 relevances, err = imports.ScoreImportPaths(ctx, opts.Env, paths) 1146 return err 1147 }); err != nil { 1148 return err 1149 } 1150 } 1151 sort.Slice(paths, func(i, j int) bool { 1152 return relevances[paths[i]] > relevances[paths[j]] 1153 }) 1154 1155 for _, path := range paths { 1156 pkg := known[path] 1157 if pkg.GetTypes().Name() != id.Name { 1158 continue 1159 } 1160 imp := &importInfo{ 1161 importPath: path, 1162 pkg: pkg, 1163 } 1164 if imports.ImportPathToAssumedName(path) != pkg.GetTypes().Name() { 1165 imp.name = pkg.GetTypes().Name() 1166 } 1167 c.packageMembers(pkg.GetTypes(), unimportedScore(relevances[path]), imp, func(cand candidate) { 1168 c.deepState.enqueue(cand) 1169 }) 1170 if len(c.items) >= unimportedMemberTarget { 1171 return nil 1172 } 1173 } 1174 1175 ctx, cancel := context.WithCancel(ctx) 1176 1177 var mu sync.Mutex 1178 add := func(pkgExport imports.PackageExport) { 1179 mu.Lock() 1180 defer mu.Unlock() 1181 if _, ok := known[pkgExport.Fix.StmtInfo.ImportPath]; ok { 1182 return // We got this one above. 1183 } 1184 1185 // Continue with untyped proposals. 1186 pkg := types.NewPackage(pkgExport.Fix.StmtInfo.ImportPath, pkgExport.Fix.IdentName) 1187 for _, export := range pkgExport.Exports { 1188 score := unimportedScore(pkgExport.Fix.Relevance) 1189 c.deepState.enqueue(candidate{ 1190 obj: types.NewVar(0, pkg, export, nil), 1191 score: score, 1192 imp: &importInfo{ 1193 importPath: pkgExport.Fix.StmtInfo.ImportPath, 1194 name: pkgExport.Fix.StmtInfo.Name, 1195 }, 1196 }) 1197 } 1198 if len(c.items) >= unimportedMemberTarget { 1199 cancel() 1200 } 1201 } 1202 1203 c.completionCallbacks = append(c.completionCallbacks, func(opts *imports.Options) error { 1204 defer cancel() 1205 return imports.GetPackageExports(ctx, add, id.Name, c.filename, c.pkg.GetTypes().Name(), opts.Env) 1206 }) 1207 return nil 1208 } 1209 1210 // unimportedScore returns a score for an unimported package that is generally 1211 // lower than other candidates. 1212 func unimportedScore(relevance float64) float64 { 1213 return (stdScore + .1*relevance) / 2 1214 } 1215 1216 func (c *completer) packageMembers(pkg *types.Package, score float64, imp *importInfo, cb func(candidate)) { 1217 scope := pkg.Scope() 1218 for _, name := range scope.Names() { 1219 obj := scope.Lookup(name) 1220 cb(candidate{ 1221 obj: obj, 1222 score: score, 1223 imp: imp, 1224 addressable: isVar(obj), 1225 }) 1226 } 1227 } 1228 1229 func (c *completer) methodsAndFields(typ types.Type, addressable bool, imp *importInfo, cb func(candidate)) { 1230 mset := c.methodSetCache[methodSetKey{typ, addressable}] 1231 if mset == nil { 1232 if addressable && !types.IsInterface(typ) && !isPointer(typ) { 1233 // Add methods of *T, which includes methods with receiver T. 1234 mset = types.NewMethodSet(types.NewPointer(typ)) 1235 } else { 1236 // Add methods of T. 1237 mset = types.NewMethodSet(typ) 1238 } 1239 c.methodSetCache[methodSetKey{typ, addressable}] = mset 1240 } 1241 1242 if typ.String() == "*testing.F" && addressable { 1243 // is that a sufficient test? (or is more care needed?) 1244 if c.fuzz(typ, mset, imp, cb, c.snapshot.FileSet()) { 1245 return 1246 } 1247 } 1248 1249 for i := 0; i < mset.Len(); i++ { 1250 cb(candidate{ 1251 obj: mset.At(i).Obj(), 1252 score: stdScore, 1253 imp: imp, 1254 addressable: addressable || isPointer(typ), 1255 }) 1256 } 1257 1258 // Add fields of T. 1259 eachField(typ, func(v *types.Var) { 1260 cb(candidate{ 1261 obj: v, 1262 score: stdScore - 0.01, 1263 imp: imp, 1264 addressable: addressable || isPointer(typ), 1265 }) 1266 }) 1267 } 1268 1269 // lexical finds completions in the lexical environment. 1270 func (c *completer) lexical(ctx context.Context) error { 1271 scopes := source.CollectScopes(c.pkg.GetTypesInfo(), c.path, c.pos) 1272 scopes = append(scopes, c.pkg.GetTypes().Scope(), types.Universe) 1273 1274 var ( 1275 builtinIota = types.Universe.Lookup("iota") 1276 builtinNil = types.Universe.Lookup("nil") 1277 // comparable is an interface that exists on the dev.typeparams Go branch. 1278 // Filter it out from completion results to stabilize tests. 1279 // TODO(rFindley) update (or remove) our handling for comparable once the 1280 // type parameter API has stabilized. 1281 builtinAny = types.Universe.Lookup("any") 1282 builtinComparable = types.Universe.Lookup("comparable") 1283 ) 1284 1285 // Track seen variables to avoid showing completions for shadowed variables. 1286 // This works since we look at scopes from innermost to outermost. 1287 seen := make(map[string]struct{}) 1288 1289 // Process scopes innermost first. 1290 for i, scope := range scopes { 1291 if scope == nil { 1292 continue 1293 } 1294 1295 Names: 1296 for _, name := range scope.Names() { 1297 declScope, obj := scope.LookupParent(name, c.pos) 1298 if declScope != scope { 1299 continue // Name was declared in some enclosing scope, or not at all. 1300 } 1301 if obj == builtinComparable || obj == builtinAny { 1302 continue 1303 } 1304 1305 // If obj's type is invalid, find the AST node that defines the lexical block 1306 // containing the declaration of obj. Don't resolve types for packages. 1307 if !isPkgName(obj) && !typeIsValid(obj.Type()) { 1308 // Match the scope to its ast.Node. If the scope is the package scope, 1309 // use the *ast.File as the starting node. 1310 var node ast.Node 1311 if i < len(c.path) { 1312 node = c.path[i] 1313 } else if i == len(c.path) { // use the *ast.File for package scope 1314 node = c.path[i-1] 1315 } 1316 if node != nil { 1317 if resolved := resolveInvalid(c.snapshot.FileSet(), obj, node, c.pkg.GetTypesInfo()); resolved != nil { 1318 obj = resolved 1319 } 1320 } 1321 } 1322 1323 // Don't use LHS of decl in RHS. 1324 for _, ident := range enclosingDeclLHS(c.path) { 1325 if obj.Pos() == ident.Pos() { 1326 continue Names 1327 } 1328 } 1329 1330 // Don't suggest "iota" outside of const decls. 1331 if obj == builtinIota && !c.inConstDecl() { 1332 continue 1333 } 1334 1335 // Rank outer scopes lower than inner. 1336 score := stdScore * math.Pow(.99, float64(i)) 1337 1338 // Dowrank "nil" a bit so it is ranked below more interesting candidates. 1339 if obj == builtinNil { 1340 score /= 2 1341 } 1342 1343 // If we haven't already added a candidate for an object with this name. 1344 if _, ok := seen[obj.Name()]; !ok { 1345 seen[obj.Name()] = struct{}{} 1346 c.deepState.enqueue(candidate{ 1347 obj: obj, 1348 score: score, 1349 addressable: isVar(obj), 1350 }) 1351 } 1352 } 1353 } 1354 1355 if c.inference.objType != nil { 1356 if named, _ := source.Deref(c.inference.objType).(*types.Named); named != nil { 1357 // If we expected a named type, check the type's package for 1358 // completion items. This is useful when the current file hasn't 1359 // imported the type's package yet. 1360 1361 if named.Obj() != nil && named.Obj().Pkg() != nil { 1362 pkg := named.Obj().Pkg() 1363 1364 // Make sure the package name isn't already in use by another 1365 // object, and that this file doesn't import the package yet. 1366 if _, ok := seen[pkg.Name()]; !ok && pkg != c.pkg.GetTypes() && !alreadyImports(c.file, pkg.Path()) { 1367 seen[pkg.Name()] = struct{}{} 1368 obj := types.NewPkgName(0, nil, pkg.Name(), pkg) 1369 imp := &importInfo{ 1370 importPath: pkg.Path(), 1371 } 1372 if imports.ImportPathToAssumedName(pkg.Path()) != pkg.Name() { 1373 imp.name = pkg.Name() 1374 } 1375 c.deepState.enqueue(candidate{ 1376 obj: obj, 1377 score: stdScore, 1378 imp: imp, 1379 }) 1380 } 1381 } 1382 } 1383 } 1384 1385 if c.opts.unimported { 1386 if err := c.unimportedPackages(ctx, seen); err != nil { 1387 return err 1388 } 1389 } 1390 1391 if c.inference.typeName.isTypeParam { 1392 // If we are completing a type param, offer each structural type. 1393 // This ensures we suggest "[]int" and "[]float64" for a constraint 1394 // with type union "[]int | []float64". 1395 if t, _ := c.inference.objType.(*types.Interface); t != nil { 1396 terms, _ := typeparams.InterfaceTermSet(t) 1397 for _, term := range terms { 1398 c.injectType(ctx, term.Type()) 1399 } 1400 } 1401 } else { 1402 c.injectType(ctx, c.inference.objType) 1403 } 1404 1405 // Add keyword completion items appropriate in the current context. 1406 c.addKeywordCompletions() 1407 1408 return nil 1409 } 1410 1411 // injectInferredType manufacters candidates based on the given type. 1412 // For example, if the type is "[]int", this method makes sure you get 1413 // candidates "[]int{}" and "[]int" (the latter applies when 1414 // completing a type name). 1415 func (c *completer) injectType(ctx context.Context, t types.Type) { 1416 if t == nil { 1417 return 1418 } 1419 1420 t = source.Deref(t) 1421 1422 // If we have an expected type and it is _not_ a named type, 1423 // handle it specially. Non-named types like "[]int" will never be 1424 // considered via a lexical search, so we need to directly inject 1425 // them. 1426 if _, named := t.(*types.Named); !named { 1427 // If our expected type is "[]int", this will add a literal 1428 // candidate of "[]int{}". 1429 c.literal(ctx, t, nil) 1430 1431 if _, isBasic := t.(*types.Basic); !isBasic { 1432 // If we expect a non-basic type name (e.g. "[]int"), hack up 1433 // a named type whose name is literally "[]int". This allows 1434 // us to reuse our object based completion machinery. 1435 fakeNamedType := candidate{ 1436 obj: types.NewTypeName(token.NoPos, nil, types.TypeString(t, c.qf), t), 1437 score: stdScore, 1438 } 1439 // Make sure the type name matches before considering 1440 // candidate. This cuts down on useless candidates. 1441 if c.matchingTypeName(&fakeNamedType) { 1442 c.deepState.enqueue(fakeNamedType) 1443 } 1444 } 1445 } 1446 } 1447 1448 func (c *completer) unimportedPackages(ctx context.Context, seen map[string]struct{}) error { 1449 var prefix string 1450 if c.surrounding != nil { 1451 prefix = c.surrounding.Prefix() 1452 } 1453 1454 // Don't suggest unimported packages if we have absolutely nothing 1455 // to go on. 1456 if prefix == "" { 1457 return nil 1458 } 1459 1460 count := 0 1461 1462 known, err := c.snapshot.CachedImportPaths(ctx) 1463 if err != nil { 1464 return err 1465 } 1466 var paths []string 1467 for path, pkg := range known { 1468 if !strings.HasPrefix(pkg.GetTypes().Name(), prefix) { 1469 continue 1470 } 1471 paths = append(paths, path) 1472 } 1473 1474 var relevances map[string]float64 1475 if len(paths) != 0 { 1476 if err := c.snapshot.RunProcessEnvFunc(ctx, func(opts *imports.Options) error { 1477 var err error 1478 relevances, err = imports.ScoreImportPaths(ctx, opts.Env, paths) 1479 return err 1480 }); err != nil { 1481 return err 1482 } 1483 } 1484 1485 sort.Slice(paths, func(i, j int) bool { 1486 if relevances[paths[i]] != relevances[paths[j]] { 1487 return relevances[paths[i]] > relevances[paths[j]] 1488 } 1489 1490 // Fall back to lexical sort to keep truncated set of candidates 1491 // in a consistent order. 1492 return paths[i] < paths[j] 1493 }) 1494 1495 for _, path := range paths { 1496 pkg := known[path] 1497 if _, ok := seen[pkg.GetTypes().Name()]; ok { 1498 continue 1499 } 1500 imp := &importInfo{ 1501 importPath: path, 1502 pkg: pkg, 1503 } 1504 if imports.ImportPathToAssumedName(path) != pkg.GetTypes().Name() { 1505 imp.name = pkg.GetTypes().Name() 1506 } 1507 if count >= maxUnimportedPackageNames { 1508 return nil 1509 } 1510 c.deepState.enqueue(candidate{ 1511 // Pass an empty *types.Package to disable deep completions. 1512 obj: types.NewPkgName(0, nil, pkg.GetTypes().Name(), types.NewPackage(path, pkg.Name())), 1513 score: unimportedScore(relevances[path]), 1514 imp: imp, 1515 }) 1516 count++ 1517 } 1518 1519 ctx, cancel := context.WithCancel(ctx) 1520 1521 var mu sync.Mutex 1522 add := func(pkg imports.ImportFix) { 1523 mu.Lock() 1524 defer mu.Unlock() 1525 if _, ok := seen[pkg.IdentName]; ok { 1526 return 1527 } 1528 if _, ok := relevances[pkg.StmtInfo.ImportPath]; ok { 1529 return 1530 } 1531 1532 if count >= maxUnimportedPackageNames { 1533 cancel() 1534 return 1535 } 1536 1537 // Do not add the unimported packages to seen, since we can have 1538 // multiple packages of the same name as completion suggestions, since 1539 // only one will be chosen. 1540 obj := types.NewPkgName(0, nil, pkg.IdentName, types.NewPackage(pkg.StmtInfo.ImportPath, pkg.IdentName)) 1541 c.deepState.enqueue(candidate{ 1542 obj: obj, 1543 score: unimportedScore(pkg.Relevance), 1544 imp: &importInfo{ 1545 importPath: pkg.StmtInfo.ImportPath, 1546 name: pkg.StmtInfo.Name, 1547 }, 1548 }) 1549 count++ 1550 } 1551 c.completionCallbacks = append(c.completionCallbacks, func(opts *imports.Options) error { 1552 defer cancel() 1553 return imports.GetAllCandidates(ctx, add, prefix, c.filename, c.pkg.GetTypes().Name(), opts.Env) 1554 }) 1555 return nil 1556 } 1557 1558 // alreadyImports reports whether f has an import with the specified path. 1559 func alreadyImports(f *ast.File, path string) bool { 1560 for _, s := range f.Imports { 1561 if source.ImportPath(s) == path { 1562 return true 1563 } 1564 } 1565 return false 1566 } 1567 1568 func (c *completer) inConstDecl() bool { 1569 for _, n := range c.path { 1570 if decl, ok := n.(*ast.GenDecl); ok && decl.Tok == token.CONST { 1571 return true 1572 } 1573 } 1574 return false 1575 } 1576 1577 // structLiteralFieldName finds completions for struct field names inside a struct literal. 1578 func (c *completer) structLiteralFieldName(ctx context.Context) error { 1579 clInfo := c.enclosingCompositeLiteral 1580 1581 // Mark fields of the composite literal that have already been set, 1582 // except for the current field. 1583 addedFields := make(map[*types.Var]bool) 1584 for _, el := range clInfo.cl.Elts { 1585 if kvExpr, ok := el.(*ast.KeyValueExpr); ok { 1586 if clInfo.kv == kvExpr { 1587 continue 1588 } 1589 1590 if key, ok := kvExpr.Key.(*ast.Ident); ok { 1591 if used, ok := c.pkg.GetTypesInfo().Uses[key]; ok { 1592 if usedVar, ok := used.(*types.Var); ok { 1593 addedFields[usedVar] = true 1594 } 1595 } 1596 } 1597 } 1598 } 1599 1600 deltaScore := 0.0001 1601 switch t := clInfo.clType.(type) { 1602 case *types.Struct: 1603 for i := 0; i < t.NumFields(); i++ { 1604 field := t.Field(i) 1605 if !addedFields[field] { 1606 c.deepState.enqueue(candidate{ 1607 obj: field, 1608 score: highScore - float64(i)*deltaScore, 1609 }) 1610 } 1611 } 1612 1613 // Add lexical completions if we aren't certain we are in the key part of a 1614 // key-value pair. 1615 if clInfo.maybeInFieldName { 1616 return c.lexical(ctx) 1617 } 1618 default: 1619 return c.lexical(ctx) 1620 } 1621 1622 return nil 1623 } 1624 1625 func (cl *compLitInfo) isStruct() bool { 1626 _, ok := cl.clType.(*types.Struct) 1627 return ok 1628 } 1629 1630 // enclosingCompositeLiteral returns information about the composite literal enclosing the 1631 // position. 1632 func enclosingCompositeLiteral(path []ast.Node, pos token.Pos, info *types.Info) *compLitInfo { 1633 for _, n := range path { 1634 switch n := n.(type) { 1635 case *ast.CompositeLit: 1636 // The enclosing node will be a composite literal if the user has just 1637 // opened the curly brace (e.g. &x{<>) or the completion request is triggered 1638 // from an already completed composite literal expression (e.g. &x{foo: 1, <>}) 1639 // 1640 // The position is not part of the composite literal unless it falls within the 1641 // curly braces (e.g. "foo.Foo<>Struct{}"). 1642 if !(n.Lbrace < pos && pos <= n.Rbrace) { 1643 // Keep searching since we may yet be inside a composite literal. 1644 // For example "Foo{B: Ba<>{}}". 1645 break 1646 } 1647 1648 tv, ok := info.Types[n] 1649 if !ok { 1650 return nil 1651 } 1652 1653 clInfo := compLitInfo{ 1654 cl: n, 1655 clType: source.Deref(tv.Type).Underlying(), 1656 } 1657 1658 var ( 1659 expr ast.Expr 1660 hasKeys bool 1661 ) 1662 for _, el := range n.Elts { 1663 // Remember the expression that the position falls in, if any. 1664 if el.Pos() <= pos && pos <= el.End() { 1665 expr = el 1666 } 1667 1668 if kv, ok := el.(*ast.KeyValueExpr); ok { 1669 hasKeys = true 1670 // If expr == el then we know the position falls in this expression, 1671 // so also record kv as the enclosing *ast.KeyValueExpr. 1672 if expr == el { 1673 clInfo.kv = kv 1674 break 1675 } 1676 } 1677 } 1678 1679 if clInfo.kv != nil { 1680 // If in a *ast.KeyValueExpr, we know we are in the key if the position 1681 // is to the left of the colon (e.g. "Foo{F<>: V}". 1682 clInfo.inKey = pos <= clInfo.kv.Colon 1683 } else if hasKeys { 1684 // If we aren't in a *ast.KeyValueExpr but the composite literal has 1685 // other *ast.KeyValueExprs, we must be on the key side of a new 1686 // *ast.KeyValueExpr (e.g. "Foo{F: V, <>}"). 1687 clInfo.inKey = true 1688 } else { 1689 switch clInfo.clType.(type) { 1690 case *types.Struct: 1691 if len(n.Elts) == 0 { 1692 // If the struct literal is empty, next could be a struct field 1693 // name or an expression (e.g. "Foo{<>}" could become "Foo{F:}" 1694 // or "Foo{someVar}"). 1695 clInfo.maybeInFieldName = true 1696 } else if len(n.Elts) == 1 { 1697 // If there is one expression and the position is in that expression 1698 // and the expression is an identifier, we may be writing a field 1699 // name or an expression (e.g. "Foo{F<>}"). 1700 _, clInfo.maybeInFieldName = expr.(*ast.Ident) 1701 } 1702 case *types.Map: 1703 // If we aren't in a *ast.KeyValueExpr we must be adding a new key 1704 // to the map. 1705 clInfo.inKey = true 1706 } 1707 } 1708 1709 return &clInfo 1710 default: 1711 if breaksExpectedTypeInference(n, pos) { 1712 return nil 1713 } 1714 } 1715 } 1716 1717 return nil 1718 } 1719 1720 // enclosingFunction returns the signature and body of the function 1721 // enclosing the given position. 1722 func enclosingFunction(path []ast.Node, info *types.Info) *funcInfo { 1723 for _, node := range path { 1724 switch t := node.(type) { 1725 case *ast.FuncDecl: 1726 if obj, ok := info.Defs[t.Name]; ok { 1727 return &funcInfo{ 1728 sig: obj.Type().(*types.Signature), 1729 body: t.Body, 1730 } 1731 } 1732 case *ast.FuncLit: 1733 if typ, ok := info.Types[t]; ok { 1734 if sig, _ := typ.Type.(*types.Signature); sig == nil { 1735 // golang/go#49397: it should not be possible, but we somehow arrived 1736 // here with a non-signature type, most likely due to AST mangling 1737 // such that node.Type is not a FuncType. 1738 return nil 1739 } 1740 return &funcInfo{ 1741 sig: typ.Type.(*types.Signature), 1742 body: t.Body, 1743 } 1744 } 1745 } 1746 } 1747 return nil 1748 } 1749 1750 func (c *completer) expectedCompositeLiteralType() types.Type { 1751 clInfo := c.enclosingCompositeLiteral 1752 switch t := clInfo.clType.(type) { 1753 case *types.Slice: 1754 if clInfo.inKey { 1755 return types.Typ[types.UntypedInt] 1756 } 1757 return t.Elem() 1758 case *types.Array: 1759 if clInfo.inKey { 1760 return types.Typ[types.UntypedInt] 1761 } 1762 return t.Elem() 1763 case *types.Map: 1764 if clInfo.inKey { 1765 return t.Key() 1766 } 1767 return t.Elem() 1768 case *types.Struct: 1769 // If we are completing a key (i.e. field name), there is no expected type. 1770 if clInfo.inKey { 1771 return nil 1772 } 1773 1774 // If we are in a key-value pair, but not in the key, then we must be on the 1775 // value side. The expected type of the value will be determined from the key. 1776 if clInfo.kv != nil { 1777 if key, ok := clInfo.kv.Key.(*ast.Ident); ok { 1778 for i := 0; i < t.NumFields(); i++ { 1779 if field := t.Field(i); field.Name() == key.Name { 1780 return field.Type() 1781 } 1782 } 1783 } 1784 } else { 1785 // If we aren't in a key-value pair and aren't in the key, we must be using 1786 // implicit field names. 1787 1788 // The order of the literal fields must match the order in the struct definition. 1789 // Find the element that the position belongs to and suggest that field's type. 1790 if i := exprAtPos(c.pos, clInfo.cl.Elts); i < t.NumFields() { 1791 return t.Field(i).Type() 1792 } 1793 } 1794 } 1795 return nil 1796 } 1797 1798 // typeMod represents an operator that changes the expected type. 1799 type typeMod struct { 1800 mod typeModKind 1801 arrayLen int64 1802 } 1803 1804 type typeModKind int 1805 1806 const ( 1807 dereference typeModKind = iota // pointer indirection: "*" 1808 reference // adds level of pointer: "&" for values, "*" for type names 1809 chanRead // channel read operator: "<-" 1810 sliceType // make a slice type: "[]" in "[]int" 1811 arrayType // make an array type: "[2]" in "[2]int" 1812 invoke // make a function call: "()" in "foo()" 1813 takeSlice // take slice of array: "[:]" in "foo[:]" 1814 takeDotDotDot // turn slice into variadic args: "..." in "foo..." 1815 index // index into slice/array: "[0]" in "foo[0]" 1816 ) 1817 1818 type objKind int 1819 1820 const ( 1821 kindAny objKind = 0 1822 kindArray objKind = 1 << iota 1823 kindSlice 1824 kindChan 1825 kindMap 1826 kindStruct 1827 kindString 1828 kindInt 1829 kindBool 1830 kindBytes 1831 kindPtr 1832 kindFloat 1833 kindComplex 1834 kindError 1835 kindStringer 1836 kindFunc 1837 ) 1838 1839 // penalizedObj represents an object that should be disfavored as a 1840 // completion candidate. 1841 type penalizedObj struct { 1842 // objChain is the full "chain", e.g. "foo.bar().baz" becomes 1843 // []types.Object{foo, bar, baz}. 1844 objChain []types.Object 1845 // penalty is score penalty in the range (0, 1). 1846 penalty float64 1847 } 1848 1849 // candidateInference holds information we have inferred about a type that can be 1850 // used at the current position. 1851 type candidateInference struct { 1852 // objType is the desired type of an object used at the query position. 1853 objType types.Type 1854 1855 // objKind is a mask of expected kinds of types such as "map", "slice", etc. 1856 objKind objKind 1857 1858 // variadic is true if we are completing the initial variadic 1859 // parameter. For example: 1860 // append([]T{}, <>) // objType=T variadic=true 1861 // append([]T{}, T{}, <>) // objType=T variadic=false 1862 variadic bool 1863 1864 // modifiers are prefixes such as "*", "&" or "<-" that influence how 1865 // a candidate type relates to the expected type. 1866 modifiers []typeMod 1867 1868 // convertibleTo is a type our candidate type must be convertible to. 1869 convertibleTo types.Type 1870 1871 // typeName holds information about the expected type name at 1872 // position, if any. 1873 typeName typeNameInference 1874 1875 // assignees are the types that would receive a function call's 1876 // results at the position. For example: 1877 // 1878 // foo := 123 1879 // foo, bar := <> 1880 // 1881 // at "<>", the assignees are [int, <invalid>]. 1882 assignees []types.Type 1883 1884 // variadicAssignees is true if we could be completing an inner 1885 // function call that fills out an outer function call's variadic 1886 // params. For example: 1887 // 1888 // func foo(int, ...string) {} 1889 // 1890 // foo(<>) // variadicAssignees=true 1891 // foo(bar<>) // variadicAssignees=true 1892 // foo(bar, baz<>) // variadicAssignees=false 1893 variadicAssignees bool 1894 1895 // penalized holds expressions that should be disfavored as 1896 // candidates. For example, it tracks expressions already used in a 1897 // switch statement's other cases. Each expression is tracked using 1898 // its entire object "chain" allowing differentiation between 1899 // "a.foo" and "b.foo" when "a" and "b" are the same type. 1900 penalized []penalizedObj 1901 1902 // objChain contains the chain of objects representing the 1903 // surrounding *ast.SelectorExpr. For example, if we are completing 1904 // "foo.bar.ba<>", objChain will contain []types.Object{foo, bar}. 1905 objChain []types.Object 1906 } 1907 1908 // typeNameInference holds information about the expected type name at 1909 // position. 1910 type typeNameInference struct { 1911 // wantTypeName is true if we expect the name of a type. 1912 wantTypeName bool 1913 1914 // modifiers are prefixes such as "*", "&" or "<-" that influence how 1915 // a candidate type relates to the expected type. 1916 modifiers []typeMod 1917 1918 // assertableFrom is a type that must be assertable to our candidate type. 1919 assertableFrom types.Type 1920 1921 // wantComparable is true if we want a comparable type. 1922 wantComparable bool 1923 1924 // seenTypeSwitchCases tracks types that have already been used by 1925 // the containing type switch. 1926 seenTypeSwitchCases []types.Type 1927 1928 // compLitType is true if we are completing a composite literal type 1929 // name, e.g "foo<>{}". 1930 compLitType bool 1931 1932 // isTypeParam is true if we are completing a type instantiation parameter 1933 isTypeParam bool 1934 } 1935 1936 // expectedCandidate returns information about the expected candidate 1937 // for an expression at the query position. 1938 func expectedCandidate(ctx context.Context, c *completer) (inf candidateInference) { 1939 inf.typeName = expectTypeName(c) 1940 1941 if c.enclosingCompositeLiteral != nil { 1942 inf.objType = c.expectedCompositeLiteralType() 1943 } 1944 1945 Nodes: 1946 for i, node := range c.path { 1947 switch node := node.(type) { 1948 case *ast.BinaryExpr: 1949 // Determine if query position comes from left or right of op. 1950 e := node.X 1951 if c.pos < node.OpPos { 1952 e = node.Y 1953 } 1954 if tv, ok := c.pkg.GetTypesInfo().Types[e]; ok { 1955 switch node.Op { 1956 case token.LAND, token.LOR: 1957 // Don't infer "bool" type for "&&" or "||". Often you want 1958 // to compose a boolean expression from non-boolean 1959 // candidates. 1960 default: 1961 inf.objType = tv.Type 1962 } 1963 break Nodes 1964 } 1965 case *ast.AssignStmt: 1966 // Only rank completions if you are on the right side of the token. 1967 if c.pos > node.TokPos { 1968 i := exprAtPos(c.pos, node.Rhs) 1969 if i >= len(node.Lhs) { 1970 i = len(node.Lhs) - 1 1971 } 1972 if tv, ok := c.pkg.GetTypesInfo().Types[node.Lhs[i]]; ok { 1973 inf.objType = tv.Type 1974 } 1975 1976 // If we have a single expression on the RHS, record the LHS 1977 // assignees so we can favor multi-return function calls with 1978 // matching result values. 1979 if len(node.Rhs) <= 1 { 1980 for _, lhs := range node.Lhs { 1981 inf.assignees = append(inf.assignees, c.pkg.GetTypesInfo().TypeOf(lhs)) 1982 } 1983 } else { 1984 // Otherwise, record our single assignee, even if its type is 1985 // not available. We use this info to downrank functions 1986 // with the wrong number of result values. 1987 inf.assignees = append(inf.assignees, c.pkg.GetTypesInfo().TypeOf(node.Lhs[i])) 1988 } 1989 } 1990 return inf 1991 case *ast.ValueSpec: 1992 if node.Type != nil && c.pos > node.Type.End() { 1993 inf.objType = c.pkg.GetTypesInfo().TypeOf(node.Type) 1994 } 1995 return inf 1996 case *ast.CallExpr: 1997 // Only consider CallExpr args if position falls between parens. 1998 if node.Lparen < c.pos && c.pos <= node.Rparen { 1999 // For type conversions like "int64(foo)" we can only infer our 2000 // desired type is convertible to int64. 2001 if typ := typeConversion(node, c.pkg.GetTypesInfo()); typ != nil { 2002 inf.convertibleTo = typ 2003 break Nodes 2004 } 2005 2006 if tv, ok := c.pkg.GetTypesInfo().Types[node.Fun]; ok { 2007 if sig, ok := tv.Type.(*types.Signature); ok { 2008 numParams := sig.Params().Len() 2009 if numParams == 0 { 2010 return inf 2011 } 2012 2013 exprIdx := exprAtPos(c.pos, node.Args) 2014 2015 // If we have one or zero arg expressions, we may be 2016 // completing to a function call that returns multiple 2017 // values, in turn getting passed in to the surrounding 2018 // call. Record the assignees so we can favor function 2019 // calls that return matching values. 2020 if len(node.Args) <= 1 && exprIdx == 0 { 2021 for i := 0; i < sig.Params().Len(); i++ { 2022 inf.assignees = append(inf.assignees, sig.Params().At(i).Type()) 2023 } 2024 2025 // Record that we may be completing into variadic parameters. 2026 inf.variadicAssignees = sig.Variadic() 2027 } 2028 2029 // Make sure not to run past the end of expected parameters. 2030 if exprIdx >= numParams { 2031 inf.objType = sig.Params().At(numParams - 1).Type() 2032 } else { 2033 inf.objType = sig.Params().At(exprIdx).Type() 2034 } 2035 2036 if sig.Variadic() && exprIdx >= (numParams-1) { 2037 // If we are completing a variadic param, deslice the variadic type. 2038 inf.objType = deslice(inf.objType) 2039 // Record whether we are completing the initial variadic param. 2040 inf.variadic = exprIdx == numParams-1 && len(node.Args) <= numParams 2041 2042 // Check if we can infer object kind from printf verb. 2043 inf.objKind |= printfArgKind(c.pkg.GetTypesInfo(), node, exprIdx) 2044 } 2045 } 2046 } 2047 2048 if funIdent, ok := node.Fun.(*ast.Ident); ok { 2049 obj := c.pkg.GetTypesInfo().ObjectOf(funIdent) 2050 2051 if obj != nil && obj.Parent() == types.Universe { 2052 // Defer call to builtinArgType so we can provide it the 2053 // inferred type from its parent node. 2054 defer func() { 2055 inf = c.builtinArgType(obj, node, inf) 2056 inf.objKind = c.builtinArgKind(ctx, obj, node) 2057 }() 2058 2059 // The expected type of builtin arguments like append() is 2060 // the expected type of the builtin call itself. For 2061 // example: 2062 // 2063 // var foo []int = append(<>) 2064 // 2065 // To find the expected type at <> we "skip" the append() 2066 // node and get the expected type one level up, which is 2067 // []int. 2068 continue Nodes 2069 } 2070 } 2071 2072 return inf 2073 } 2074 case *ast.ReturnStmt: 2075 if c.enclosingFunc != nil { 2076 sig := c.enclosingFunc.sig 2077 // Find signature result that corresponds to our return statement. 2078 if resultIdx := exprAtPos(c.pos, node.Results); resultIdx < len(node.Results) { 2079 if resultIdx < sig.Results().Len() { 2080 inf.objType = sig.Results().At(resultIdx).Type() 2081 } 2082 } 2083 } 2084 return inf 2085 case *ast.CaseClause: 2086 if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, node).(*ast.SwitchStmt); ok { 2087 if tv, ok := c.pkg.GetTypesInfo().Types[swtch.Tag]; ok { 2088 inf.objType = tv.Type 2089 2090 // Record which objects have already been used in the case 2091 // statements so we don't suggest them again. 2092 for _, cc := range swtch.Body.List { 2093 for _, caseExpr := range cc.(*ast.CaseClause).List { 2094 // Don't record the expression we are currently completing. 2095 if caseExpr.Pos() < c.pos && c.pos <= caseExpr.End() { 2096 continue 2097 } 2098 2099 if objs := objChain(c.pkg.GetTypesInfo(), caseExpr); len(objs) > 0 { 2100 inf.penalized = append(inf.penalized, penalizedObj{objChain: objs, penalty: 0.1}) 2101 } 2102 } 2103 } 2104 } 2105 } 2106 return inf 2107 case *ast.SliceExpr: 2108 // Make sure position falls within the brackets (e.g. "foo[a:<>]"). 2109 if node.Lbrack < c.pos && c.pos <= node.Rbrack { 2110 inf.objType = types.Typ[types.UntypedInt] 2111 } 2112 return inf 2113 case *ast.IndexExpr: 2114 // Make sure position falls within the brackets (e.g. "foo[<>]"). 2115 if node.Lbrack < c.pos && c.pos <= node.Rbrack { 2116 if tv, ok := c.pkg.GetTypesInfo().Types[node.X]; ok { 2117 switch t := tv.Type.Underlying().(type) { 2118 case *types.Map: 2119 inf.objType = t.Key() 2120 case *types.Slice, *types.Array: 2121 inf.objType = types.Typ[types.UntypedInt] 2122 } 2123 2124 if ct := expectedConstraint(tv.Type, 0); ct != nil { 2125 inf.objType = ct 2126 inf.typeName.wantTypeName = true 2127 inf.typeName.isTypeParam = true 2128 } 2129 } 2130 } 2131 return inf 2132 case *typeparams.IndexListExpr: 2133 if node.Lbrack < c.pos && c.pos <= node.Rbrack { 2134 if tv, ok := c.pkg.GetTypesInfo().Types[node.X]; ok { 2135 if ct := expectedConstraint(tv.Type, exprAtPos(c.pos, node.Indices)); ct != nil { 2136 inf.objType = ct 2137 inf.typeName.wantTypeName = true 2138 inf.typeName.isTypeParam = true 2139 } 2140 } 2141 } 2142 return inf 2143 case *ast.SendStmt: 2144 // Make sure we are on right side of arrow (e.g. "foo <- <>"). 2145 if c.pos > node.Arrow+1 { 2146 if tv, ok := c.pkg.GetTypesInfo().Types[node.Chan]; ok { 2147 if ch, ok := tv.Type.Underlying().(*types.Chan); ok { 2148 inf.objType = ch.Elem() 2149 } 2150 } 2151 } 2152 return inf 2153 case *ast.RangeStmt: 2154 if source.NodeContains(node.X, c.pos) { 2155 inf.objKind |= kindSlice | kindArray | kindMap | kindString 2156 if node.Value == nil { 2157 inf.objKind |= kindChan 2158 } 2159 } 2160 return inf 2161 case *ast.StarExpr: 2162 inf.modifiers = append(inf.modifiers, typeMod{mod: dereference}) 2163 case *ast.UnaryExpr: 2164 switch node.Op { 2165 case token.AND: 2166 inf.modifiers = append(inf.modifiers, typeMod{mod: reference}) 2167 case token.ARROW: 2168 inf.modifiers = append(inf.modifiers, typeMod{mod: chanRead}) 2169 } 2170 case *ast.DeferStmt, *ast.GoStmt: 2171 inf.objKind |= kindFunc 2172 return inf 2173 default: 2174 if breaksExpectedTypeInference(node, c.pos) { 2175 return inf 2176 } 2177 } 2178 } 2179 2180 return inf 2181 } 2182 2183 func expectedConstraint(t types.Type, idx int) types.Type { 2184 var tp *typeparams.TypeParamList 2185 if named, _ := t.(*types.Named); named != nil { 2186 tp = typeparams.ForNamed(named) 2187 } else if sig, _ := t.Underlying().(*types.Signature); sig != nil { 2188 tp = typeparams.ForSignature(sig) 2189 } 2190 if tp == nil || idx >= tp.Len() { 2191 return nil 2192 } 2193 return tp.At(idx).Constraint() 2194 } 2195 2196 // objChain decomposes e into a chain of objects if possible. For 2197 // example, "foo.bar().baz" will yield []types.Object{foo, bar, baz}. 2198 // If any part can't be turned into an object, return nil. 2199 func objChain(info *types.Info, e ast.Expr) []types.Object { 2200 var objs []types.Object 2201 2202 for e != nil { 2203 switch n := e.(type) { 2204 case *ast.Ident: 2205 obj := info.ObjectOf(n) 2206 if obj == nil { 2207 return nil 2208 } 2209 objs = append(objs, obj) 2210 e = nil 2211 case *ast.SelectorExpr: 2212 obj := info.ObjectOf(n.Sel) 2213 if obj == nil { 2214 return nil 2215 } 2216 objs = append(objs, obj) 2217 e = n.X 2218 case *ast.CallExpr: 2219 if len(n.Args) > 0 { 2220 return nil 2221 } 2222 e = n.Fun 2223 default: 2224 return nil 2225 } 2226 } 2227 2228 // Reverse order so the layout matches the syntactic order. 2229 for i := 0; i < len(objs)/2; i++ { 2230 objs[i], objs[len(objs)-1-i] = objs[len(objs)-1-i], objs[i] 2231 } 2232 2233 return objs 2234 } 2235 2236 // applyTypeModifiers applies the list of type modifiers to a type. 2237 // It returns nil if the modifiers could not be applied. 2238 func (ci candidateInference) applyTypeModifiers(typ types.Type, addressable bool) types.Type { 2239 for _, mod := range ci.modifiers { 2240 switch mod.mod { 2241 case dereference: 2242 // For every "*" indirection operator, remove a pointer layer 2243 // from candidate type. 2244 if ptr, ok := typ.Underlying().(*types.Pointer); ok { 2245 typ = ptr.Elem() 2246 } else { 2247 return nil 2248 } 2249 case reference: 2250 // For every "&" address operator, add another pointer layer to 2251 // candidate type, if the candidate is addressable. 2252 if addressable { 2253 typ = types.NewPointer(typ) 2254 } else { 2255 return nil 2256 } 2257 case chanRead: 2258 // For every "<-" operator, remove a layer of channelness. 2259 if ch, ok := typ.(*types.Chan); ok { 2260 typ = ch.Elem() 2261 } else { 2262 return nil 2263 } 2264 } 2265 } 2266 2267 return typ 2268 } 2269 2270 // applyTypeNameModifiers applies the list of type modifiers to a type name. 2271 func (ci candidateInference) applyTypeNameModifiers(typ types.Type) types.Type { 2272 for _, mod := range ci.typeName.modifiers { 2273 switch mod.mod { 2274 case reference: 2275 typ = types.NewPointer(typ) 2276 case arrayType: 2277 typ = types.NewArray(typ, mod.arrayLen) 2278 case sliceType: 2279 typ = types.NewSlice(typ) 2280 } 2281 } 2282 return typ 2283 } 2284 2285 // matchesVariadic returns true if we are completing a variadic 2286 // parameter and candType is a compatible slice type. 2287 func (ci candidateInference) matchesVariadic(candType types.Type) bool { 2288 return ci.variadic && ci.objType != nil && types.AssignableTo(candType, types.NewSlice(ci.objType)) 2289 } 2290 2291 // findSwitchStmt returns an *ast.CaseClause's corresponding *ast.SwitchStmt or 2292 // *ast.TypeSwitchStmt. path should start from the case clause's first ancestor. 2293 func findSwitchStmt(path []ast.Node, pos token.Pos, c *ast.CaseClause) ast.Stmt { 2294 // Make sure position falls within a "case <>:" clause. 2295 if exprAtPos(pos, c.List) >= len(c.List) { 2296 return nil 2297 } 2298 // A case clause is always nested within a block statement in a switch statement. 2299 if len(path) < 2 { 2300 return nil 2301 } 2302 if _, ok := path[0].(*ast.BlockStmt); !ok { 2303 return nil 2304 } 2305 switch s := path[1].(type) { 2306 case *ast.SwitchStmt: 2307 return s 2308 case *ast.TypeSwitchStmt: 2309 return s 2310 default: 2311 return nil 2312 } 2313 } 2314 2315 // breaksExpectedTypeInference reports if an expression node's type is unrelated 2316 // to its child expression node types. For example, "Foo{Bar: x.Baz(<>)}" should 2317 // expect a function argument, not a composite literal value. 2318 func breaksExpectedTypeInference(n ast.Node, pos token.Pos) bool { 2319 switch n := n.(type) { 2320 case *ast.CompositeLit: 2321 // Doesn't break inference if pos is in type name. 2322 // For example: "Foo<>{Bar: 123}" 2323 return !source.NodeContains(n.Type, pos) 2324 case *ast.CallExpr: 2325 // Doesn't break inference if pos is in func name. 2326 // For example: "Foo<>(123)" 2327 return !source.NodeContains(n.Fun, pos) 2328 case *ast.FuncLit, *ast.IndexExpr, *ast.SliceExpr: 2329 return true 2330 default: 2331 return false 2332 } 2333 } 2334 2335 // expectTypeName returns information about the expected type name at position. 2336 func expectTypeName(c *completer) typeNameInference { 2337 var inf typeNameInference 2338 2339 Nodes: 2340 for i, p := range c.path { 2341 switch n := p.(type) { 2342 case *ast.FieldList: 2343 // Expect a type name if pos is in a FieldList. This applies to 2344 // FuncType params/results, FuncDecl receiver, StructType, and 2345 // InterfaceType. We don't need to worry about the field name 2346 // because completion bails out early if pos is in an *ast.Ident 2347 // that defines an object. 2348 inf.wantTypeName = true 2349 break Nodes 2350 case *ast.CaseClause: 2351 // Expect type names in type switch case clauses. 2352 if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, n).(*ast.TypeSwitchStmt); ok { 2353 // The case clause types must be assertable from the type switch parameter. 2354 ast.Inspect(swtch.Assign, func(n ast.Node) bool { 2355 if ta, ok := n.(*ast.TypeAssertExpr); ok { 2356 inf.assertableFrom = c.pkg.GetTypesInfo().TypeOf(ta.X) 2357 return false 2358 } 2359 return true 2360 }) 2361 inf.wantTypeName = true 2362 2363 // Track the types that have already been used in this 2364 // switch's case statements so we don't recommend them. 2365 for _, e := range swtch.Body.List { 2366 for _, typeExpr := range e.(*ast.CaseClause).List { 2367 // Skip if type expression contains pos. We don't want to 2368 // count it as already used if the user is completing it. 2369 if typeExpr.Pos() < c.pos && c.pos <= typeExpr.End() { 2370 continue 2371 } 2372 2373 if t := c.pkg.GetTypesInfo().TypeOf(typeExpr); t != nil { 2374 inf.seenTypeSwitchCases = append(inf.seenTypeSwitchCases, t) 2375 } 2376 } 2377 } 2378 2379 break Nodes 2380 } 2381 return typeNameInference{} 2382 case *ast.TypeAssertExpr: 2383 // Expect type names in type assert expressions. 2384 if n.Lparen < c.pos && c.pos <= n.Rparen { 2385 // The type in parens must be assertable from the expression type. 2386 inf.assertableFrom = c.pkg.GetTypesInfo().TypeOf(n.X) 2387 inf.wantTypeName = true 2388 break Nodes 2389 } 2390 return typeNameInference{} 2391 case *ast.StarExpr: 2392 inf.modifiers = append(inf.modifiers, typeMod{mod: reference}) 2393 case *ast.CompositeLit: 2394 // We want a type name if position is in the "Type" part of a 2395 // composite literal (e.g. "Foo<>{}"). 2396 if n.Type != nil && n.Type.Pos() <= c.pos && c.pos <= n.Type.End() { 2397 inf.wantTypeName = true 2398 inf.compLitType = true 2399 2400 if i < len(c.path)-1 { 2401 // Track preceding "&" operator. Technically it applies to 2402 // the composite literal and not the type name, but if 2403 // affects our type completion nonetheless. 2404 if u, ok := c.path[i+1].(*ast.UnaryExpr); ok && u.Op == token.AND { 2405 inf.modifiers = append(inf.modifiers, typeMod{mod: reference}) 2406 } 2407 } 2408 } 2409 break Nodes 2410 case *ast.ArrayType: 2411 // If we are inside the "Elt" part of an array type, we want a type name. 2412 if n.Elt.Pos() <= c.pos && c.pos <= n.Elt.End() { 2413 inf.wantTypeName = true 2414 if n.Len == nil { 2415 // No "Len" expression means a slice type. 2416 inf.modifiers = append(inf.modifiers, typeMod{mod: sliceType}) 2417 } else { 2418 // Try to get the array type using the constant value of "Len". 2419 tv, ok := c.pkg.GetTypesInfo().Types[n.Len] 2420 if ok && tv.Value != nil && tv.Value.Kind() == constant.Int { 2421 if arrayLen, ok := constant.Int64Val(tv.Value); ok { 2422 inf.modifiers = append(inf.modifiers, typeMod{mod: arrayType, arrayLen: arrayLen}) 2423 } 2424 } 2425 } 2426 2427 // ArrayTypes can be nested, so keep going if our parent is an 2428 // ArrayType. 2429 if i < len(c.path)-1 { 2430 if _, ok := c.path[i+1].(*ast.ArrayType); ok { 2431 continue Nodes 2432 } 2433 } 2434 2435 break Nodes 2436 } 2437 case *ast.MapType: 2438 inf.wantTypeName = true 2439 if n.Key != nil { 2440 inf.wantComparable = source.NodeContains(n.Key, c.pos) 2441 } else { 2442 // If the key is empty, assume we are completing the key if 2443 // pos is directly after the "map[". 2444 inf.wantComparable = c.pos == n.Pos()+token.Pos(len("map[")) 2445 } 2446 break Nodes 2447 case *ast.ValueSpec: 2448 inf.wantTypeName = source.NodeContains(n.Type, c.pos) 2449 break Nodes 2450 case *ast.TypeSpec: 2451 inf.wantTypeName = source.NodeContains(n.Type, c.pos) 2452 default: 2453 if breaksExpectedTypeInference(p, c.pos) { 2454 return typeNameInference{} 2455 } 2456 } 2457 } 2458 2459 return inf 2460 } 2461 2462 func (c *completer) fakeObj(T types.Type) *types.Var { 2463 return types.NewVar(token.NoPos, c.pkg.GetTypes(), "", T) 2464 } 2465 2466 // derivableTypes iterates types you can derive from t. For example, 2467 // from "foo" we might derive "&foo", and "foo()". 2468 func derivableTypes(t types.Type, addressable bool, f func(t types.Type, addressable bool, mod typeModKind) bool) bool { 2469 switch t := t.Underlying().(type) { 2470 case *types.Signature: 2471 // If t is a func type with a single result, offer the result type. 2472 if t.Results().Len() == 1 && f(t.Results().At(0).Type(), false, invoke) { 2473 return true 2474 } 2475 case *types.Array: 2476 if f(t.Elem(), true, index) { 2477 return true 2478 } 2479 // Try converting array to slice. 2480 if f(types.NewSlice(t.Elem()), false, takeSlice) { 2481 return true 2482 } 2483 case *types.Pointer: 2484 if f(t.Elem(), false, dereference) { 2485 return true 2486 } 2487 case *types.Slice: 2488 if f(t.Elem(), true, index) { 2489 return true 2490 } 2491 case *types.Map: 2492 if f(t.Elem(), false, index) { 2493 return true 2494 } 2495 case *types.Chan: 2496 if f(t.Elem(), false, chanRead) { 2497 return true 2498 } 2499 } 2500 2501 // Check if c is addressable and a pointer to c matches our type inference. 2502 if addressable && f(types.NewPointer(t), false, reference) { 2503 return true 2504 } 2505 2506 return false 2507 } 2508 2509 // anyCandType reports whether f returns true for any candidate type 2510 // derivable from c. It searches up to three levels of type 2511 // modification. For example, given "foo" we could discover "***foo" 2512 // or "*foo()". 2513 func (c *candidate) anyCandType(f func(t types.Type, addressable bool) bool) bool { 2514 if c.obj == nil || c.obj.Type() == nil { 2515 return false 2516 } 2517 2518 const maxDepth = 3 2519 2520 var searchTypes func(t types.Type, addressable bool, mods []typeModKind) bool 2521 searchTypes = func(t types.Type, addressable bool, mods []typeModKind) bool { 2522 if f(t, addressable) { 2523 if len(mods) > 0 { 2524 newMods := make([]typeModKind, len(mods)+len(c.mods)) 2525 copy(newMods, mods) 2526 copy(newMods[len(mods):], c.mods) 2527 c.mods = newMods 2528 } 2529 return true 2530 } 2531 2532 if len(mods) == maxDepth { 2533 return false 2534 } 2535 2536 return derivableTypes(t, addressable, func(t types.Type, addressable bool, mod typeModKind) bool { 2537 return searchTypes(t, addressable, append(mods, mod)) 2538 }) 2539 } 2540 2541 return searchTypes(c.obj.Type(), c.addressable, make([]typeModKind, 0, maxDepth)) 2542 } 2543 2544 // matchingCandidate reports whether cand matches our type inferences. 2545 // It mutates cand's score in certain cases. 2546 func (c *completer) matchingCandidate(cand *candidate) bool { 2547 if c.completionContext.commentCompletion { 2548 return false 2549 } 2550 2551 // Bail out early if we are completing a field name in a composite literal. 2552 if v, ok := cand.obj.(*types.Var); ok && v.IsField() && c.wantStructFieldCompletions() { 2553 return true 2554 } 2555 2556 if isTypeName(cand.obj) { 2557 return c.matchingTypeName(cand) 2558 } else if c.wantTypeName() { 2559 // If we want a type, a non-type object never matches. 2560 return false 2561 } 2562 2563 if c.inference.candTypeMatches(cand) { 2564 return true 2565 } 2566 2567 candType := cand.obj.Type() 2568 if candType == nil { 2569 return false 2570 } 2571 2572 if sig, ok := candType.Underlying().(*types.Signature); ok { 2573 if c.inference.assigneesMatch(cand, sig) { 2574 // Invoke the candidate if its results are multi-assignable. 2575 cand.mods = append(cand.mods, invoke) 2576 return true 2577 } 2578 } 2579 2580 // Default to invoking *types.Func candidates. This is so function 2581 // completions in an empty statement (or other cases with no expected type) 2582 // are invoked by default. 2583 if isFunc(cand.obj) { 2584 cand.mods = append(cand.mods, invoke) 2585 } 2586 2587 return false 2588 } 2589 2590 // candTypeMatches reports whether cand makes a good completion 2591 // candidate given the candidate inference. cand's score may be 2592 // mutated to downrank the candidate in certain situations. 2593 func (ci *candidateInference) candTypeMatches(cand *candidate) bool { 2594 var ( 2595 expTypes = make([]types.Type, 0, 2) 2596 variadicType types.Type 2597 ) 2598 if ci.objType != nil { 2599 expTypes = append(expTypes, ci.objType) 2600 2601 if ci.variadic { 2602 variadicType = types.NewSlice(ci.objType) 2603 expTypes = append(expTypes, variadicType) 2604 } 2605 } 2606 2607 return cand.anyCandType(func(candType types.Type, addressable bool) bool { 2608 // Take into account any type modifiers on the expected type. 2609 candType = ci.applyTypeModifiers(candType, addressable) 2610 if candType == nil { 2611 return false 2612 } 2613 2614 if ci.convertibleTo != nil && types.ConvertibleTo(candType, ci.convertibleTo) { 2615 return true 2616 } 2617 2618 for _, expType := range expTypes { 2619 if isEmptyInterface(expType) { 2620 continue 2621 } 2622 2623 matches := ci.typeMatches(expType, candType) 2624 if !matches { 2625 // If candType doesn't otherwise match, consider if we can 2626 // convert candType directly to expType. 2627 if considerTypeConversion(candType, expType, cand.path) { 2628 cand.convertTo = expType 2629 // Give a major score penalty so we always prefer directly 2630 // assignable candidates, all else equal. 2631 cand.score *= 0.5 2632 return true 2633 } 2634 2635 continue 2636 } 2637 2638 if expType == variadicType { 2639 cand.mods = append(cand.mods, takeDotDotDot) 2640 } 2641 2642 // Lower candidate score for untyped conversions. This avoids 2643 // ranking untyped constants above candidates with an exact type 2644 // match. Don't lower score of builtin constants, e.g. "true". 2645 if isUntyped(candType) && !types.Identical(candType, expType) && cand.obj.Parent() != types.Universe { 2646 // Bigger penalty for deep completions into other packages to 2647 // avoid random constants from other packages popping up all 2648 // the time. 2649 if len(cand.path) > 0 && isPkgName(cand.path[0]) { 2650 cand.score *= 0.5 2651 } else { 2652 cand.score *= 0.75 2653 } 2654 } 2655 2656 return true 2657 } 2658 2659 // If we don't have a specific expected type, fall back to coarser 2660 // object kind checks. 2661 if ci.objType == nil || isEmptyInterface(ci.objType) { 2662 // If we were able to apply type modifiers to our candidate type, 2663 // count that as a match. For example: 2664 // 2665 // var foo chan int 2666 // <-fo<> 2667 // 2668 // We were able to apply the "<-" type modifier to "foo", so "foo" 2669 // matches. 2670 if len(ci.modifiers) > 0 { 2671 return true 2672 } 2673 2674 // If we didn't have an exact type match, check if our object kind 2675 // matches. 2676 if ci.kindMatches(candType) { 2677 if ci.objKind == kindFunc { 2678 cand.mods = append(cand.mods, invoke) 2679 } 2680 return true 2681 } 2682 } 2683 2684 return false 2685 }) 2686 } 2687 2688 // considerTypeConversion returns true if we should offer a completion 2689 // automatically converting "from" to "to". 2690 func considerTypeConversion(from, to types.Type, path []types.Object) bool { 2691 // Don't offer to convert deep completions from other packages. 2692 // Otherwise there are many random package level consts/vars that 2693 // pop up as candidates all the time. 2694 if len(path) > 0 && isPkgName(path[0]) { 2695 return false 2696 } 2697 2698 if _, ok := from.(*typeparams.TypeParam); ok { 2699 return false 2700 } 2701 2702 if !types.ConvertibleTo(from, to) { 2703 return false 2704 } 2705 2706 // Don't offer to convert ints to strings since that probably 2707 // doesn't do what the user wants. 2708 if isBasicKind(from, types.IsInteger) && isBasicKind(to, types.IsString) { 2709 return false 2710 } 2711 2712 return true 2713 } 2714 2715 // typeMatches reports whether an object of candType makes a good 2716 // completion candidate given the expected type expType. 2717 func (ci *candidateInference) typeMatches(expType, candType types.Type) bool { 2718 // Handle untyped values specially since AssignableTo gives false negatives 2719 // for them (see https://golang.org/issue/32146). 2720 if candBasic, ok := candType.Underlying().(*types.Basic); ok { 2721 if expBasic, ok := expType.Underlying().(*types.Basic); ok { 2722 // Note that the candidate and/or the expected can be untyped. 2723 // In "fo<> == 100" the expected type is untyped, and the 2724 // candidate could also be an untyped constant. 2725 2726 // Sort by is_untyped and then by is_int to simplify below logic. 2727 a, b := candBasic.Info(), expBasic.Info() 2728 if a&types.IsUntyped == 0 || (b&types.IsInteger > 0 && b&types.IsUntyped > 0) { 2729 a, b = b, a 2730 } 2731 2732 // If at least one is untyped... 2733 if a&types.IsUntyped > 0 { 2734 switch { 2735 // Untyped integers are compatible with floats. 2736 case a&types.IsInteger > 0 && b&types.IsFloat > 0: 2737 return true 2738 2739 // Check if their constant kind (bool|int|float|complex|string) matches. 2740 // This doesn't take into account the constant value, so there will be some 2741 // false positives due to integer sign and overflow. 2742 case a&types.IsConstType == b&types.IsConstType: 2743 return true 2744 } 2745 } 2746 } 2747 } 2748 2749 // AssignableTo covers the case where the types are equal, but also handles 2750 // cases like assigning a concrete type to an interface type. 2751 return types.AssignableTo(candType, expType) 2752 } 2753 2754 // kindMatches reports whether candType's kind matches our expected 2755 // kind (e.g. slice, map, etc.). 2756 func (ci *candidateInference) kindMatches(candType types.Type) bool { 2757 return ci.objKind > 0 && ci.objKind&candKind(candType) > 0 2758 } 2759 2760 // assigneesMatch reports whether an invocation of sig matches the 2761 // number and type of any assignees. 2762 func (ci *candidateInference) assigneesMatch(cand *candidate, sig *types.Signature) bool { 2763 if len(ci.assignees) == 0 { 2764 return false 2765 } 2766 2767 // Uniresult functions are always usable and are handled by the 2768 // normal, non-assignees type matching logic. 2769 if sig.Results().Len() == 1 { 2770 return false 2771 } 2772 2773 // Don't prefer completing into func(...interface{}) calls since all 2774 // functions would match. 2775 if ci.variadicAssignees && len(ci.assignees) == 1 && isEmptyInterface(deslice(ci.assignees[0])) { 2776 return false 2777 } 2778 2779 var numberOfResultsCouldMatch bool 2780 if ci.variadicAssignees { 2781 numberOfResultsCouldMatch = sig.Results().Len() >= len(ci.assignees)-1 2782 } else { 2783 numberOfResultsCouldMatch = sig.Results().Len() == len(ci.assignees) 2784 } 2785 2786 // If our signature doesn't return the right number of values, it's 2787 // not a match, so downrank it. For example: 2788 // 2789 // var foo func() (int, int) 2790 // a, b, c := <> // downrank "foo()" since it only returns two values 2791 if !numberOfResultsCouldMatch { 2792 cand.score /= 2 2793 return false 2794 } 2795 2796 // If at least one assignee has a valid type, and all valid 2797 // assignees match the corresponding sig result value, the signature 2798 // is a match. 2799 allMatch := false 2800 for i := 0; i < sig.Results().Len(); i++ { 2801 var assignee types.Type 2802 2803 // If we are completing into variadic parameters, deslice the 2804 // expected variadic type. 2805 if ci.variadicAssignees && i >= len(ci.assignees)-1 { 2806 assignee = ci.assignees[len(ci.assignees)-1] 2807 if elem := deslice(assignee); elem != nil { 2808 assignee = elem 2809 } 2810 } else { 2811 assignee = ci.assignees[i] 2812 } 2813 2814 if assignee == nil { 2815 continue 2816 } 2817 2818 allMatch = ci.typeMatches(assignee, sig.Results().At(i).Type()) 2819 if !allMatch { 2820 break 2821 } 2822 } 2823 return allMatch 2824 } 2825 2826 func (c *completer) matchingTypeName(cand *candidate) bool { 2827 if !c.wantTypeName() { 2828 return false 2829 } 2830 2831 typeMatches := func(candType types.Type) bool { 2832 // Take into account any type name modifier prefixes. 2833 candType = c.inference.applyTypeNameModifiers(candType) 2834 2835 if from := c.inference.typeName.assertableFrom; from != nil { 2836 // Don't suggest the starting type in type assertions. For example, 2837 // if "foo" is an io.Writer, don't suggest "foo.(io.Writer)". 2838 if types.Identical(from, candType) { 2839 return false 2840 } 2841 2842 if intf, ok := from.Underlying().(*types.Interface); ok { 2843 if !types.AssertableTo(intf, candType) { 2844 return false 2845 } 2846 } 2847 } 2848 2849 if c.inference.typeName.wantComparable && !types.Comparable(candType) { 2850 return false 2851 } 2852 2853 // Skip this type if it has already been used in another type 2854 // switch case. 2855 for _, seen := range c.inference.typeName.seenTypeSwitchCases { 2856 if types.Identical(candType, seen) { 2857 return false 2858 } 2859 } 2860 2861 // We can expect a type name and have an expected type in cases like: 2862 // 2863 // var foo []int 2864 // foo = []i<> 2865 // 2866 // Where our expected type is "[]int", and we expect a type name. 2867 if c.inference.objType != nil { 2868 return types.AssignableTo(candType, c.inference.objType) 2869 } 2870 2871 // Default to saying any type name is a match. 2872 return true 2873 } 2874 2875 t := cand.obj.Type() 2876 2877 if typeMatches(t) { 2878 return true 2879 } 2880 2881 if !source.IsInterface(t) && typeMatches(types.NewPointer(t)) { 2882 if c.inference.typeName.compLitType { 2883 // If we are completing a composite literal type as in 2884 // "foo<>{}", to make a pointer we must prepend "&". 2885 cand.mods = append(cand.mods, reference) 2886 } else { 2887 // If we are completing a normal type name such as "foo<>", to 2888 // make a pointer we must prepend "*". 2889 cand.mods = append(cand.mods, dereference) 2890 } 2891 return true 2892 } 2893 2894 return false 2895 } 2896 2897 var ( 2898 // "interface { Error() string }" (i.e. error) 2899 errorIntf = types.Universe.Lookup("error").Type().Underlying().(*types.Interface) 2900 2901 // "interface { String() string }" (i.e. fmt.Stringer) 2902 stringerIntf = types.NewInterfaceType([]*types.Func{ 2903 types.NewFunc(token.NoPos, nil, "String", types.NewSignature( 2904 nil, 2905 nil, 2906 types.NewTuple(types.NewParam(token.NoPos, nil, "", types.Typ[types.String])), 2907 false, 2908 )), 2909 }, nil).Complete() 2910 2911 byteType = types.Universe.Lookup("byte").Type() 2912 ) 2913 2914 // candKind returns the objKind of candType, if any. 2915 func candKind(candType types.Type) objKind { 2916 var kind objKind 2917 2918 switch t := candType.Underlying().(type) { 2919 case *types.Array: 2920 kind |= kindArray 2921 if t.Elem() == byteType { 2922 kind |= kindBytes 2923 } 2924 case *types.Slice: 2925 kind |= kindSlice 2926 if t.Elem() == byteType { 2927 kind |= kindBytes 2928 } 2929 case *types.Chan: 2930 kind |= kindChan 2931 case *types.Map: 2932 kind |= kindMap 2933 case *types.Pointer: 2934 kind |= kindPtr 2935 2936 // Some builtins handle array pointers as arrays, so just report a pointer 2937 // to an array as an array. 2938 if _, isArray := t.Elem().Underlying().(*types.Array); isArray { 2939 kind |= kindArray 2940 } 2941 case *types.Basic: 2942 switch info := t.Info(); { 2943 case info&types.IsString > 0: 2944 kind |= kindString 2945 case info&types.IsInteger > 0: 2946 kind |= kindInt 2947 case info&types.IsFloat > 0: 2948 kind |= kindFloat 2949 case info&types.IsComplex > 0: 2950 kind |= kindComplex 2951 case info&types.IsBoolean > 0: 2952 kind |= kindBool 2953 } 2954 case *types.Signature: 2955 return kindFunc 2956 } 2957 2958 if types.Implements(candType, errorIntf) { 2959 kind |= kindError 2960 } 2961 2962 if types.Implements(candType, stringerIntf) { 2963 kind |= kindStringer 2964 } 2965 2966 return kind 2967 }