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