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 5package source 6 7import ( 8 "context" 9 "fmt" 10 "go/ast" 11 "go/constant" 12 "go/scanner" 13 "go/token" 14 "go/types" 15 "math" 16 "sort" 17 "strconv" 18 "strings" 19 "sync" 20 "time" 21 "unicode" 22 23 "golang.org/x/tools/go/ast/astutil" 24 "golang.org/x/tools/internal/event" 25 "golang.org/x/tools/internal/imports" 26 "golang.org/x/tools/internal/lsp/fuzzy" 27 "golang.org/x/tools/internal/lsp/protocol" 28 "golang.org/x/tools/internal/lsp/snippet" 29 errors "golang.org/x/xerrors" 30) 31 32type CompletionItem struct { 33 // Label is the primary text the user sees for this completion item. 34 Label string 35 36 // Detail is supplemental information to present to the user. 37 // This often contains the type or return type of the completion item. 38 Detail string 39 40 // InsertText is the text to insert if this item is selected. 41 // Any of the prefix that has already been typed is not trimmed. 42 // The insert text does not contain snippets. 43 InsertText string 44 45 Kind protocol.CompletionItemKind 46 47 // An optional array of additional TextEdits that are applied when 48 // selecting this completion. 49 // 50 // Additional text edits should be used to change text unrelated to the current cursor position 51 // (for example adding an import statement at the top of the file if the completion item will 52 // insert an unqualified type). 53 AdditionalTextEdits []protocol.TextEdit 54 55 // Depth is how many levels were searched to find this completion. 56 // For example when completing "foo<>", "fooBar" is depth 0, and 57 // "fooBar.Baz" is depth 1. 58 Depth int 59 60 // Score is the internal relevance score. 61 // A higher score indicates that this completion item is more relevant. 62 Score float64 63 64 // snippet is the LSP snippet for the completion item. The LSP 65 // specification contains details about LSP snippets. For example, a 66 // snippet for a function with the following signature: 67 // 68 // func foo(a, b, c int) 69 // 70 // would be: 71 // 72 // foo(${1:a int}, ${2: b int}, ${3: c int}) 73 // 74 // If Placeholders is false in the CompletionOptions, the above 75 // snippet would instead be: 76 // 77 // foo(${1:}) 78 snippet *snippet.Builder 79 80 // Documentation is the documentation for the completion item. 81 Documentation string 82 83 // obj is the object from which this candidate was derived, if any. 84 // obj is for internal use only. 85 obj types.Object 86} 87 88// Snippet is a convenience returns the snippet if available, otherwise 89// the InsertText. 90// used for an item, depending on if the callee wants placeholders or not. 91func (i *CompletionItem) Snippet() string { 92 if i.snippet != nil { 93 return i.snippet.String() 94 } 95 return i.InsertText 96} 97 98// Scoring constants are used for weighting the relevance of different candidates. 99const ( 100 // stdScore is the base score for all completion items. 101 stdScore float64 = 1.0 102 103 // highScore indicates a very relevant completion item. 104 highScore float64 = 10.0 105 106 // lowScore indicates an irrelevant or not useful completion item. 107 lowScore float64 = 0.01 108) 109 110// matcher matches a candidate's label against the user input. The 111// returned score reflects the quality of the match. A score of zero 112// indicates no match, and a score of one means a perfect match. 113type matcher interface { 114 Score(candidateLabel string) (score float32) 115} 116 117// prefixMatcher implements case sensitive prefix matching. 118type prefixMatcher string 119 120func (pm prefixMatcher) Score(candidateLabel string) float32 { 121 if strings.HasPrefix(candidateLabel, string(pm)) { 122 return 1 123 } 124 return -1 125} 126 127// insensitivePrefixMatcher implements case insensitive prefix matching. 128type insensitivePrefixMatcher string 129 130func (ipm insensitivePrefixMatcher) Score(candidateLabel string) float32 { 131 if strings.HasPrefix(strings.ToLower(candidateLabel), string(ipm)) { 132 return 1 133 } 134 return -1 135} 136 137// completer contains the necessary information for a single completion request. 138type completer struct { 139 snapshot Snapshot 140 pkg Package 141 qf types.Qualifier 142 opts *completionOptions 143 144 // filename is the name of the file associated with this completion request. 145 filename string 146 147 // file is the AST of the file associated with this completion request. 148 file *ast.File 149 150 // pos is the position at which the request was triggered. 151 pos token.Pos 152 153 // path is the path of AST nodes enclosing the position. 154 path []ast.Node 155 156 // seen is the map that ensures we do not return duplicate results. 157 seen map[types.Object]bool 158 159 // items is the list of completion items returned. 160 items []CompletionItem 161 162 // surrounding describes the identifier surrounding the position. 163 surrounding *Selection 164 165 // inference contains information we've inferred about ideal 166 // candidates such as the candidate's type. 167 inference candidateInference 168 169 // enclosingFunc contains information about the function enclosing 170 // the position. 171 enclosingFunc *funcInfo 172 173 // enclosingCompositeLiteral contains information about the composite literal 174 // enclosing the position. 175 enclosingCompositeLiteral *compLitInfo 176 177 // deepState contains the current state of our deep completion search. 178 deepState deepCompletionState 179 180 // matcher matches the candidates against the surrounding prefix. 181 matcher matcher 182 183 // methodSetCache caches the types.NewMethodSet call, which is relatively 184 // expensive and can be called many times for the same type while searching 185 // for deep completions. 186 methodSetCache map[methodSetKey]*types.MethodSet 187 188 // mapper converts the positions in the file from which the completion originated. 189 mapper *protocol.ColumnMapper 190 191 // startTime is when we started processing this completion request. It does 192 // not include any time the request spent in the queue. 193 startTime time.Time 194} 195 196// funcInfo holds info about a function object. 197type funcInfo struct { 198 // sig is the function declaration enclosing the position. 199 sig *types.Signature 200 201 // body is the function's body. 202 body *ast.BlockStmt 203} 204 205type compLitInfo struct { 206 // cl is the *ast.CompositeLit enclosing the position. 207 cl *ast.CompositeLit 208 209 // clType is the type of cl. 210 clType types.Type 211 212 // kv is the *ast.KeyValueExpr enclosing the position, if any. 213 kv *ast.KeyValueExpr 214 215 // inKey is true if we are certain the position is in the key side 216 // of a key-value pair. 217 inKey bool 218 219 // maybeInFieldName is true if inKey is false and it is possible 220 // we are completing a struct field name. For example, 221 // "SomeStruct{<>}" will be inKey=false, but maybeInFieldName=true 222 // because we _could_ be completing a field name. 223 maybeInFieldName bool 224} 225 226type importInfo struct { 227 importPath string 228 name string 229 pkg Package 230} 231 232type methodSetKey struct { 233 typ types.Type 234 addressable bool 235} 236 237// A Selection represents the cursor position and surrounding identifier. 238type Selection struct { 239 content string 240 cursor token.Pos 241 mappedRange 242} 243 244func (p Selection) Prefix() string { 245 return p.content[:p.cursor-p.spanRange.Start] 246} 247 248func (p Selection) Suffix() string { 249 return p.content[p.cursor-p.spanRange.Start:] 250} 251 252func (c *completer) setSurrounding(ident *ast.Ident) { 253 if c.surrounding != nil { 254 return 255 } 256 if !(ident.Pos() <= c.pos && c.pos <= ident.End()) { 257 return 258 } 259 260 c.surrounding = &Selection{ 261 content: ident.Name, 262 cursor: c.pos, 263 // Overwrite the prefix only. 264 mappedRange: newMappedRange(c.snapshot.FileSet(), c.mapper, ident.Pos(), ident.End()), 265 } 266 267 switch c.opts.matcher { 268 case Fuzzy: 269 c.matcher = fuzzy.NewMatcher(c.surrounding.Prefix()) 270 case CaseSensitive: 271 c.matcher = prefixMatcher(c.surrounding.Prefix()) 272 default: 273 c.matcher = insensitivePrefixMatcher(strings.ToLower(c.surrounding.Prefix())) 274 } 275} 276 277func (c *completer) getSurrounding() *Selection { 278 if c.surrounding == nil { 279 c.surrounding = &Selection{ 280 content: "", 281 cursor: c.pos, 282 mappedRange: newMappedRange(c.snapshot.FileSet(), c.mapper, c.pos, c.pos), 283 } 284 } 285 return c.surrounding 286} 287 288// found adds a candidate completion. We will also search through the object's 289// members for more candidates. 290func (c *completer) found(ctx context.Context, cand candidate) { 291 obj := cand.obj 292 293 if obj.Pkg() != nil && obj.Pkg() != c.pkg.GetTypes() && !obj.Exported() { 294 // obj is not accessible because it lives in another package and is not 295 // exported. Don't treat it as a completion candidate. 296 return 297 } 298 299 if c.inDeepCompletion() { 300 // When searching deep, just make sure we don't have a cycle in our chain. 301 // We don't dedupe by object because we want to allow both "foo.Baz" and 302 // "bar.Baz" even though "Baz" is represented the same types.Object in both. 303 for _, seenObj := range c.deepState.chain { 304 if seenObj == obj { 305 return 306 } 307 } 308 } else { 309 // At the top level, dedupe by object. 310 if c.seen[obj] { 311 return 312 } 313 c.seen[obj] = true 314 } 315 316 // If we are running out of budgeted time we must limit our search for deep 317 // completion candidates. 318 if c.shouldPrune() { 319 return 320 } 321 322 // If we know we want a type name, don't offer non-type name 323 // candidates. However, do offer package names since they can 324 // contain type names, and do offer any candidate without a type 325 // since we aren't sure if it is a type name or not (i.e. unimported 326 // candidate). 327 if c.wantTypeName() && obj.Type() != nil && !isTypeName(obj) && !isPkgName(obj) { 328 return 329 } 330 331 if c.matchingCandidate(&cand) { 332 cand.score *= highScore 333 } else if isTypeName(obj) { 334 // If obj is a *types.TypeName that didn't otherwise match, check 335 // if a literal object of this type makes a good candidate. 336 337 // We only care about named types (i.e. don't want builtin types). 338 if _, isNamed := obj.Type().(*types.Named); isNamed { 339 c.literal(ctx, obj.Type(), cand.imp) 340 } 341 } 342 343 // Lower score of method calls so we prefer fields and vars over calls. 344 if cand.expandFuncCall { 345 if sig, ok := obj.Type().Underlying().(*types.Signature); ok && sig.Recv() != nil { 346 cand.score *= 0.9 347 } 348 } 349 350 // Prefer private objects over public ones. 351 if !obj.Exported() && obj.Parent() != types.Universe { 352 cand.score *= 1.1 353 } 354 355 // Favor shallow matches by lowering score according to depth. 356 cand.score -= cand.score * c.deepState.scorePenalty() 357 358 if cand.score < 0 { 359 cand.score = 0 360 } 361 362 cand.name = c.deepState.chainString(obj.Name()) 363 matchScore := c.matcher.Score(cand.name) 364 if matchScore > 0 { 365 cand.score *= float64(matchScore) 366 367 // Avoid calling c.item() for deep candidates that wouldn't be in the top 368 // MaxDeepCompletions anyway. 369 if !c.inDeepCompletion() || c.deepState.isHighScore(cand.score) { 370 if item, err := c.item(ctx, cand); err == nil { 371 c.items = append(c.items, item) 372 } 373 } 374 } 375 376 c.deepSearch(ctx, cand) 377} 378 379// candidate represents a completion candidate. 380type candidate struct { 381 // obj is the types.Object to complete to. 382 obj types.Object 383 384 // score is used to rank candidates. 385 score float64 386 387 // name is the deep object name path, e.g. "foo.bar" 388 name string 389 390 // expandFuncCall is true if obj should be invoked in the completion. 391 // For example, expandFuncCall=true yields "foo()", expandFuncCall=false yields "foo". 392 expandFuncCall bool 393 394 // takeAddress is true if the completion should take a pointer to obj. 395 // For example, takeAddress=true yields "&foo", takeAddress=false yields "foo". 396 takeAddress bool 397 398 // addressable is true if a pointer can be taken to the candidate. 399 addressable bool 400 401 // makePointer is true if the candidate type name T should be made into *T. 402 makePointer bool 403 404 // dereference is a count of how many times to dereference the candidate obj. 405 // For example, dereference=2 turns "foo" into "**foo" when formatting. 406 dereference int 407 408 // imp is the import that needs to be added to this package in order 409 // for this candidate to be valid. nil if no import needed. 410 imp *importInfo 411} 412 413// ErrIsDefinition is an error that informs the user they got no 414// completions because they tried to complete the name of a new object 415// being defined. 416type ErrIsDefinition struct { 417 objStr string 418} 419 420func (e ErrIsDefinition) Error() string { 421 msg := "this is a definition" 422 if e.objStr != "" { 423 msg += " of " + e.objStr 424 } 425 return msg 426} 427 428// Completion returns a list of possible candidates for completion, given a 429// a file and a position. 430// 431// The selection is computed based on the preceding identifier and can be used by 432// the client to score the quality of the completion. For instance, some clients 433// may tolerate imperfect matches as valid completion results, since users may make typos. 434func Completion(ctx context.Context, snapshot Snapshot, fh FileHandle, protoPos protocol.Position) ([]CompletionItem, *Selection, error) { 435 ctx, done := event.Start(ctx, "source.Completion") 436 defer done() 437 438 startTime := time.Now() 439 440 pkg, pgf, err := getParsedFile(ctx, snapshot, fh, NarrowestPackage) 441 if err != nil { 442 return nil, nil, fmt.Errorf("getting file for Completion: %w", err) 443 } 444 spn, err := pgf.Mapper.PointSpan(protoPos) 445 if err != nil { 446 return nil, nil, err 447 } 448 rng, err := spn.Range(pgf.Mapper.Converter) 449 if err != nil { 450 return nil, nil, err 451 } 452 // Completion is based on what precedes the cursor. 453 // Find the path to the position before pos. 454 path, _ := astutil.PathEnclosingInterval(pgf.File, rng.Start-1, rng.Start-1) 455 if path == nil { 456 return nil, nil, errors.Errorf("cannot find node enclosing position") 457 } 458 459 pos := rng.Start 460 461 // Check if completion at this position is valid. If not, return early. 462 switch n := path[0].(type) { 463 case *ast.BasicLit: 464 // Skip completion inside any kind of literal. 465 return nil, nil, nil 466 case *ast.CallExpr: 467 if n.Ellipsis.IsValid() && pos > n.Ellipsis && pos <= n.Ellipsis+token.Pos(len("...")) { 468 // Don't offer completions inside or directly after "...". For 469 // example, don't offer completions at "<>" in "foo(bar...<>"). 470 return nil, nil, nil 471 } 472 case *ast.Ident: 473 // reject defining identifiers 474 if obj, ok := pkg.GetTypesInfo().Defs[n]; ok { 475 if v, ok := obj.(*types.Var); ok && v.IsField() && v.Embedded() { 476 // An anonymous field is also a reference to a type. 477 } else { 478 objStr := "" 479 if obj != nil { 480 qual := types.RelativeTo(pkg.GetTypes()) 481 objStr = types.ObjectString(obj, qual) 482 } 483 return nil, nil, ErrIsDefinition{objStr: objStr} 484 } 485 } 486 } 487 488 opts := snapshot.View().Options() 489 c := &completer{ 490 pkg: pkg, 491 snapshot: snapshot, 492 qf: qualifier(pgf.File, pkg.GetTypes(), pkg.GetTypesInfo()), 493 filename: fh.URI().Filename(), 494 file: pgf.File, 495 path: path, 496 pos: pos, 497 seen: make(map[types.Object]bool), 498 enclosingFunc: enclosingFunction(path, pkg.GetTypesInfo()), 499 enclosingCompositeLiteral: enclosingCompositeLiteral(path, rng.Start, pkg.GetTypesInfo()), 500 opts: &completionOptions{ 501 matcher: opts.Matcher, 502 deepCompletion: opts.DeepCompletion, 503 unimported: opts.UnimportedCompletion, 504 documentation: opts.CompletionDocumentation, 505 fullDocumentation: opts.HoverKind == FullDocumentation, 506 placeholders: opts.Placeholders, 507 literal: opts.LiteralCompletions && opts.InsertTextFormat == protocol.SnippetTextFormat, 508 budget: opts.CompletionBudget, 509 }, 510 // default to a matcher that always matches 511 matcher: prefixMatcher(""), 512 methodSetCache: make(map[methodSetKey]*types.MethodSet), 513 mapper: pgf.Mapper, 514 startTime: startTime, 515 } 516 517 if c.opts.deepCompletion { 518 // Initialize max search depth to unlimited. 519 c.deepState.maxDepth = -1 520 } 521 522 var cancel context.CancelFunc 523 if c.opts.budget == 0 { 524 ctx, cancel = context.WithCancel(ctx) 525 } else { 526 ctx, cancel = context.WithDeadline(ctx, c.startTime.Add(c.opts.budget)) 527 } 528 defer cancel() 529 530 if surrounding := c.containingIdent(pgf.Src); surrounding != nil { 531 c.setSurrounding(surrounding) 532 } 533 534 c.inference = expectedCandidate(ctx, c) 535 536 defer c.sortItems() 537 538 // If we're inside a comment return comment completions 539 for _, comment := range pgf.File.Comments { 540 if comment.Pos() < rng.Start && rng.Start <= comment.End() { 541 c.populateCommentCompletions(ctx, comment) 542 return c.items, c.getSurrounding(), nil 543 } 544 } 545 546 // Struct literals are handled entirely separately. 547 if c.wantStructFieldCompletions() { 548 if err := c.structLiteralFieldName(ctx); err != nil { 549 return nil, nil, err 550 } 551 return c.items, c.getSurrounding(), nil 552 } 553 554 if lt := c.wantLabelCompletion(); lt != labelNone { 555 c.labels(ctx, lt) 556 return c.items, c.getSurrounding(), nil 557 } 558 559 if c.emptySwitchStmt() { 560 // Empty switch statements only admit "default" and "case" keywords. 561 c.addKeywordItems(map[string]bool{}, highScore, CASE, DEFAULT) 562 return c.items, c.getSurrounding(), nil 563 } 564 565 switch n := path[0].(type) { 566 case *ast.Ident: 567 // Is this the Sel part of a selector? 568 if sel, ok := path[1].(*ast.SelectorExpr); ok && sel.Sel == n { 569 if err := c.selector(ctx, sel); err != nil { 570 return nil, nil, err 571 } 572 } else if obj, ok := pkg.GetTypesInfo().Defs[n]; ok { 573 // reject defining identifiers 574 575 if v, ok := obj.(*types.Var); ok && v.IsField() && v.Embedded() { 576 // An anonymous field is also a reference to a type. 577 } else { 578 objStr := "" 579 if obj != nil { 580 qual := types.RelativeTo(pkg.GetTypes()) 581 objStr = types.ObjectString(obj, qual) 582 } 583 return nil, nil, ErrIsDefinition{objStr: objStr} 584 } 585 } else if err := c.lexical(ctx); err != nil { 586 return nil, nil, err 587 } 588 // The function name hasn't been typed yet, but the parens are there: 589 // recv.‸(arg) 590 case *ast.TypeAssertExpr: 591 // Create a fake selector expression. 592 if err := c.selector(ctx, &ast.SelectorExpr{X: n.X}); err != nil { 593 return nil, nil, err 594 } 595 596 case *ast.SelectorExpr: 597 if err := c.selector(ctx, n); err != nil { 598 return nil, nil, err 599 } 600 601 // At the file scope, only keywords are allowed. 602 case *ast.BadDecl, *ast.File: 603 c.addKeywordCompletions() 604 605 default: 606 // fallback to lexical completions 607 if err := c.lexical(ctx); err != nil { 608 return nil, nil, err 609 } 610 } 611 612 // Statement candidates offer an entire statement in certain 613 // contexts, as opposed to a single object. Add statement candidates 614 // last because they depend on other candidates having already been 615 // collected. 616 c.addStatementCandidates() 617 618 return c.items, c.getSurrounding(), nil 619} 620 621// containingIdent returns the *ast.Ident containing pos, if any. It 622// synthesizes an *ast.Ident to allow completion in the face of 623// certain syntax errors. 624func (c *completer) containingIdent(src []byte) *ast.Ident { 625 // In the normal case, our leaf AST node is the identifer being completed. 626 if ident, ok := c.path[0].(*ast.Ident); ok { 627 return ident 628 } 629 630 pos, tkn, lit := c.scanToken(src) 631 if !pos.IsValid() { 632 return nil 633 } 634 635 fakeIdent := &ast.Ident{Name: lit, NamePos: pos} 636 637 if _, isBadDecl := c.path[0].(*ast.BadDecl); isBadDecl { 638 // You don't get *ast.Idents at the file level, so look for bad 639 // decls and use the manually extracted token. 640 return fakeIdent 641 } else if c.emptySwitchStmt() { 642 // Only keywords are allowed in empty switch statements. 643 // *ast.Idents are not parsed, so we must use the manually 644 // extracted token. 645 return fakeIdent 646 } else if tkn.IsKeyword() { 647 // Otherwise, manually extract the prefix if our containing token 648 // is a keyword. This improves completion after an "accidental 649 // keyword", e.g. completing to "variance" in "someFunc(var<>)". 650 return fakeIdent 651 } 652 653 return nil 654} 655 656// scanToken scans pgh's contents for the token containing pos. 657func (c *completer) scanToken(contents []byte) (token.Pos, token.Token, string) { 658 tok := c.snapshot.FileSet().File(c.pos) 659 660 var s scanner.Scanner 661 s.Init(tok, contents, nil, 0) 662 for { 663 tknPos, tkn, lit := s.Scan() 664 if tkn == token.EOF || tknPos >= c.pos { 665 return token.NoPos, token.ILLEGAL, "" 666 } 667 668 if len(lit) > 0 && tknPos <= c.pos && c.pos <= tknPos+token.Pos(len(lit)) { 669 return tknPos, tkn, lit 670 } 671 } 672} 673 674func (c *completer) sortItems() { 675 sort.SliceStable(c.items, func(i, j int) bool { 676 // Sort by score first. 677 if c.items[i].Score != c.items[j].Score { 678 return c.items[i].Score > c.items[j].Score 679 } 680 681 // Then sort by label so order stays consistent. This also has the 682 // effect of prefering shorter candidates. 683 return c.items[i].Label < c.items[j].Label 684 }) 685} 686 687// emptySwitchStmt reports whether pos is in an empty switch or select 688// statement. 689func (c *completer) emptySwitchStmt() bool { 690 block, ok := c.path[0].(*ast.BlockStmt) 691 if !ok || len(block.List) > 0 || len(c.path) == 1 { 692 return false 693 } 694 695 switch c.path[1].(type) { 696 case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt: 697 return true 698 default: 699 return false 700 } 701} 702 703// populateCommentCompletions yields completions for exported 704// symbols immediately preceding comment. 705func (c *completer) populateCommentCompletions(ctx context.Context, comment *ast.CommentGroup) { 706 // Using the comment position find the line after 707 file := c.snapshot.FileSet().File(comment.End()) 708 if file == nil { 709 return 710 } 711 712 line := file.Line(comment.End()) 713 if file.LineCount() < line+1 { 714 return 715 } 716 717 nextLinePos := file.LineStart(line + 1) 718 if !nextLinePos.IsValid() { 719 return 720 } 721 722 // comment is valid, set surrounding as word boundaries around cursor 723 c.setSurroundingForComment(comment) 724 725 // Using the next line pos, grab and parse the exported symbol on that line 726 for _, n := range c.file.Decls { 727 if n.Pos() != nextLinePos { 728 continue 729 } 730 switch node := n.(type) { 731 // handle const, vars, and types 732 case *ast.GenDecl: 733 for _, spec := range node.Specs { 734 switch spec := spec.(type) { 735 case *ast.ValueSpec: 736 for _, name := range spec.Names { 737 if name.String() == "_" || !name.IsExported() { 738 continue 739 } 740 obj := c.pkg.GetTypesInfo().ObjectOf(name) 741 c.found(ctx, candidate{obj: obj, score: stdScore}) 742 } 743 case *ast.TypeSpec: 744 if spec.Name.String() == "_" || !spec.Name.IsExported() { 745 continue 746 } 747 obj := c.pkg.GetTypesInfo().ObjectOf(spec.Name) 748 c.found(ctx, candidate{obj: obj, score: stdScore}) 749 } 750 } 751 // handle functions 752 case *ast.FuncDecl: 753 if node.Name.String() == "_" || !node.Name.IsExported() { 754 continue 755 } 756 757 obj := c.pkg.GetTypesInfo().ObjectOf(node.Name) 758 if obj == nil || obj.Pkg() != nil && obj.Pkg() != c.pkg.GetTypes() { 759 continue 760 } 761 762 // We don't want expandFuncCall inside comments. We add this directly to the 763 // completions list because using c.found sets expandFuncCall to true by default 764 item, err := c.item(ctx, candidate{ 765 obj: obj, 766 name: obj.Name(), 767 expandFuncCall: false, 768 score: stdScore, 769 }) 770 if err != nil { 771 continue 772 } 773 c.items = append(c.items, item) 774 } 775 } 776} 777 778// sets word boundaries surrounding a cursor for a comment 779func (c *completer) setSurroundingForComment(comments *ast.CommentGroup) { 780 var cursorComment *ast.Comment 781 for _, comment := range comments.List { 782 if c.pos >= comment.Pos() && c.pos <= comment.End() { 783 cursorComment = comment 784 break 785 } 786 } 787 // if cursor isn't in the comment 788 if cursorComment == nil { 789 return 790 } 791 792 // index of cursor in comment text 793 cursorOffset := int(c.pos - cursorComment.Pos()) 794 start, end := cursorOffset, cursorOffset 795 for start > 0 && isValidIdentifierChar(cursorComment.Text[start-1]) { 796 start-- 797 } 798 for end < len(cursorComment.Text) && isValidIdentifierChar(cursorComment.Text[end]) { 799 end++ 800 } 801 802 c.surrounding = &Selection{ 803 content: cursorComment.Text[start:end], 804 cursor: c.pos, 805 mappedRange: newMappedRange(c.snapshot.FileSet(), c.mapper, 806 token.Pos(int(cursorComment.Slash)+start), token.Pos(int(cursorComment.Slash)+end)), 807 } 808} 809 810// isValidIdentifierChar returns true if a byte is a valid go identifier character 811// i.e unicode letter or digit or undescore 812func isValidIdentifierChar(char byte) bool { 813 charRune := rune(char) 814 return unicode.In(charRune, unicode.Letter, unicode.Digit) || char == '_' 815} 816 817func (c *completer) wantStructFieldCompletions() bool { 818 clInfo := c.enclosingCompositeLiteral 819 if clInfo == nil { 820 return false 821 } 822 823 return clInfo.isStruct() && (clInfo.inKey || clInfo.maybeInFieldName) 824} 825 826func (c *completer) wantTypeName() bool { 827 return c.inference.typeName.wantTypeName 828} 829 830// See https://golang.org/issue/36001. Unimported completions are expensive. 831const ( 832 maxUnimportedPackageNames = 5 833 unimportedMemberTarget = 100 834) 835 836// selector finds completions for the specified selector expression. 837func (c *completer) selector(ctx context.Context, sel *ast.SelectorExpr) error { 838 // Is sel a qualified identifier? 839 if id, ok := sel.X.(*ast.Ident); ok { 840 if pkgName, ok := c.pkg.GetTypesInfo().Uses[id].(*types.PkgName); ok { 841 c.packageMembers(ctx, pkgName.Imported(), stdScore, nil) 842 return nil 843 } 844 } 845 846 // Invariant: sel is a true selector. 847 tv, ok := c.pkg.GetTypesInfo().Types[sel.X] 848 if ok { 849 return c.methodsAndFields(ctx, tv.Type, tv.Addressable(), nil) 850 } 851 852 // Try unimported packages. 853 if id, ok := sel.X.(*ast.Ident); ok && c.opts.unimported { 854 if err := c.unimportedMembers(ctx, id); err != nil { 855 return err 856 } 857 } 858 return nil 859} 860 861func (c *completer) unimportedMembers(ctx context.Context, id *ast.Ident) error { 862 // Try loaded packages first. They're relevant, fast, and fully typed. 863 known, err := c.snapshot.CachedImportPaths(ctx) 864 if err != nil { 865 return err 866 } 867 868 var paths []string 869 for path, pkg := range known { 870 if pkg.GetTypes().Name() != id.Name { 871 continue 872 } 873 paths = append(paths, path) 874 } 875 876 var relevances map[string]int 877 if len(paths) != 0 { 878 if err := c.snapshot.View().RunProcessEnvFunc(ctx, func(opts *imports.Options) error { 879 var err error 880 relevances, err = imports.ScoreImportPaths(ctx, opts.Env, paths) 881 return err 882 }); err != nil { 883 return err 884 } 885 } 886 sort.Slice(paths, func(i, j int) bool { 887 return relevances[paths[i]] > relevances[paths[j]] 888 }) 889 890 for _, path := range paths { 891 pkg := known[path] 892 if pkg.GetTypes().Name() != id.Name { 893 continue 894 } 895 imp := &importInfo{ 896 importPath: path, 897 pkg: pkg, 898 } 899 if imports.ImportPathToAssumedName(path) != pkg.GetTypes().Name() { 900 imp.name = pkg.GetTypes().Name() 901 } 902 c.packageMembers(ctx, pkg.GetTypes(), unimportedScore(relevances[path]), imp) 903 if len(c.items) >= unimportedMemberTarget { 904 return nil 905 } 906 } 907 908 ctx, cancel := context.WithCancel(ctx) 909 defer cancel() 910 911 var mu sync.Mutex 912 add := func(pkgExport imports.PackageExport) { 913 mu.Lock() 914 defer mu.Unlock() 915 if _, ok := known[pkgExport.Fix.StmtInfo.ImportPath]; ok { 916 return // We got this one above. 917 } 918 919 // Continue with untyped proposals. 920 pkg := types.NewPackage(pkgExport.Fix.StmtInfo.ImportPath, pkgExport.Fix.IdentName) 921 for _, export := range pkgExport.Exports { 922 score := unimportedScore(pkgExport.Fix.Relevance) 923 c.found(ctx, candidate{ 924 obj: types.NewVar(0, pkg, export, nil), 925 score: score, 926 imp: &importInfo{ 927 importPath: pkgExport.Fix.StmtInfo.ImportPath, 928 name: pkgExport.Fix.StmtInfo.Name, 929 }, 930 }) 931 } 932 if len(c.items) >= unimportedMemberTarget { 933 cancel() 934 } 935 } 936 return c.snapshot.View().RunProcessEnvFunc(ctx, func(opts *imports.Options) error { 937 return imports.GetPackageExports(ctx, add, id.Name, c.filename, c.pkg.GetTypes().Name(), opts.Env) 938 }) 939} 940 941// unimportedScore returns a score for an unimported package that is generally 942// lower than other candidates. 943func unimportedScore(relevance int) float64 { 944 return (stdScore + .1*float64(relevance)) / 2 945} 946 947func (c *completer) packageMembers(ctx context.Context, pkg *types.Package, score float64, imp *importInfo) { 948 scope := pkg.Scope() 949 for _, name := range scope.Names() { 950 obj := scope.Lookup(name) 951 c.found(ctx, candidate{ 952 obj: obj, 953 score: score, 954 imp: imp, 955 addressable: isVar(obj), 956 }) 957 } 958} 959 960func (c *completer) methodsAndFields(ctx context.Context, typ types.Type, addressable bool, imp *importInfo) error { 961 mset := c.methodSetCache[methodSetKey{typ, addressable}] 962 if mset == nil { 963 if addressable && !types.IsInterface(typ) && !isPointer(typ) { 964 // Add methods of *T, which includes methods with receiver T. 965 mset = types.NewMethodSet(types.NewPointer(typ)) 966 } else { 967 // Add methods of T. 968 mset = types.NewMethodSet(typ) 969 } 970 c.methodSetCache[methodSetKey{typ, addressable}] = mset 971 } 972 973 for i := 0; i < mset.Len(); i++ { 974 c.found(ctx, candidate{ 975 obj: mset.At(i).Obj(), 976 score: stdScore, 977 imp: imp, 978 addressable: addressable || isPointer(typ), 979 }) 980 } 981 982 // Add fields of T. 983 eachField(typ, func(v *types.Var) { 984 c.found(ctx, candidate{ 985 obj: v, 986 score: stdScore - 0.01, 987 imp: imp, 988 addressable: addressable || isPointer(typ), 989 }) 990 }) 991 992 return nil 993} 994 995// lexical finds completions in the lexical environment. 996func (c *completer) lexical(ctx context.Context) error { 997 scopes := collectScopes(c.pkg.GetTypesInfo(), c.path, c.pos) 998 scopes = append(scopes, c.pkg.GetTypes().Scope(), types.Universe) 999 1000 var ( 1001 builtinIota = types.Universe.Lookup("iota") 1002 builtinNil = types.Universe.Lookup("nil") 1003 ) 1004 1005 // Track seen variables to avoid showing completions for shadowed variables. 1006 // This works since we look at scopes from innermost to outermost. 1007 seen := make(map[string]struct{}) 1008 1009 // Process scopes innermost first. 1010 for i, scope := range scopes { 1011 if scope == nil { 1012 continue 1013 } 1014 1015 Names: 1016 for _, name := range scope.Names() { 1017 declScope, obj := scope.LookupParent(name, c.pos) 1018 if declScope != scope { 1019 continue // Name was declared in some enclosing scope, or not at all. 1020 } 1021 1022 // If obj's type is invalid, find the AST node that defines the lexical block 1023 // containing the declaration of obj. Don't resolve types for packages. 1024 if !isPkgName(obj) && !typeIsValid(obj.Type()) { 1025 // Match the scope to its ast.Node. If the scope is the package scope, 1026 // use the *ast.File as the starting node. 1027 var node ast.Node 1028 if i < len(c.path) { 1029 node = c.path[i] 1030 } else if i == len(c.path) { // use the *ast.File for package scope 1031 node = c.path[i-1] 1032 } 1033 if node != nil { 1034 if resolved := resolveInvalid(c.snapshot.FileSet(), obj, node, c.pkg.GetTypesInfo()); resolved != nil { 1035 obj = resolved 1036 } 1037 } 1038 } 1039 1040 // Don't use LHS of value spec in RHS. 1041 if vs := enclosingValueSpec(c.path); vs != nil { 1042 for _, ident := range vs.Names { 1043 if obj.Pos() == ident.Pos() { 1044 continue Names 1045 } 1046 } 1047 } 1048 1049 // Don't suggest "iota" outside of const decls. 1050 if obj == builtinIota && !c.inConstDecl() { 1051 continue 1052 } 1053 1054 // Rank outer scopes lower than inner. 1055 score := stdScore * math.Pow(.99, float64(i)) 1056 1057 // Dowrank "nil" a bit so it is ranked below more interesting candidates. 1058 if obj == builtinNil { 1059 score /= 2 1060 } 1061 1062 // If we haven't already added a candidate for an object with this name. 1063 if _, ok := seen[obj.Name()]; !ok { 1064 seen[obj.Name()] = struct{}{} 1065 c.found(ctx, candidate{ 1066 obj: obj, 1067 score: score, 1068 addressable: isVar(obj), 1069 }) 1070 } 1071 } 1072 } 1073 1074 if c.inference.objType != nil { 1075 if named, _ := deref(c.inference.objType).(*types.Named); named != nil { 1076 // If we expected a named type, check the type's package for 1077 // completion items. This is useful when the current file hasn't 1078 // imported the type's package yet. 1079 1080 if named.Obj() != nil && named.Obj().Pkg() != nil { 1081 pkg := named.Obj().Pkg() 1082 1083 // Make sure the package name isn't already in use by another 1084 // object, and that this file doesn't import the package yet. 1085 if _, ok := seen[pkg.Name()]; !ok && pkg != c.pkg.GetTypes() && !alreadyImports(c.file, pkg.Path()) { 1086 seen[pkg.Name()] = struct{}{} 1087 obj := types.NewPkgName(0, nil, pkg.Name(), pkg) 1088 imp := &importInfo{ 1089 importPath: pkg.Path(), 1090 } 1091 if imports.ImportPathToAssumedName(pkg.Path()) != pkg.Name() { 1092 imp.name = pkg.Name() 1093 } 1094 c.found(ctx, candidate{ 1095 obj: obj, 1096 score: stdScore, 1097 imp: imp, 1098 }) 1099 } 1100 } 1101 } 1102 } 1103 1104 if c.opts.unimported { 1105 if err := c.unimportedPackages(ctx, seen); err != nil { 1106 return err 1107 } 1108 } 1109 1110 if t := c.inference.objType; t != nil { 1111 t = deref(t) 1112 1113 // If we have an expected type and it is _not_ a named type, see 1114 // if an object literal makes a good candidate. For example, if 1115 // our expected type is "[]int", this will add a candidate of 1116 // "[]int{}". 1117 if _, named := t.(*types.Named); !named { 1118 c.literal(ctx, t, nil) 1119 } 1120 } 1121 1122 // Add keyword completion items appropriate in the current context. 1123 c.addKeywordCompletions() 1124 1125 return nil 1126} 1127 1128func collectScopes(info *types.Info, path []ast.Node, pos token.Pos) []*types.Scope { 1129 // scopes[i], where i<len(path), is the possibly nil Scope of path[i]. 1130 var scopes []*types.Scope 1131 for _, n := range path { 1132 // Include *FuncType scope if pos is inside the function body. 1133 switch node := n.(type) { 1134 case *ast.FuncDecl: 1135 if node.Body != nil && nodeContains(node.Body, pos) { 1136 n = node.Type 1137 } 1138 case *ast.FuncLit: 1139 if node.Body != nil && nodeContains(node.Body, pos) { 1140 n = node.Type 1141 } 1142 } 1143 scopes = append(scopes, info.Scopes[n]) 1144 } 1145 return scopes 1146} 1147 1148func (c *completer) unimportedPackages(ctx context.Context, seen map[string]struct{}) error { 1149 var prefix string 1150 if c.surrounding != nil { 1151 prefix = c.surrounding.Prefix() 1152 } 1153 count := 0 1154 1155 known, err := c.snapshot.CachedImportPaths(ctx) 1156 if err != nil { 1157 return err 1158 } 1159 var paths []string 1160 for path, pkg := range known { 1161 if !strings.HasPrefix(pkg.GetTypes().Name(), prefix) { 1162 continue 1163 } 1164 paths = append(paths, path) 1165 } 1166 1167 var relevances map[string]int 1168 if len(paths) != 0 { 1169 if err := c.snapshot.View().RunProcessEnvFunc(ctx, func(opts *imports.Options) error { 1170 var err error 1171 relevances, err = imports.ScoreImportPaths(ctx, opts.Env, paths) 1172 return err 1173 }); err != nil { 1174 return err 1175 } 1176 } 1177 sort.Slice(paths, func(i, j int) bool { 1178 return relevances[paths[i]] > relevances[paths[j]] 1179 }) 1180 1181 for _, path := range paths { 1182 pkg := known[path] 1183 if _, ok := seen[pkg.GetTypes().Name()]; ok { 1184 continue 1185 } 1186 imp := &importInfo{ 1187 importPath: path, 1188 pkg: pkg, 1189 } 1190 if imports.ImportPathToAssumedName(path) != pkg.GetTypes().Name() { 1191 imp.name = pkg.GetTypes().Name() 1192 } 1193 if count >= maxUnimportedPackageNames { 1194 return nil 1195 } 1196 c.found(ctx, candidate{ 1197 obj: types.NewPkgName(0, nil, pkg.GetTypes().Name(), pkg.GetTypes()), 1198 score: unimportedScore(relevances[path]), 1199 imp: imp, 1200 }) 1201 count++ 1202 } 1203 1204 ctx, cancel := context.WithCancel(ctx) 1205 defer cancel() 1206 1207 var mu sync.Mutex 1208 add := func(pkg imports.ImportFix) { 1209 mu.Lock() 1210 defer mu.Unlock() 1211 if _, ok := seen[pkg.IdentName]; ok { 1212 return 1213 } 1214 if _, ok := relevances[pkg.StmtInfo.ImportPath]; ok { 1215 return 1216 } 1217 1218 if count >= maxUnimportedPackageNames { 1219 cancel() 1220 return 1221 } 1222 1223 // Do not add the unimported packages to seen, since we can have 1224 // multiple packages of the same name as completion suggestions, since 1225 // only one will be chosen. 1226 obj := types.NewPkgName(0, nil, pkg.IdentName, types.NewPackage(pkg.StmtInfo.ImportPath, pkg.IdentName)) 1227 c.found(ctx, candidate{ 1228 obj: obj, 1229 score: unimportedScore(pkg.Relevance), 1230 imp: &importInfo{ 1231 importPath: pkg.StmtInfo.ImportPath, 1232 name: pkg.StmtInfo.Name, 1233 }, 1234 }) 1235 count++ 1236 } 1237 return c.snapshot.View().RunProcessEnvFunc(ctx, func(opts *imports.Options) error { 1238 return imports.GetAllCandidates(ctx, add, prefix, c.filename, c.pkg.GetTypes().Name(), opts.Env) 1239 }) 1240} 1241 1242// alreadyImports reports whether f has an import with the specified path. 1243func alreadyImports(f *ast.File, path string) bool { 1244 for _, s := range f.Imports { 1245 if importPath(s) == path { 1246 return true 1247 } 1248 } 1249 return false 1250} 1251 1252// importPath returns the unquoted import path of s, 1253// or "" if the path is not properly quoted. 1254func importPath(s *ast.ImportSpec) string { 1255 t, err := strconv.Unquote(s.Path.Value) 1256 if err != nil { 1257 return "" 1258 } 1259 return t 1260} 1261 1262func nodeContains(n ast.Node, pos token.Pos) bool { 1263 return n != nil && n.Pos() <= pos && pos <= n.End() 1264} 1265 1266func (c *completer) inConstDecl() bool { 1267 for _, n := range c.path { 1268 if decl, ok := n.(*ast.GenDecl); ok && decl.Tok == token.CONST { 1269 return true 1270 } 1271 } 1272 return false 1273} 1274 1275// structLiteralFieldName finds completions for struct field names inside a struct literal. 1276func (c *completer) structLiteralFieldName(ctx context.Context) error { 1277 clInfo := c.enclosingCompositeLiteral 1278 1279 // Mark fields of the composite literal that have already been set, 1280 // except for the current field. 1281 addedFields := make(map[*types.Var]bool) 1282 for _, el := range clInfo.cl.Elts { 1283 if kvExpr, ok := el.(*ast.KeyValueExpr); ok { 1284 if clInfo.kv == kvExpr { 1285 continue 1286 } 1287 1288 if key, ok := kvExpr.Key.(*ast.Ident); ok { 1289 if used, ok := c.pkg.GetTypesInfo().Uses[key]; ok { 1290 if usedVar, ok := used.(*types.Var); ok { 1291 addedFields[usedVar] = true 1292 } 1293 } 1294 } 1295 } 1296 } 1297 1298 switch t := clInfo.clType.(type) { 1299 case *types.Struct: 1300 for i := 0; i < t.NumFields(); i++ { 1301 field := t.Field(i) 1302 if !addedFields[field] { 1303 c.found(ctx, candidate{ 1304 obj: field, 1305 score: highScore, 1306 }) 1307 } 1308 } 1309 1310 // Add lexical completions if we aren't certain we are in the key part of a 1311 // key-value pair. 1312 if clInfo.maybeInFieldName { 1313 return c.lexical(ctx) 1314 } 1315 default: 1316 return c.lexical(ctx) 1317 } 1318 1319 return nil 1320} 1321 1322func (cl *compLitInfo) isStruct() bool { 1323 _, ok := cl.clType.(*types.Struct) 1324 return ok 1325} 1326 1327// enclosingCompositeLiteral returns information about the composite literal enclosing the 1328// position. 1329func enclosingCompositeLiteral(path []ast.Node, pos token.Pos, info *types.Info) *compLitInfo { 1330 for _, n := range path { 1331 switch n := n.(type) { 1332 case *ast.CompositeLit: 1333 // The enclosing node will be a composite literal if the user has just 1334 // opened the curly brace (e.g. &x{<>) or the completion request is triggered 1335 // from an already completed composite literal expression (e.g. &x{foo: 1, <>}) 1336 // 1337 // The position is not part of the composite literal unless it falls within the 1338 // curly braces (e.g. "foo.Foo<>Struct{}"). 1339 if !(n.Lbrace < pos && pos <= n.Rbrace) { 1340 // Keep searching since we may yet be inside a composite literal. 1341 // For example "Foo{B: Ba<>{}}". 1342 break 1343 } 1344 1345 tv, ok := info.Types[n] 1346 if !ok { 1347 return nil 1348 } 1349 1350 clInfo := compLitInfo{ 1351 cl: n, 1352 clType: deref(tv.Type).Underlying(), 1353 } 1354 1355 var ( 1356 expr ast.Expr 1357 hasKeys bool 1358 ) 1359 for _, el := range n.Elts { 1360 // Remember the expression that the position falls in, if any. 1361 if el.Pos() <= pos && pos <= el.End() { 1362 expr = el 1363 } 1364 1365 if kv, ok := el.(*ast.KeyValueExpr); ok { 1366 hasKeys = true 1367 // If expr == el then we know the position falls in this expression, 1368 // so also record kv as the enclosing *ast.KeyValueExpr. 1369 if expr == el { 1370 clInfo.kv = kv 1371 break 1372 } 1373 } 1374 } 1375 1376 if clInfo.kv != nil { 1377 // If in a *ast.KeyValueExpr, we know we are in the key if the position 1378 // is to the left of the colon (e.g. "Foo{F<>: V}". 1379 clInfo.inKey = pos <= clInfo.kv.Colon 1380 } else if hasKeys { 1381 // If we aren't in a *ast.KeyValueExpr but the composite literal has 1382 // other *ast.KeyValueExprs, we must be on the key side of a new 1383 // *ast.KeyValueExpr (e.g. "Foo{F: V, <>}"). 1384 clInfo.inKey = true 1385 } else { 1386 switch clInfo.clType.(type) { 1387 case *types.Struct: 1388 if len(n.Elts) == 0 { 1389 // If the struct literal is empty, next could be a struct field 1390 // name or an expression (e.g. "Foo{<>}" could become "Foo{F:}" 1391 // or "Foo{someVar}"). 1392 clInfo.maybeInFieldName = true 1393 } else if len(n.Elts) == 1 { 1394 // If there is one expression and the position is in that expression 1395 // and the expression is an identifier, we may be writing a field 1396 // name or an expression (e.g. "Foo{F<>}"). 1397 _, clInfo.maybeInFieldName = expr.(*ast.Ident) 1398 } 1399 case *types.Map: 1400 // If we aren't in a *ast.KeyValueExpr we must be adding a new key 1401 // to the map. 1402 clInfo.inKey = true 1403 } 1404 } 1405 1406 return &clInfo 1407 default: 1408 if breaksExpectedTypeInference(n) { 1409 return nil 1410 } 1411 } 1412 } 1413 1414 return nil 1415} 1416 1417// enclosingFunction returns the signature and body of the function 1418// enclosing the given position. 1419func enclosingFunction(path []ast.Node, info *types.Info) *funcInfo { 1420 for _, node := range path { 1421 switch t := node.(type) { 1422 case *ast.FuncDecl: 1423 if obj, ok := info.Defs[t.Name]; ok { 1424 return &funcInfo{ 1425 sig: obj.Type().(*types.Signature), 1426 body: t.Body, 1427 } 1428 } 1429 case *ast.FuncLit: 1430 if typ, ok := info.Types[t]; ok { 1431 return &funcInfo{ 1432 sig: typ.Type.(*types.Signature), 1433 body: t.Body, 1434 } 1435 } 1436 } 1437 } 1438 return nil 1439} 1440 1441func (c *completer) expectedCompositeLiteralType() types.Type { 1442 clInfo := c.enclosingCompositeLiteral 1443 switch t := clInfo.clType.(type) { 1444 case *types.Slice: 1445 if clInfo.inKey { 1446 return types.Typ[types.Int] 1447 } 1448 return t.Elem() 1449 case *types.Array: 1450 if clInfo.inKey { 1451 return types.Typ[types.Int] 1452 } 1453 return t.Elem() 1454 case *types.Map: 1455 if clInfo.inKey { 1456 return t.Key() 1457 } 1458 return t.Elem() 1459 case *types.Struct: 1460 // If we are completing a key (i.e. field name), there is no expected type. 1461 if clInfo.inKey { 1462 return nil 1463 } 1464 1465 // If we are in a key-value pair, but not in the key, then we must be on the 1466 // value side. The expected type of the value will be determined from the key. 1467 if clInfo.kv != nil { 1468 if key, ok := clInfo.kv.Key.(*ast.Ident); ok { 1469 for i := 0; i < t.NumFields(); i++ { 1470 if field := t.Field(i); field.Name() == key.Name { 1471 return field.Type() 1472 } 1473 } 1474 } 1475 } else { 1476 // If we aren't in a key-value pair and aren't in the key, we must be using 1477 // implicit field names. 1478 1479 // The order of the literal fields must match the order in the struct definition. 1480 // Find the element that the position belongs to and suggest that field's type. 1481 if i := exprAtPos(c.pos, clInfo.cl.Elts); i < t.NumFields() { 1482 return t.Field(i).Type() 1483 } 1484 } 1485 } 1486 return nil 1487} 1488 1489// typeModifier represents an operator that changes the expected type. 1490type typeModifier struct { 1491 mod typeMod 1492 arrayLen int64 1493} 1494 1495type typeMod int 1496 1497const ( 1498 star typeMod = iota // pointer indirection for expressions, pointer indicator for types 1499 address // address operator ("&") 1500 chanRead // channel read operator ("<-") 1501 slice // make a slice type ("[]" in "[]int") 1502 array // make an array type ("[2]" in "[2]int") 1503) 1504 1505type objKind int 1506 1507const ( 1508 kindArray objKind = 1 << iota 1509 kindSlice 1510 kindChan 1511 kindMap 1512 kindStruct 1513 kindString 1514 kindFunc 1515) 1516 1517// candidateInference holds information we have inferred about a type that can be 1518// used at the current position. 1519type candidateInference struct { 1520 // objType is the desired type of an object used at the query position. 1521 objType types.Type 1522 1523 // objKind is a mask of expected kinds of types such as "map", "slice", etc. 1524 objKind objKind 1525 1526 // variadic is true if we are completing the initial variadic 1527 // parameter. For example: 1528 // append([]T{}, <>) // objType=T variadic=true 1529 // append([]T{}, T{}, <>) // objType=T variadic=false 1530 variadic bool 1531 1532 // modifiers are prefixes such as "*", "&" or "<-" that influence how 1533 // a candidate type relates to the expected type. 1534 modifiers []typeModifier 1535 1536 // convertibleTo is a type our candidate type must be convertible to. 1537 convertibleTo types.Type 1538 1539 // typeName holds information about the expected type name at 1540 // position, if any. 1541 typeName typeNameInference 1542 1543 // assignees are the types that would receive a function call's 1544 // results at the position. For example: 1545 // 1546 // foo := 123 1547 // foo, bar := <> 1548 // 1549 // at "<>", the assignees are [int, <invalid>]. 1550 assignees []types.Type 1551 1552 // variadicAssignees is true if we could be completing an inner 1553 // function call that fills out an outer function call's variadic 1554 // params. For example: 1555 // 1556 // func foo(int, ...string) {} 1557 // 1558 // foo(<>) // variadicAssignees=true 1559 // foo(bar<>) // variadicAssignees=true 1560 // foo(bar, baz<>) // variadicAssignees=false 1561 variadicAssignees bool 1562} 1563 1564// typeNameInference holds information about the expected type name at 1565// position. 1566type typeNameInference struct { 1567 // wantTypeName is true if we expect the name of a type. 1568 wantTypeName bool 1569 1570 // modifiers are prefixes such as "*", "&" or "<-" that influence how 1571 // a candidate type relates to the expected type. 1572 modifiers []typeModifier 1573 1574 // assertableFrom is a type that must be assertable to our candidate type. 1575 assertableFrom types.Type 1576 1577 // wantComparable is true if we want a comparable type. 1578 wantComparable bool 1579 1580 // seenTypeSwitchCases tracks types that have already been used by 1581 // the containing type switch. 1582 seenTypeSwitchCases []types.Type 1583} 1584 1585// expectedCandidate returns information about the expected candidate 1586// for an expression at the query position. 1587func expectedCandidate(ctx context.Context, c *completer) (inf candidateInference) { 1588 inf.typeName = expectTypeName(c) 1589 1590 if c.enclosingCompositeLiteral != nil { 1591 inf.objType = c.expectedCompositeLiteralType() 1592 } 1593 1594Nodes: 1595 for i, node := range c.path { 1596 switch node := node.(type) { 1597 case *ast.BinaryExpr: 1598 // Determine if query position comes from left or right of op. 1599 e := node.X 1600 if c.pos < node.OpPos { 1601 e = node.Y 1602 } 1603 if tv, ok := c.pkg.GetTypesInfo().Types[e]; ok { 1604 switch node.Op { 1605 case token.LAND, token.LOR: 1606 // Don't infer "bool" type for "&&" or "||". Often you want 1607 // to compose a boolean expression from non-boolean 1608 // candidates. 1609 default: 1610 inf.objType = tv.Type 1611 } 1612 break Nodes 1613 } 1614 case *ast.AssignStmt: 1615 // Only rank completions if you are on the right side of the token. 1616 if c.pos > node.TokPos { 1617 i := exprAtPos(c.pos, node.Rhs) 1618 if i >= len(node.Lhs) { 1619 i = len(node.Lhs) - 1 1620 } 1621 if tv, ok := c.pkg.GetTypesInfo().Types[node.Lhs[i]]; ok { 1622 inf.objType = tv.Type 1623 } 1624 1625 // If we have a single expression on the RHS, record the LHS 1626 // assignees so we can favor multi-return function calls with 1627 // matching result values. 1628 if len(node.Rhs) <= 1 { 1629 for _, lhs := range node.Lhs { 1630 inf.assignees = append(inf.assignees, c.pkg.GetTypesInfo().TypeOf(lhs)) 1631 } 1632 } else { 1633 // Otherwse, record our single assignee, even if its type is 1634 // not available. We use this info to downrank functions 1635 // with the wrong number of result values. 1636 inf.assignees = append(inf.assignees, c.pkg.GetTypesInfo().TypeOf(node.Lhs[i])) 1637 } 1638 } 1639 return inf 1640 case *ast.ValueSpec: 1641 if node.Type != nil && c.pos > node.Type.End() { 1642 inf.objType = c.pkg.GetTypesInfo().TypeOf(node.Type) 1643 } 1644 return inf 1645 case *ast.CallExpr: 1646 // Only consider CallExpr args if position falls between parens. 1647 if node.Lparen < c.pos && c.pos <= node.Rparen { 1648 // For type conversions like "int64(foo)" we can only infer our 1649 // desired type is convertible to int64. 1650 if typ := typeConversion(node, c.pkg.GetTypesInfo()); typ != nil { 1651 inf.convertibleTo = typ 1652 break Nodes 1653 } 1654 1655 if tv, ok := c.pkg.GetTypesInfo().Types[node.Fun]; ok { 1656 if sig, ok := tv.Type.(*types.Signature); ok { 1657 numParams := sig.Params().Len() 1658 if numParams == 0 { 1659 return inf 1660 } 1661 1662 exprIdx := exprAtPos(c.pos, node.Args) 1663 1664 // If we have one or zero arg expressions, we may be 1665 // completing to a function call that returns multiple 1666 // values, in turn getting passed in to the surrounding 1667 // call. Record the assignees so we can favor function 1668 // calls that return matching values. 1669 if len(node.Args) <= 1 && exprIdx == 0 { 1670 for i := 0; i < sig.Params().Len(); i++ { 1671 inf.assignees = append(inf.assignees, sig.Params().At(i).Type()) 1672 } 1673 1674 // Record that we may be completing into variadic parameters. 1675 inf.variadicAssignees = sig.Variadic() 1676 } 1677 1678 // Make sure not to run past the end of expected parameters. 1679 if exprIdx >= numParams { 1680 inf.objType = sig.Params().At(numParams - 1).Type() 1681 } else { 1682 inf.objType = sig.Params().At(exprIdx).Type() 1683 } 1684 1685 if sig.Variadic() && exprIdx >= (numParams-1) { 1686 // If we are completing a variadic param, deslice the variadic type. 1687 inf.objType = deslice(inf.objType) 1688 // Record whether we are completing the initial variadic param. 1689 inf.variadic = exprIdx == numParams-1 && len(node.Args) <= numParams 1690 } 1691 } 1692 } 1693 1694 if funIdent, ok := node.Fun.(*ast.Ident); ok { 1695 obj := c.pkg.GetTypesInfo().ObjectOf(funIdent) 1696 1697 if obj != nil && obj.Parent() == types.Universe { 1698 // Defer call to builtinArgType so we can provide it the 1699 // inferred type from its parent node. 1700 defer func() { 1701 inf = c.builtinArgType(obj, node, inf) 1702 inf.objKind = c.builtinArgKind(ctx, obj, node) 1703 }() 1704 1705 // The expected type of builtin arguments like append() is 1706 // the expected type of the builtin call itself. For 1707 // example: 1708 // 1709 // var foo []int = append(<>) 1710 // 1711 // To find the expected type at <> we "skip" the append() 1712 // node and get the expected type one level up, which is 1713 // []int. 1714 continue Nodes 1715 } 1716 } 1717 1718 return inf 1719 } 1720 case *ast.ReturnStmt: 1721 if c.enclosingFunc != nil { 1722 sig := c.enclosingFunc.sig 1723 // Find signature result that corresponds to our return statement. 1724 if resultIdx := exprAtPos(c.pos, node.Results); resultIdx < len(node.Results) { 1725 if resultIdx < sig.Results().Len() { 1726 inf.objType = sig.Results().At(resultIdx).Type() 1727 } 1728 } 1729 } 1730 return inf 1731 case *ast.CaseClause: 1732 if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, node).(*ast.SwitchStmt); ok { 1733 if tv, ok := c.pkg.GetTypesInfo().Types[swtch.Tag]; ok { 1734 inf.objType = tv.Type 1735 } 1736 } 1737 return inf 1738 case *ast.SliceExpr: 1739 // Make sure position falls within the brackets (e.g. "foo[a:<>]"). 1740 if node.Lbrack < c.pos && c.pos <= node.Rbrack { 1741 inf.objType = types.Typ[types.Int] 1742 } 1743 return inf 1744 case *ast.IndexExpr: 1745 // Make sure position falls within the brackets (e.g. "foo[<>]"). 1746 if node.Lbrack < c.pos && c.pos <= node.Rbrack { 1747 if tv, ok := c.pkg.GetTypesInfo().Types[node.X]; ok { 1748 switch t := tv.Type.Underlying().(type) { 1749 case *types.Map: 1750 inf.objType = t.Key() 1751 case *types.Slice, *types.Array: 1752 inf.objType = types.Typ[types.Int] 1753 } 1754 } 1755 } 1756 return inf 1757 case *ast.SendStmt: 1758 // Make sure we are on right side of arrow (e.g. "foo <- <>"). 1759 if c.pos > node.Arrow+1 { 1760 if tv, ok := c.pkg.GetTypesInfo().Types[node.Chan]; ok { 1761 if ch, ok := tv.Type.Underlying().(*types.Chan); ok { 1762 inf.objType = ch.Elem() 1763 } 1764 } 1765 } 1766 return inf 1767 case *ast.RangeStmt: 1768 if nodeContains(node.X, c.pos) { 1769 inf.objKind |= kindSlice | kindArray | kindMap | kindString 1770 if node.Value == nil { 1771 inf.objKind |= kindChan 1772 } 1773 } 1774 return inf 1775 case *ast.StarExpr: 1776 inf.modifiers = append(inf.modifiers, typeModifier{mod: star}) 1777 case *ast.UnaryExpr: 1778 switch node.Op { 1779 case token.AND: 1780 inf.modifiers = append(inf.modifiers, typeModifier{mod: address}) 1781 case token.ARROW: 1782 inf.modifiers = append(inf.modifiers, typeModifier{mod: chanRead}) 1783 } 1784 case *ast.DeferStmt, *ast.GoStmt: 1785 inf.objKind |= kindFunc 1786 return inf 1787 default: 1788 if breaksExpectedTypeInference(node) { 1789 return inf 1790 } 1791 } 1792 } 1793 1794 return inf 1795} 1796 1797// applyTypeModifiers applies the list of type modifiers to a type. 1798// It returns nil if the modifiers could not be applied. 1799func (ci candidateInference) applyTypeModifiers(typ types.Type, addressable bool) types.Type { 1800 for _, mod := range ci.modifiers { 1801 switch mod.mod { 1802 case star: 1803 // For every "*" indirection operator, remove a pointer layer 1804 // from candidate type. 1805 if ptr, ok := typ.Underlying().(*types.Pointer); ok { 1806 typ = ptr.Elem() 1807 } else { 1808 return nil 1809 } 1810 case address: 1811 // For every "&" address operator, add another pointer layer to 1812 // candidate type, if the candidate is addressable. 1813 if addressable { 1814 typ = types.NewPointer(typ) 1815 } else { 1816 return nil 1817 } 1818 case chanRead: 1819 // For every "<-" operator, remove a layer of channelness. 1820 if ch, ok := typ.(*types.Chan); ok { 1821 typ = ch.Elem() 1822 } else { 1823 return nil 1824 } 1825 } 1826 } 1827 1828 return typ 1829} 1830 1831// applyTypeNameModifiers applies the list of type modifiers to a type name. 1832func (ci candidateInference) applyTypeNameModifiers(typ types.Type) types.Type { 1833 for _, mod := range ci.typeName.modifiers { 1834 switch mod.mod { 1835 case star: 1836 // For every "*" indicator, add a pointer layer to type name. 1837 typ = types.NewPointer(typ) 1838 case array: 1839 typ = types.NewArray(typ, mod.arrayLen) 1840 case slice: 1841 typ = types.NewSlice(typ) 1842 } 1843 } 1844 return typ 1845} 1846 1847// matchesVariadic returns true if we are completing a variadic 1848// parameter and candType is a compatible slice type. 1849func (ci candidateInference) matchesVariadic(candType types.Type) bool { 1850 return ci.variadic && ci.objType != nil && types.AssignableTo(candType, types.NewSlice(ci.objType)) 1851} 1852 1853// findSwitchStmt returns an *ast.CaseClause's corresponding *ast.SwitchStmt or 1854// *ast.TypeSwitchStmt. path should start from the case clause's first ancestor. 1855func findSwitchStmt(path []ast.Node, pos token.Pos, c *ast.CaseClause) ast.Stmt { 1856 // Make sure position falls within a "case <>:" clause. 1857 if exprAtPos(pos, c.List) >= len(c.List) { 1858 return nil 1859 } 1860 // A case clause is always nested within a block statement in a switch statement. 1861 if len(path) < 2 { 1862 return nil 1863 } 1864 if _, ok := path[0].(*ast.BlockStmt); !ok { 1865 return nil 1866 } 1867 switch s := path[1].(type) { 1868 case *ast.SwitchStmt: 1869 return s 1870 case *ast.TypeSwitchStmt: 1871 return s 1872 default: 1873 return nil 1874 } 1875} 1876 1877// breaksExpectedTypeInference reports if an expression node's type is unrelated 1878// to its child expression node types. For example, "Foo{Bar: x.Baz(<>)}" should 1879// expect a function argument, not a composite literal value. 1880func breaksExpectedTypeInference(n ast.Node) bool { 1881 switch n.(type) { 1882 case *ast.FuncLit, *ast.CallExpr, *ast.IndexExpr, *ast.SliceExpr, *ast.CompositeLit: 1883 return true 1884 default: 1885 return false 1886 } 1887} 1888 1889// expectTypeName returns information about the expected type name at position. 1890func expectTypeName(c *completer) typeNameInference { 1891 var ( 1892 wantTypeName bool 1893 wantComparable bool 1894 modifiers []typeModifier 1895 assertableFrom types.Type 1896 seenTypeSwitchCases []types.Type 1897 ) 1898 1899Nodes: 1900 for i, p := range c.path { 1901 switch n := p.(type) { 1902 case *ast.FieldList: 1903 // Expect a type name if pos is in a FieldList. This applies to 1904 // FuncType params/results, FuncDecl receiver, StructType, and 1905 // InterfaceType. We don't need to worry about the field name 1906 // because completion bails out early if pos is in an *ast.Ident 1907 // that defines an object. 1908 wantTypeName = true 1909 break Nodes 1910 case *ast.CaseClause: 1911 // Expect type names in type switch case clauses. 1912 if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, n).(*ast.TypeSwitchStmt); ok { 1913 // The case clause types must be assertable from the type switch parameter. 1914 ast.Inspect(swtch.Assign, func(n ast.Node) bool { 1915 if ta, ok := n.(*ast.TypeAssertExpr); ok { 1916 assertableFrom = c.pkg.GetTypesInfo().TypeOf(ta.X) 1917 return false 1918 } 1919 return true 1920 }) 1921 wantTypeName = true 1922 1923 // Track the types that have already been used in this 1924 // switch's case statements so we don't recommend them. 1925 for _, e := range swtch.Body.List { 1926 for _, typeExpr := range e.(*ast.CaseClause).List { 1927 // Skip if type expression contains pos. We don't want to 1928 // count it as already used if the user is completing it. 1929 if typeExpr.Pos() < c.pos && c.pos <= typeExpr.End() { 1930 continue 1931 } 1932 1933 if t := c.pkg.GetTypesInfo().TypeOf(typeExpr); t != nil { 1934 seenTypeSwitchCases = append(seenTypeSwitchCases, t) 1935 } 1936 } 1937 } 1938 1939 break Nodes 1940 } 1941 return typeNameInference{} 1942 case *ast.TypeAssertExpr: 1943 // Expect type names in type assert expressions. 1944 if n.Lparen < c.pos && c.pos <= n.Rparen { 1945 // The type in parens must be assertable from the expression type. 1946 assertableFrom = c.pkg.GetTypesInfo().TypeOf(n.X) 1947 wantTypeName = true 1948 break Nodes 1949 } 1950 return typeNameInference{} 1951 case *ast.StarExpr: 1952 modifiers = append(modifiers, typeModifier{mod: star}) 1953 case *ast.CompositeLit: 1954 // We want a type name if position is in the "Type" part of a 1955 // composite literal (e.g. "Foo<>{}"). 1956 if n.Type != nil && n.Type.Pos() <= c.pos && c.pos <= n.Type.End() { 1957 wantTypeName = true 1958 } 1959 break Nodes 1960 case *ast.ArrayType: 1961 // If we are inside the "Elt" part of an array type, we want a type name. 1962 if n.Elt.Pos() <= c.pos && c.pos <= n.Elt.End() { 1963 wantTypeName = true 1964 if n.Len == nil { 1965 // No "Len" expression means a slice type. 1966 modifiers = append(modifiers, typeModifier{mod: slice}) 1967 } else { 1968 // Try to get the array type using the constant value of "Len". 1969 tv, ok := c.pkg.GetTypesInfo().Types[n.Len] 1970 if ok && tv.Value != nil && tv.Value.Kind() == constant.Int { 1971 if arrayLen, ok := constant.Int64Val(tv.Value); ok { 1972 modifiers = append(modifiers, typeModifier{mod: array, arrayLen: arrayLen}) 1973 } 1974 } 1975 } 1976 1977 // ArrayTypes can be nested, so keep going if our parent is an 1978 // ArrayType. 1979 if i < len(c.path)-1 { 1980 if _, ok := c.path[i+1].(*ast.ArrayType); ok { 1981 continue Nodes 1982 } 1983 } 1984 1985 break Nodes 1986 } 1987 case *ast.MapType: 1988 wantTypeName = true 1989 if n.Key != nil { 1990 wantComparable = nodeContains(n.Key, c.pos) 1991 } else { 1992 // If the key is empty, assume we are completing the key if 1993 // pos is directly after the "map[". 1994 wantComparable = c.pos == n.Pos()+token.Pos(len("map[")) 1995 } 1996 break Nodes 1997 case *ast.ValueSpec: 1998 wantTypeName = nodeContains(n.Type, c.pos) 1999 break Nodes 2000 case *ast.TypeSpec: 2001 wantTypeName = nodeContains(n.Type, c.pos) 2002 default: 2003 if breaksExpectedTypeInference(p) { 2004 return typeNameInference{} 2005 } 2006 } 2007 } 2008 2009 return typeNameInference{ 2010 wantTypeName: wantTypeName, 2011 wantComparable: wantComparable, 2012 modifiers: modifiers, 2013 assertableFrom: assertableFrom, 2014 seenTypeSwitchCases: seenTypeSwitchCases, 2015 } 2016} 2017 2018func (c *completer) fakeObj(T types.Type) *types.Var { 2019 return types.NewVar(token.NoPos, c.pkg.GetTypes(), "", T) 2020} 2021 2022// anyCandType reports whether f returns true for any candidate type 2023// derivable from c. For example, from "foo" we might derive "&foo", 2024// and "foo()". 2025func (c *candidate) anyCandType(f func(t types.Type, addressable bool) bool) bool { 2026 if c.obj == nil || c.obj.Type() == nil { 2027 return false 2028 } 2029 2030 objType := c.obj.Type() 2031 2032 if f(objType, c.addressable) { 2033 return true 2034 } 2035 2036 // If c is a func type with a single result, offer the result type. 2037 if sig, ok := objType.Underlying().(*types.Signature); ok { 2038 if sig.Results().Len() == 1 && f(sig.Results().At(0).Type(), false) { 2039 // Mark the candidate so we know to append "()" when formatting. 2040 c.expandFuncCall = true 2041 return true 2042 } 2043 } 2044 2045 var ( 2046 seenPtrTypes map[types.Type]bool 2047 ptrType = objType 2048 ptrDepth int 2049 ) 2050 2051 // Check if dereferencing c would match our type inference. We loop 2052 // since c could have arbitrary levels of pointerness. 2053 for { 2054 ptr, ok := ptrType.Underlying().(*types.Pointer) 2055 if !ok { 2056 break 2057 } 2058 2059 ptrDepth++ 2060 2061 // Avoid pointer type cycles. 2062 if seenPtrTypes[ptrType] { 2063 break 2064 } 2065 2066 if _, named := ptrType.(*types.Named); named { 2067 // Lazily allocate "seen" since it isn't used normally. 2068 if seenPtrTypes == nil { 2069 seenPtrTypes = make(map[types.Type]bool) 2070 } 2071 2072 // Track named pointer types we have seen to detect cycles. 2073 seenPtrTypes[ptrType] = true 2074 } 2075 2076 if f(ptr.Elem(), false) { 2077 // Mark the candidate so we know to prepend "*" when formatting. 2078 c.dereference = ptrDepth 2079 return true 2080 } 2081 2082 ptrType = ptr.Elem() 2083 } 2084 2085 // Check if c is addressable and a pointer to c matches our type inference. 2086 if c.addressable && f(types.NewPointer(objType), false) { 2087 // Mark the candidate so we know to prepend "&" when formatting. 2088 c.takeAddress = true 2089 return true 2090 } 2091 2092 return false 2093} 2094 2095// matchingCandidate reports whether cand matches our type inferences. 2096// It mutates cand's score in certain cases. 2097func (c *completer) matchingCandidate(cand *candidate) bool { 2098 if isTypeName(cand.obj) { 2099 return c.matchingTypeName(cand) 2100 } else if c.wantTypeName() { 2101 // If we want a type, a non-type object never matches. 2102 return false 2103 } 2104 2105 if c.inference.candTypeMatches(cand) { 2106 return true 2107 } 2108 2109 candType := cand.obj.Type() 2110 if candType == nil { 2111 return false 2112 } 2113 2114 if sig, ok := candType.Underlying().(*types.Signature); ok { 2115 if c.inference.assigneesMatch(cand, sig) { 2116 // Invoke the candidate if its results are multi-assignable. 2117 cand.expandFuncCall = true 2118 return true 2119 } 2120 } 2121 2122 // Default to invoking *types.Func candidates. This is so function 2123 // completions in an empty statement (or other cases with no expected type) 2124 // are invoked by default. 2125 cand.expandFuncCall = isFunc(cand.obj) 2126 2127 return false 2128} 2129 2130// candTypeMatches reports whether cand makes a good completion 2131// candidate given the candidate inference. cand's score may be 2132// mutated to downrank the candidate in certain situations. 2133func (ci *candidateInference) candTypeMatches(cand *candidate) bool { 2134 expTypes := make([]types.Type, 0, 2) 2135 if ci.objType != nil { 2136 expTypes = append(expTypes, ci.objType) 2137 if ci.variadic { 2138 expTypes = append(expTypes, types.NewSlice(ci.objType)) 2139 } 2140 } 2141 2142 return cand.anyCandType(func(candType types.Type, addressable bool) bool { 2143 // Take into account any type modifiers on the expected type. 2144 candType = ci.applyTypeModifiers(candType, addressable) 2145 if candType == nil { 2146 return false 2147 } 2148 2149 if ci.convertibleTo != nil && types.ConvertibleTo(candType, ci.convertibleTo) { 2150 return true 2151 } 2152 2153 if len(expTypes) == 0 { 2154 // If we have no expected type but were able to apply type 2155 // modifiers to our candidate type, count that as a match. This 2156 // handles cases like: 2157 // 2158 // var foo chan int 2159 // <-fo<> 2160 // 2161 // There is no exected type at "<>", but we were able to apply 2162 // the "<-" type modifier to "foo", so it matches. 2163 if len(ci.modifiers) > 0 { 2164 return true 2165 } 2166 2167 // If we have no expected type, fall back to checking the 2168 // expected "kind" of object, if available. 2169 if ci.kindMatches(candType) { 2170 if ci.objKind == kindFunc { 2171 cand.expandFuncCall = true 2172 } 2173 return true 2174 } 2175 } 2176 2177 for _, expType := range expTypes { 2178 matches, untyped := ci.typeMatches(expType, candType) 2179 if !matches { 2180 continue 2181 } 2182 2183 // Lower candidate score for untyped conversions. This avoids 2184 // ranking untyped constants above candidates with an exact type 2185 // match. Don't lower score of builtin constants, e.g. "true". 2186 if untyped && !types.Identical(candType, expType) && cand.obj.Parent() != types.Universe { 2187 cand.score /= 2 2188 } 2189 2190 return true 2191 } 2192 2193 return false 2194 }) 2195} 2196 2197// typeMatches reports whether an object of candType makes a good 2198// completion candidate given the expected type expType. It also 2199// returns a second bool which is true if both types are basic types 2200// of the same kind, and at least one is untyped. 2201func (ci *candidateInference) typeMatches(expType, candType types.Type) (bool, bool) { 2202 // Handle untyped values specially since AssignableTo gives false negatives 2203 // for them (see https://golang.org/issue/32146). 2204 if candBasic, ok := candType.Underlying().(*types.Basic); ok { 2205 if wantBasic, ok := expType.Underlying().(*types.Basic); ok { 2206 // Make sure at least one of them is untyped. 2207 if isUntyped(candType) || isUntyped(expType) { 2208 // Check that their constant kind (bool|int|float|complex|string) matches. 2209 // This doesn't take into account the constant value, so there will be some 2210 // false positives due to integer sign and overflow. 2211 if candBasic.Info()&types.IsConstType == wantBasic.Info()&types.IsConstType { 2212 return true, true 2213 } 2214 } 2215 } 2216 } 2217 2218 // AssignableTo covers the case where the types are equal, but also handles 2219 // cases like assigning a concrete type to an interface type. 2220 return types.AssignableTo(candType, expType), false 2221} 2222 2223// kindMatches reports whether candType's kind matches our expected 2224// kind (e.g. slice, map, etc.). 2225func (ci *candidateInference) kindMatches(candType types.Type) bool { 2226 return ci.objKind&candKind(candType) > 0 2227} 2228 2229// assigneesMatch reports whether an invocation of sig matches the 2230// number and type of any assignees. 2231func (ci *candidateInference) assigneesMatch(cand *candidate, sig *types.Signature) bool { 2232 if len(ci.assignees) == 0 { 2233 return false 2234 } 2235 2236 // Uniresult functions are always usable and are handled by the 2237 // normal, non-assignees type matching logic. 2238 if sig.Results().Len() == 1 { 2239 return false 2240 } 2241 2242 var numberOfResultsCouldMatch bool 2243 if ci.variadicAssignees { 2244 numberOfResultsCouldMatch = sig.Results().Len() >= len(ci.assignees)-1 2245 } else { 2246 numberOfResultsCouldMatch = sig.Results().Len() == len(ci.assignees) 2247 } 2248 2249 // If our signature doesn't return the right number of values, it's 2250 // not a match, so downrank it. For example: 2251 // 2252 // var foo func() (int, int) 2253 // a, b, c := <> // downrank "foo()" since it only returns two values 2254 if !numberOfResultsCouldMatch { 2255 cand.score /= 2 2256 return false 2257 } 2258 2259 // If at least one assignee has a valid type, and all valid 2260 // assignees match the corresponding sig result value, the signature 2261 // is a match. 2262 allMatch := false 2263 for i := 0; i < sig.Results().Len(); i++ { 2264 var assignee types.Type 2265 2266 // If we are completing into variadic parameters, deslice the 2267 // expected variadic type. 2268 if ci.variadicAssignees && i >= len(ci.assignees)-1 { 2269 assignee = ci.assignees[len(ci.assignees)-1] 2270 if elem := deslice(assignee); elem != nil { 2271 assignee = elem 2272 } 2273 } else { 2274 assignee = ci.assignees[i] 2275 } 2276 2277 if assignee == nil { 2278 continue 2279 } 2280 2281 allMatch, _ = ci.typeMatches(assignee, sig.Results().At(i).Type()) 2282 if !allMatch { 2283 break 2284 } 2285 } 2286 return allMatch 2287} 2288 2289func (c *completer) matchingTypeName(cand *candidate) bool { 2290 if !c.wantTypeName() { 2291 return false 2292 } 2293 2294 typeMatches := func(candType types.Type) bool { 2295 // Take into account any type name modifier prefixes. 2296 candType = c.inference.applyTypeNameModifiers(candType) 2297 2298 if from := c.inference.typeName.assertableFrom; from != nil { 2299 // Don't suggest the starting type in type assertions. For example, 2300 // if "foo" is an io.Writer, don't suggest "foo.(io.Writer)". 2301 if types.Identical(from, candType) { 2302 return false 2303 } 2304 2305 if intf, ok := from.Underlying().(*types.Interface); ok { 2306 if !types.AssertableTo(intf, candType) { 2307 return false 2308 } 2309 } 2310 } 2311 2312 if c.inference.typeName.wantComparable && !types.Comparable(candType) { 2313 return false 2314 } 2315 2316 // Skip this type if it has already been used in another type 2317 // switch case. 2318 for _, seen := range c.inference.typeName.seenTypeSwitchCases { 2319 if types.Identical(candType, seen) { 2320 return false 2321 } 2322 } 2323 2324 // We can expect a type name and have an expected type in cases like: 2325 // 2326 // var foo []int 2327 // foo = []i<> 2328 // 2329 // Where our expected type is "[]int", and we expect a type name. 2330 if c.inference.objType != nil { 2331 return types.AssignableTo(candType, c.inference.objType) 2332 } 2333 2334 // Default to saying any type name is a match. 2335 return true 2336 } 2337 2338 t := cand.obj.Type() 2339 2340 if typeMatches(t) { 2341 return true 2342 } 2343 2344 if !isInterface(t) && typeMatches(types.NewPointer(t)) { 2345 cand.makePointer = true 2346 return true 2347 } 2348 2349 return false 2350} 2351 2352// candKind returns the objKind of candType, if any. 2353func candKind(candType types.Type) objKind { 2354 switch t := candType.Underlying().(type) { 2355 case *types.Array: 2356 return kindArray 2357 case *types.Slice: 2358 return kindSlice 2359 case *types.Chan: 2360 return kindChan 2361 case *types.Map: 2362 return kindMap 2363 case *types.Pointer: 2364 // Some builtins handle array pointers as arrays, so just report a pointer 2365 // to an array as an array. 2366 if _, isArray := t.Elem().Underlying().(*types.Array); isArray { 2367 return kindArray 2368 } 2369 case *types.Basic: 2370 if t.Info()&types.IsString > 0 { 2371 return kindString 2372 } 2373 case *types.Signature: 2374 return kindFunc 2375 } 2376 2377 return 0 2378} 2379