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/token" 12 "go/types" 13 14 "golang.org/x/tools/go/ast/astutil" 15 "golang.org/x/tools/internal/lsp/fuzzy" 16 "golang.org/x/tools/internal/lsp/snippet" 17 "golang.org/x/tools/internal/lsp/telemetry/trace" 18 "golang.org/x/tools/internal/span" 19) 20 21type CompletionItem struct { 22 // Label is the primary text the user sees for this completion item. 23 Label string 24 25 // Detail is supplemental information to present to the user. 26 // This often contains the type or return type of the completion item. 27 Detail string 28 29 // InsertText is the text to insert if this item is selected. 30 // Any of the prefix that has already been typed is not trimmed. 31 // The insert text does not contain snippets. 32 InsertText string 33 34 Kind CompletionItemKind 35 36 // Depth is how many levels were searched to find this completion. 37 // For example when completing "foo<>", "fooBar" is depth 0, and 38 // "fooBar.Baz" is depth 1. 39 Depth int 40 41 // Score is the internal relevance score. 42 // A higher score indicates that this completion item is more relevant. 43 Score float64 44 45 // Snippet is the LSP snippet for the completion item, without placeholders. 46 // The LSP specification contains details about LSP snippets. 47 // For example, a snippet for a function with the following signature: 48 // 49 // func foo(a, b, c int) 50 // 51 // would be: 52 // 53 // foo(${1:}) 54 // 55 plainSnippet *snippet.Builder 56 57 // PlaceholderSnippet is the LSP snippet for the completion ite, containing 58 // placeholders. The LSP specification contains details about LSP snippets. 59 // For example, a placeholder snippet for a function with the following signature: 60 // 61 // func foo(a, b, c int) 62 // 63 // would be: 64 // 65 // foo(${1:a int}, ${2: b int}, ${3: c int}) 66 // 67 placeholderSnippet *snippet.Builder 68 69 // Documentation is the documentation for the completion item. 70 Documentation string 71} 72 73// Snippet is a convenience function that determines the snippet that should be 74// used for an item, depending on if the callee wants placeholders or not. 75func (i *CompletionItem) Snippet(usePlaceholders bool) string { 76 if usePlaceholders { 77 if i.placeholderSnippet != nil { 78 return i.placeholderSnippet.String() 79 } 80 } 81 if i.plainSnippet != nil { 82 return i.plainSnippet.String() 83 } 84 return i.InsertText 85} 86 87type CompletionItemKind int 88 89const ( 90 Unknown CompletionItemKind = iota 91 InterfaceCompletionItem 92 StructCompletionItem 93 TypeCompletionItem 94 ConstantCompletionItem 95 FieldCompletionItem 96 ParameterCompletionItem 97 VariableCompletionItem 98 FunctionCompletionItem 99 MethodCompletionItem 100 PackageCompletionItem 101) 102 103// Scoring constants are used for weighting the relevance of different candidates. 104const ( 105 // stdScore is the base score for all completion items. 106 stdScore float64 = 1.0 107 108 // highScore indicates a very relevant completion item. 109 highScore float64 = 10.0 110 111 // lowScore indicates an irrelevant or not useful completion item. 112 lowScore float64 = 0.01 113) 114 115// completer contains the necessary information for a single completion request. 116type completer struct { 117 // Package-specific fields. 118 types *types.Package 119 info *types.Info 120 qf types.Qualifier 121 opts CompletionOptions 122 123 // view is the View associated with this completion request. 124 view View 125 126 // ctx is the context associated with this completion request. 127 ctx context.Context 128 129 // pos is the position at which the request was triggered. 130 pos token.Pos 131 132 // path is the path of AST nodes enclosing the position. 133 path []ast.Node 134 135 // seen is the map that ensures we do not return duplicate results. 136 seen map[types.Object]bool 137 138 // items is the list of completion items returned. 139 items []CompletionItem 140 141 // surrounding describes the identifier surrounding the position. 142 surrounding *Selection 143 144 // expectedType conains information about the type we expect the completion 145 // candidate to be. It will be the zero value if no information is available. 146 expectedType typeInference 147 148 // enclosingFunction is the function declaration enclosing the position. 149 enclosingFunction *types.Signature 150 151 // enclosingCompositeLiteral contains information about the composite literal 152 // enclosing the position. 153 enclosingCompositeLiteral *compLitInfo 154 155 // deepState contains the current state of our deep completion search. 156 deepState deepCompletionState 157 158 // matcher does fuzzy matching of the candidates for the surrounding prefix. 159 matcher *fuzzy.Matcher 160} 161 162type compLitInfo struct { 163 // cl is the *ast.CompositeLit enclosing the position. 164 cl *ast.CompositeLit 165 166 // clType is the type of cl. 167 clType types.Type 168 169 // kv is the *ast.KeyValueExpr enclosing the position, if any. 170 kv *ast.KeyValueExpr 171 172 // inKey is true if we are certain the position is in the key side 173 // of a key-value pair. 174 inKey bool 175 176 // maybeInFieldName is true if inKey is false and it is possible 177 // we are completing a struct field name. For example, 178 // "SomeStruct{<>}" will be inKey=false, but maybeInFieldName=true 179 // because we _could_ be completing a field name. 180 maybeInFieldName bool 181} 182 183// A Selection represents the cursor position and surrounding identifier. 184type Selection struct { 185 Content string 186 Range span.Range 187 Cursor token.Pos 188} 189 190func (p Selection) Prefix() string { 191 return p.Content[:p.Cursor-p.Range.Start] 192} 193 194func (c *completer) setSurrounding(ident *ast.Ident) { 195 if c.surrounding != nil { 196 return 197 } 198 if !(ident.Pos() <= c.pos && c.pos <= ident.End()) { 199 return 200 } 201 c.surrounding = &Selection{ 202 Content: ident.Name, 203 Range: span.NewRange(c.view.Session().Cache().FileSet(), ident.Pos(), ident.End()), 204 Cursor: c.pos, 205 } 206 if c.surrounding.Prefix() != "" { 207 c.matcher = fuzzy.NewMatcher(c.surrounding.Prefix(), fuzzy.Symbol) 208 } 209} 210 211// found adds a candidate completion. We will also search through the object's 212// members for more candidates. 213func (c *completer) found(obj types.Object, score float64) error { 214 if obj.Pkg() != nil && obj.Pkg() != c.types && !obj.Exported() { 215 return fmt.Errorf("%s is inaccessible from %s", obj.Name(), c.types.Path()) 216 } 217 218 if c.inDeepCompletion() { 219 // When searching deep, just make sure we don't have a cycle in our chain. 220 // We don't dedupe by object because we want to allow both "foo.Baz" and 221 // "bar.Baz" even though "Baz" is represented the same types.Object in both. 222 for _, seenObj := range c.deepState.chain { 223 if seenObj == obj { 224 return nil 225 } 226 } 227 } else { 228 // At the top level, dedupe by object. 229 if c.seen[obj] { 230 return nil 231 } 232 c.seen[obj] = true 233 } 234 235 cand := candidate{ 236 obj: obj, 237 score: score, 238 } 239 240 if c.matchingType(&cand) { 241 cand.score *= highScore 242 } 243 244 // Favor shallow matches by lowering weight according to depth. 245 cand.score -= stdScore * float64(len(c.deepState.chain)) 246 item, err := c.item(cand) 247 if err != nil { 248 return err 249 } 250 c.items = append(c.items, item) 251 252 c.deepSearch(obj) 253 return nil 254} 255 256// candidate represents a completion candidate. 257type candidate struct { 258 // obj is the types.Object to complete to. 259 obj types.Object 260 261 // score is used to rank candidates. 262 score float64 263 264 // expandFuncCall is true if obj should be invoked in the completion. 265 // For example, expandFuncCall=true yields "foo()", expandFuncCall=false yields "foo". 266 expandFuncCall bool 267} 268 269type CompletionOptions struct { 270 DeepComplete bool 271 WantDocumentaton bool 272} 273 274// Completion returns a list of possible candidates for completion, given a 275// a file and a position. 276// 277// The selection is computed based on the preceding identifier and can be used by 278// the client to score the quality of the completion. For instance, some clients 279// may tolerate imperfect matches as valid completion results, since users may make typos. 280func Completion(ctx context.Context, view View, f GoFile, pos token.Pos, opts CompletionOptions) ([]CompletionItem, *Selection, error) { 281 ctx, ts := trace.StartSpan(ctx, "source.Completion") 282 defer ts.End() 283 file := f.GetAST(ctx) 284 if file == nil { 285 return nil, nil, fmt.Errorf("no AST for %s", f.URI()) 286 } 287 288 pkg := f.GetPackage(ctx) 289 if pkg == nil || pkg.IsIllTyped() { 290 return nil, nil, fmt.Errorf("package for %s is ill typed", f.URI()) 291 } 292 293 // Completion is based on what precedes the cursor. 294 // Find the path to the position before pos. 295 path, _ := astutil.PathEnclosingInterval(file, pos-1, pos-1) 296 if path == nil { 297 return nil, nil, fmt.Errorf("cannot find node enclosing position") 298 } 299 // Skip completion inside comments. 300 for _, g := range file.Comments { 301 if g.Pos() <= pos && pos <= g.End() { 302 return nil, nil, nil 303 } 304 } 305 // Skip completion inside any kind of literal. 306 if _, ok := path[0].(*ast.BasicLit); ok { 307 return nil, nil, nil 308 } 309 310 clInfo := enclosingCompositeLiteral(path, pos, pkg.GetTypesInfo()) 311 c := &completer{ 312 types: pkg.GetTypes(), 313 info: pkg.GetTypesInfo(), 314 qf: qualifier(file, pkg.GetTypes(), pkg.GetTypesInfo()), 315 view: view, 316 ctx: ctx, 317 path: path, 318 pos: pos, 319 seen: make(map[types.Object]bool), 320 enclosingFunction: enclosingFunction(path, pos, pkg.GetTypesInfo()), 321 enclosingCompositeLiteral: clInfo, 322 opts: opts, 323 } 324 325 c.deepState.enabled = opts.DeepComplete 326 327 // Set the filter surrounding. 328 if ident, ok := path[0].(*ast.Ident); ok { 329 c.setSurrounding(ident) 330 } 331 332 c.expectedType = expectedType(c) 333 334 // Struct literals are handled entirely separately. 335 if c.wantStructFieldCompletions() { 336 if err := c.structLiteralFieldName(); err != nil { 337 return nil, nil, err 338 } 339 return c.items, c.surrounding, nil 340 } 341 342 switch n := path[0].(type) { 343 case *ast.Ident: 344 // Is this the Sel part of a selector? 345 if sel, ok := path[1].(*ast.SelectorExpr); ok && sel.Sel == n { 346 if err := c.selector(sel); err != nil { 347 return nil, nil, err 348 } 349 return c.items, c.surrounding, nil 350 } 351 // reject defining identifiers 352 if obj, ok := pkg.GetTypesInfo().Defs[n]; ok { 353 if v, ok := obj.(*types.Var); ok && v.IsField() { 354 // An anonymous field is also a reference to a type. 355 } else { 356 of := "" 357 if obj != nil { 358 qual := types.RelativeTo(pkg.GetTypes()) 359 of += ", of " + types.ObjectString(obj, qual) 360 } 361 return nil, nil, fmt.Errorf("this is a definition%s", of) 362 } 363 } 364 if err := c.lexical(); err != nil { 365 return nil, nil, err 366 } 367 368 // The function name hasn't been typed yet, but the parens are there: 369 // recv.‸(arg) 370 case *ast.TypeAssertExpr: 371 // Create a fake selector expression. 372 if err := c.selector(&ast.SelectorExpr{X: n.X}); err != nil { 373 return nil, nil, err 374 } 375 376 case *ast.SelectorExpr: 377 // The go parser inserts a phantom "_" Sel node when the selector is 378 // not followed by an identifier or a "(". The "_" isn't actually in 379 // the text, so don't think it is our surrounding. 380 // TODO: Find a way to differentiate between phantom "_" and real "_", 381 // perhaps by checking if "_" is present in file contents. 382 if n.Sel.Name != "_" || c.pos != n.Sel.Pos() { 383 c.setSurrounding(n.Sel) 384 } 385 386 if err := c.selector(n); err != nil { 387 return nil, nil, err 388 } 389 390 default: 391 // fallback to lexical completions 392 if err := c.lexical(); err != nil { 393 return nil, nil, err 394 } 395 } 396 397 return c.items, c.surrounding, nil 398} 399 400func (c *completer) wantStructFieldCompletions() bool { 401 clInfo := c.enclosingCompositeLiteral 402 if clInfo == nil { 403 return false 404 } 405 406 return clInfo.isStruct() && (clInfo.inKey || clInfo.maybeInFieldName) 407} 408 409func (c *completer) wantTypeName() bool { 410 return c.expectedType.wantTypeName 411} 412 413// selector finds completions for the specified selector expression. 414func (c *completer) selector(sel *ast.SelectorExpr) error { 415 // Is sel a qualified identifier? 416 if id, ok := sel.X.(*ast.Ident); ok { 417 if pkgname, ok := c.info.Uses[id].(*types.PkgName); ok { 418 c.packageMembers(pkgname) 419 return nil 420 } 421 } 422 423 // Invariant: sel is a true selector. 424 tv, ok := c.info.Types[sel.X] 425 if !ok { 426 return fmt.Errorf("cannot resolve %s", sel.X) 427 } 428 429 return c.methodsAndFields(tv.Type, tv.Addressable()) 430} 431 432func (c *completer) packageMembers(pkg *types.PkgName) { 433 scope := pkg.Imported().Scope() 434 for _, name := range scope.Names() { 435 c.found(scope.Lookup(name), stdScore) 436 } 437} 438 439func (c *completer) methodsAndFields(typ types.Type, addressable bool) error { 440 var mset *types.MethodSet 441 442 if addressable && !types.IsInterface(typ) && !isPointer(typ) { 443 // Add methods of *T, which includes methods with receiver T. 444 mset = types.NewMethodSet(types.NewPointer(typ)) 445 } else { 446 // Add methods of T. 447 mset = types.NewMethodSet(typ) 448 } 449 450 for i := 0; i < mset.Len(); i++ { 451 c.found(mset.At(i).Obj(), stdScore) 452 } 453 454 // Add fields of T. 455 for _, f := range fieldSelections(typ) { 456 c.found(f, stdScore) 457 } 458 return nil 459} 460 461// lexical finds completions in the lexical environment. 462func (c *completer) lexical() error { 463 var scopes []*types.Scope // scopes[i], where i<len(path), is the possibly nil Scope of path[i]. 464 for _, n := range c.path { 465 switch node := n.(type) { 466 case *ast.FuncDecl: 467 n = node.Type 468 case *ast.FuncLit: 469 n = node.Type 470 } 471 scopes = append(scopes, c.info.Scopes[n]) 472 } 473 scopes = append(scopes, c.types.Scope(), types.Universe) 474 475 // Track seen variables to avoid showing completions for shadowed variables. 476 // This works since we look at scopes from innermost to outermost. 477 seen := make(map[string]struct{}) 478 479 // Process scopes innermost first. 480 for i, scope := range scopes { 481 if scope == nil { 482 continue 483 } 484 for _, name := range scope.Names() { 485 declScope, obj := scope.LookupParent(name, c.pos) 486 if declScope != scope { 487 continue // Name was declared in some enclosing scope, or not at all. 488 } 489 // If obj's type is invalid, find the AST node that defines the lexical block 490 // containing the declaration of obj. Don't resolve types for packages. 491 if _, ok := obj.(*types.PkgName); !ok && obj.Type() == types.Typ[types.Invalid] { 492 // Match the scope to its ast.Node. If the scope is the package scope, 493 // use the *ast.File as the starting node. 494 var node ast.Node 495 if i < len(c.path) { 496 node = c.path[i] 497 } else if i == len(c.path) { // use the *ast.File for package scope 498 node = c.path[i-1] 499 } 500 if node != nil { 501 if resolved := resolveInvalid(obj, node, c.info); resolved != nil { 502 obj = resolved 503 } 504 } 505 } 506 507 score := stdScore 508 // Rank builtins significantly lower than other results. 509 if scope == types.Universe { 510 score *= 0.1 511 } 512 // If we haven't already added a candidate for an object with this name. 513 if _, ok := seen[obj.Name()]; !ok { 514 seen[obj.Name()] = struct{}{} 515 c.found(obj, score) 516 } 517 } 518 } 519 return nil 520} 521 522// structLiteralFieldName finds completions for struct field names inside a struct literal. 523func (c *completer) structLiteralFieldName() error { 524 clInfo := c.enclosingCompositeLiteral 525 526 // Mark fields of the composite literal that have already been set, 527 // except for the current field. 528 addedFields := make(map[*types.Var]bool) 529 for _, el := range clInfo.cl.Elts { 530 if kvExpr, ok := el.(*ast.KeyValueExpr); ok { 531 if clInfo.kv == kvExpr { 532 continue 533 } 534 535 if key, ok := kvExpr.Key.(*ast.Ident); ok { 536 if used, ok := c.info.Uses[key]; ok { 537 if usedVar, ok := used.(*types.Var); ok { 538 addedFields[usedVar] = true 539 } 540 } 541 } 542 } 543 } 544 545 switch t := clInfo.clType.(type) { 546 case *types.Struct: 547 for i := 0; i < t.NumFields(); i++ { 548 field := t.Field(i) 549 if !addedFields[field] { 550 c.found(field, highScore) 551 } 552 } 553 554 // Add lexical completions if we aren't certain we are in the key part of a 555 // key-value pair. 556 if clInfo.maybeInFieldName { 557 return c.lexical() 558 } 559 default: 560 return c.lexical() 561 } 562 563 return nil 564} 565 566func (cl *compLitInfo) isStruct() bool { 567 _, ok := cl.clType.(*types.Struct) 568 return ok 569} 570 571// enclosingCompositeLiteral returns information about the composite literal enclosing the 572// position. 573func enclosingCompositeLiteral(path []ast.Node, pos token.Pos, info *types.Info) *compLitInfo { 574 for _, n := range path { 575 switch n := n.(type) { 576 case *ast.CompositeLit: 577 // The enclosing node will be a composite literal if the user has just 578 // opened the curly brace (e.g. &x{<>) or the completion request is triggered 579 // from an already completed composite literal expression (e.g. &x{foo: 1, <>}) 580 // 581 // The position is not part of the composite literal unless it falls within the 582 // curly braces (e.g. "foo.Foo<>Struct{}"). 583 if !(n.Lbrace <= pos && pos <= n.Rbrace) { 584 return nil 585 } 586 587 tv, ok := info.Types[n] 588 if !ok { 589 return nil 590 } 591 592 clInfo := compLitInfo{ 593 cl: n, 594 clType: tv.Type.Underlying(), 595 } 596 597 var ( 598 expr ast.Expr 599 hasKeys bool 600 ) 601 for _, el := range n.Elts { 602 // Remember the expression that the position falls in, if any. 603 if el.Pos() <= pos && pos <= el.End() { 604 expr = el 605 } 606 607 if kv, ok := el.(*ast.KeyValueExpr); ok { 608 hasKeys = true 609 // If expr == el then we know the position falls in this expression, 610 // so also record kv as the enclosing *ast.KeyValueExpr. 611 if expr == el { 612 clInfo.kv = kv 613 break 614 } 615 } 616 } 617 618 if clInfo.kv != nil { 619 // If in a *ast.KeyValueExpr, we know we are in the key if the position 620 // is to the left of the colon (e.g. "Foo{F<>: V}". 621 clInfo.inKey = pos <= clInfo.kv.Colon 622 } else if hasKeys { 623 // If we aren't in a *ast.KeyValueExpr but the composite literal has 624 // other *ast.KeyValueExprs, we must be on the key side of a new 625 // *ast.KeyValueExpr (e.g. "Foo{F: V, <>}"). 626 clInfo.inKey = true 627 } else { 628 switch clInfo.clType.(type) { 629 case *types.Struct: 630 if len(n.Elts) == 0 { 631 // If the struct literal is empty, next could be a struct field 632 // name or an expression (e.g. "Foo{<>}" could become "Foo{F:}" 633 // or "Foo{someVar}"). 634 clInfo.maybeInFieldName = true 635 } else if len(n.Elts) == 1 { 636 // If there is one expression and the position is in that expression 637 // and the expression is an identifier, we may be writing a field 638 // name or an expression (e.g. "Foo{F<>}"). 639 _, clInfo.maybeInFieldName = expr.(*ast.Ident) 640 } 641 case *types.Map: 642 // If we aren't in a *ast.KeyValueExpr we must be adding a new key 643 // to the map. 644 clInfo.inKey = true 645 } 646 } 647 648 return &clInfo 649 default: 650 if breaksExpectedTypeInference(n) { 651 return nil 652 } 653 } 654 } 655 656 return nil 657} 658 659// enclosingFunction returns the signature of the function enclosing the given position. 660func enclosingFunction(path []ast.Node, pos token.Pos, info *types.Info) *types.Signature { 661 for _, node := range path { 662 switch t := node.(type) { 663 case *ast.FuncDecl: 664 if obj, ok := info.Defs[t.Name]; ok { 665 return obj.Type().(*types.Signature) 666 } 667 case *ast.FuncLit: 668 if typ, ok := info.Types[t]; ok { 669 return typ.Type.(*types.Signature) 670 } 671 } 672 } 673 return nil 674} 675 676func (c *completer) expectedCompositeLiteralType() types.Type { 677 clInfo := c.enclosingCompositeLiteral 678 switch t := clInfo.clType.(type) { 679 case *types.Slice: 680 if clInfo.inKey { 681 return types.Typ[types.Int] 682 } 683 return t.Elem() 684 case *types.Array: 685 if clInfo.inKey { 686 return types.Typ[types.Int] 687 } 688 return t.Elem() 689 case *types.Map: 690 if clInfo.inKey { 691 return t.Key() 692 } 693 return t.Elem() 694 case *types.Struct: 695 // If we are completing a key (i.e. field name), there is no expected type. 696 if clInfo.inKey { 697 return nil 698 } 699 700 // If we are in a key-value pair, but not in the key, then we must be on the 701 // value side. The expected type of the value will be determined from the key. 702 if clInfo.kv != nil { 703 if key, ok := clInfo.kv.Key.(*ast.Ident); ok { 704 for i := 0; i < t.NumFields(); i++ { 705 if field := t.Field(i); field.Name() == key.Name { 706 return field.Type() 707 } 708 } 709 } 710 } else { 711 // If we aren't in a key-value pair and aren't in the key, we must be using 712 // implicit field names. 713 714 // The order of the literal fields must match the order in the struct definition. 715 // Find the element that the position belongs to and suggest that field's type. 716 if i := indexExprAtPos(c.pos, clInfo.cl.Elts); i < t.NumFields() { 717 return t.Field(i).Type() 718 } 719 } 720 } 721 return nil 722} 723 724// typeModifier represents an operator that changes the expected type. 725type typeModifier int 726 727const ( 728 star typeModifier = iota // dereference operator for expressions, pointer indicator for types 729 reference // reference ("&") operator 730 chanRead // channel read ("<-") operator 731) 732 733// typeInference holds information we have inferred about a type that can be 734// used at the current position. 735type typeInference struct { 736 // objType is the desired type of an object used at the query position. 737 objType types.Type 738 739 // wantTypeName is true if we expect the name of a type. 740 wantTypeName bool 741 742 // modifiers are prefixes such as "*", "&" or "<-" that influence how 743 // a candidate type relates to the expected type. 744 modifiers []typeModifier 745 746 // assertableFrom is a type that must be assertable to our candidate type. 747 assertableFrom types.Type 748 749 // convertibleTo is a type our candidate type must be convertible to. 750 convertibleTo types.Type 751} 752 753// expectedType returns information about the expected type for an expression at 754// the query position. 755func expectedType(c *completer) typeInference { 756 if ti := expectTypeName(c); ti.wantTypeName { 757 return ti 758 } 759 760 if c.enclosingCompositeLiteral != nil { 761 return typeInference{objType: c.expectedCompositeLiteralType()} 762 } 763 764 var ( 765 modifiers []typeModifier 766 typ types.Type 767 convertibleTo types.Type 768 ) 769 770Nodes: 771 for i, node := range c.path { 772 switch node := node.(type) { 773 case *ast.BinaryExpr: 774 // Determine if query position comes from left or right of op. 775 e := node.X 776 if c.pos < node.OpPos { 777 e = node.Y 778 } 779 if tv, ok := c.info.Types[e]; ok { 780 typ = tv.Type 781 break Nodes 782 } 783 case *ast.AssignStmt: 784 // Only rank completions if you are on the right side of the token. 785 if c.pos > node.TokPos { 786 i := indexExprAtPos(c.pos, node.Rhs) 787 if i >= len(node.Lhs) { 788 i = len(node.Lhs) - 1 789 } 790 if tv, ok := c.info.Types[node.Lhs[i]]; ok { 791 typ = tv.Type 792 break Nodes 793 } 794 } 795 return typeInference{} 796 case *ast.CallExpr: 797 // Only consider CallExpr args if position falls between parens. 798 if node.Lparen <= c.pos && c.pos <= node.Rparen { 799 // For type conversions like "int64(foo)" we can only infer our 800 // desired type is convertible to int64. 801 if typ := typeConversion(node, c.info); typ != nil { 802 convertibleTo = typ 803 break Nodes 804 } 805 806 if tv, ok := c.info.Types[node.Fun]; ok { 807 if sig, ok := tv.Type.(*types.Signature); ok { 808 if sig.Params().Len() == 0 { 809 return typeInference{} 810 } 811 i := indexExprAtPos(c.pos, node.Args) 812 // Make sure not to run past the end of expected parameters. 813 if i >= sig.Params().Len() { 814 i = sig.Params().Len() - 1 815 } 816 typ = sig.Params().At(i).Type() 817 break Nodes 818 } 819 } 820 } 821 return typeInference{} 822 case *ast.ReturnStmt: 823 if sig := c.enclosingFunction; sig != nil { 824 // Find signature result that corresponds to our return statement. 825 if resultIdx := indexExprAtPos(c.pos, node.Results); resultIdx < len(node.Results) { 826 if resultIdx < sig.Results().Len() { 827 typ = sig.Results().At(resultIdx).Type() 828 break Nodes 829 } 830 } 831 } 832 return typeInference{} 833 case *ast.CaseClause: 834 if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, node).(*ast.SwitchStmt); ok { 835 if tv, ok := c.info.Types[swtch.Tag]; ok { 836 typ = tv.Type 837 break Nodes 838 } 839 } 840 return typeInference{} 841 case *ast.SliceExpr: 842 // Make sure position falls within the brackets (e.g. "foo[a:<>]"). 843 if node.Lbrack < c.pos && c.pos <= node.Rbrack { 844 typ = types.Typ[types.Int] 845 break Nodes 846 } 847 return typeInference{} 848 case *ast.IndexExpr: 849 // Make sure position falls within the brackets (e.g. "foo[<>]"). 850 if node.Lbrack < c.pos && c.pos <= node.Rbrack { 851 if tv, ok := c.info.Types[node.X]; ok { 852 switch t := tv.Type.Underlying().(type) { 853 case *types.Map: 854 typ = t.Key() 855 case *types.Slice, *types.Array: 856 typ = types.Typ[types.Int] 857 default: 858 return typeInference{} 859 } 860 break Nodes 861 } 862 } 863 return typeInference{} 864 case *ast.SendStmt: 865 // Make sure we are on right side of arrow (e.g. "foo <- <>"). 866 if c.pos > node.Arrow+1 { 867 if tv, ok := c.info.Types[node.Chan]; ok { 868 if ch, ok := tv.Type.Underlying().(*types.Chan); ok { 869 typ = ch.Elem() 870 break Nodes 871 } 872 } 873 } 874 return typeInference{} 875 case *ast.StarExpr: 876 modifiers = append(modifiers, star) 877 case *ast.UnaryExpr: 878 switch node.Op { 879 case token.AND: 880 modifiers = append(modifiers, reference) 881 case token.ARROW: 882 modifiers = append(modifiers, chanRead) 883 } 884 default: 885 if breaksExpectedTypeInference(node) { 886 return typeInference{} 887 } 888 } 889 } 890 891 return typeInference{ 892 objType: typ, 893 modifiers: modifiers, 894 convertibleTo: convertibleTo, 895 } 896} 897 898// applyTypeModifiers applies the list of type modifiers to a type. 899func (ti typeInference) applyTypeModifiers(typ types.Type) types.Type { 900 for _, mod := range ti.modifiers { 901 switch mod { 902 case star: 903 // For every "*" deref operator, remove a pointer layer from candidate type. 904 typ = deref(typ) 905 case reference: 906 // For every "&" ref operator, add another pointer layer to candidate type. 907 typ = types.NewPointer(typ) 908 case chanRead: 909 // For every "<-" operator, remove a layer of channelness. 910 if ch, ok := typ.(*types.Chan); ok { 911 typ = ch.Elem() 912 } 913 } 914 } 915 return typ 916} 917 918// applyTypeNameModifiers applies the list of type modifiers to a type name. 919func (ti typeInference) applyTypeNameModifiers(typ types.Type) types.Type { 920 for _, mod := range ti.modifiers { 921 switch mod { 922 case star: 923 // For every "*" indicator, add a pointer layer to type name. 924 typ = types.NewPointer(typ) 925 } 926 } 927 return typ 928} 929 930// findSwitchStmt returns an *ast.CaseClause's corresponding *ast.SwitchStmt or 931// *ast.TypeSwitchStmt. path should start from the case clause's first ancestor. 932func findSwitchStmt(path []ast.Node, pos token.Pos, c *ast.CaseClause) ast.Stmt { 933 // Make sure position falls within a "case <>:" clause. 934 if exprAtPos(pos, c.List) == nil { 935 return nil 936 } 937 // A case clause is always nested within a block statement in a switch statement. 938 if len(path) < 2 { 939 return nil 940 } 941 if _, ok := path[0].(*ast.BlockStmt); !ok { 942 return nil 943 } 944 switch s := path[1].(type) { 945 case *ast.SwitchStmt: 946 return s 947 case *ast.TypeSwitchStmt: 948 return s 949 default: 950 return nil 951 } 952} 953 954// breaksExpectedTypeInference reports if an expression node's type is unrelated 955// to its child expression node types. For example, "Foo{Bar: x.Baz(<>)}" should 956// expect a function argument, not a composite literal value. 957func breaksExpectedTypeInference(n ast.Node) bool { 958 switch n.(type) { 959 case *ast.FuncLit, *ast.CallExpr, *ast.TypeAssertExpr, *ast.IndexExpr, *ast.SliceExpr, *ast.CompositeLit: 960 return true 961 default: 962 return false 963 } 964} 965 966// expectTypeName returns information about the expected type name at position. 967func expectTypeName(c *completer) typeInference { 968 var ( 969 wantTypeName bool 970 modifiers []typeModifier 971 assertableFrom types.Type 972 ) 973 974Nodes: 975 for i, p := range c.path { 976 switch n := p.(type) { 977 case *ast.FuncDecl: 978 // Expect type names in a function declaration receiver, params and results. 979 980 if r := n.Recv; r != nil && r.Pos() <= c.pos && c.pos <= r.End() { 981 wantTypeName = true 982 break Nodes 983 } 984 if t := n.Type; t != nil { 985 if p := t.Params; p != nil && p.Pos() <= c.pos && c.pos <= p.End() { 986 wantTypeName = true 987 break Nodes 988 } 989 if r := t.Results; r != nil && r.Pos() <= c.pos && c.pos <= r.End() { 990 wantTypeName = true 991 break Nodes 992 } 993 } 994 return typeInference{} 995 case *ast.CaseClause: 996 // Expect type names in type switch case clauses. 997 if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, n).(*ast.TypeSwitchStmt); ok { 998 // The case clause types must be assertable from the type switch parameter. 999 ast.Inspect(swtch.Assign, func(n ast.Node) bool { 1000 if ta, ok := n.(*ast.TypeAssertExpr); ok { 1001 assertableFrom = c.info.TypeOf(ta.X) 1002 return false 1003 } 1004 return true 1005 }) 1006 wantTypeName = true 1007 break Nodes 1008 } 1009 return typeInference{} 1010 case *ast.TypeAssertExpr: 1011 // Expect type names in type assert expressions. 1012 if n.Lparen < c.pos && c.pos <= n.Rparen { 1013 // The type in parens must be assertable from the expression type. 1014 assertableFrom = c.info.TypeOf(n.X) 1015 wantTypeName = true 1016 break Nodes 1017 } 1018 return typeInference{} 1019 case *ast.StarExpr: 1020 modifiers = append(modifiers, star) 1021 default: 1022 if breaksExpectedTypeInference(p) { 1023 return typeInference{} 1024 } 1025 } 1026 } 1027 1028 return typeInference{ 1029 wantTypeName: wantTypeName, 1030 modifiers: modifiers, 1031 assertableFrom: assertableFrom, 1032 } 1033} 1034 1035// matchingType reports whether an object is a good completion candidate 1036// in the context of the expected type. 1037func (c *completer) matchingType(cand *candidate) bool { 1038 if isTypeName(cand.obj) { 1039 return c.matchingTypeName(cand) 1040 } 1041 1042 objType := cand.obj.Type() 1043 1044 // Default to invoking *types.Func candidates. This is so function 1045 // completions in an empty statement (or other cases with no expected type) 1046 // are invoked by default. 1047 cand.expandFuncCall = isFunc(cand.obj) 1048 1049 typeMatches := func(candType types.Type) bool { 1050 // Take into account any type modifiers on the expected type. 1051 candType = c.expectedType.applyTypeModifiers(candType) 1052 1053 if c.expectedType.objType != nil { 1054 wantType := types.Default(c.expectedType.objType) 1055 1056 // Handle untyped values specially since AssignableTo gives false negatives 1057 // for them (see https://golang.org/issue/32146). 1058 if candBasic, ok := candType.(*types.Basic); ok && candBasic.Info()&types.IsUntyped > 0 { 1059 if wantBasic, ok := wantType.Underlying().(*types.Basic); ok { 1060 // Check that their constant kind (bool|int|float|complex|string) matches. 1061 // This doesn't take into account the constant value, so there will be some 1062 // false positives due to integer sign and overflow. 1063 return candBasic.Info()&types.IsConstType == wantBasic.Info()&types.IsConstType 1064 } 1065 return false 1066 } 1067 1068 // AssignableTo covers the case where the types are equal, but also handles 1069 // cases like assigning a concrete type to an interface type. 1070 return types.AssignableTo(candType, wantType) 1071 } 1072 1073 return false 1074 } 1075 1076 if typeMatches(objType) { 1077 // If obj's type matches, we don't want to expand to an invocation of obj. 1078 cand.expandFuncCall = false 1079 return true 1080 } 1081 1082 // Try using a function's return type as its type. 1083 if sig, ok := objType.Underlying().(*types.Signature); ok && sig.Results().Len() == 1 { 1084 if typeMatches(sig.Results().At(0).Type()) { 1085 // If obj's return value matches the expected type, we need to invoke obj 1086 // in the completion. 1087 cand.expandFuncCall = true 1088 return true 1089 } 1090 } 1091 1092 if c.expectedType.convertibleTo != nil { 1093 return types.ConvertibleTo(objType, c.expectedType.convertibleTo) 1094 } 1095 1096 return false 1097} 1098 1099func (c *completer) matchingTypeName(cand *candidate) bool { 1100 if !c.wantTypeName() { 1101 return false 1102 } 1103 1104 // Take into account any type name modifier prefixes. 1105 actual := c.expectedType.applyTypeNameModifiers(cand.obj.Type()) 1106 1107 if c.expectedType.assertableFrom != nil { 1108 // Don't suggest the starting type in type assertions. For example, 1109 // if "foo" is an io.Writer, don't suggest "foo.(io.Writer)". 1110 if types.Identical(c.expectedType.assertableFrom, actual) { 1111 return false 1112 } 1113 1114 if intf, ok := c.expectedType.assertableFrom.Underlying().(*types.Interface); ok { 1115 if !types.AssertableTo(intf, actual) { 1116 return false 1117 } 1118 } 1119 } 1120 1121 // Default to saying any type name is a match. 1122 return true 1123} 1124