2019-04-24 17:26:34 -06:00
|
|
|
// Copyright 2018 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2018-11-07 18:57:08 -07:00
|
|
|
package source
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2019-12-04 11:45:53 -07:00
|
|
|
"fmt"
|
2018-11-07 18:57:08 -07:00
|
|
|
"go/ast"
|
2019-09-13 13:15:53 -06:00
|
|
|
"go/constant"
|
2018-11-07 18:57:08 -07:00
|
|
|
"go/token"
|
|
|
|
"go/types"
|
2019-12-27 13:45:09 -07:00
|
|
|
"math"
|
2019-11-12 14:58:00 -07:00
|
|
|
"strconv"
|
internal/lsp: add fuzzy completion matching
Make use of the existing fuzzy matcher to perform server side fuzzy
completion matching. Previously the server did exact prefix matching
for completion candidates and left fancy filtering to the
client. Having the server do fuzzy matching has two main benefits:
- Deep completions now update as you type. The completion candidates
returned to the client are marked "incomplete", causing the client
to refresh the candidates after every keystroke. This lets the
server pick the most relevant set of deep completion candidates.
- All editors get fuzzy matching for free. VSCode has fuzzy matching
out of the box, but some editors either don't provide it, or it can
be difficult to set up.
I modified the fuzzy matcher to allow matches where the input doesn't
match the final segment of the candidate. For example, previously "ab"
would not match "abc.def" because the "b" in "ab" did not match the
final segment "def". I can see how this is useful when the text
matching happens in a vacuum and candidate's final segment is the most
specific part. But, in our case, we have various other methods to
order candidates, so we don't want to exclude them just because the
final segment doesn't match. For example, if we know our candidate
needs to be type "context.Context" and "foo.ctx" is of the right type,
we want to suggest "foo.ctx" as soon as the user starts inputting
"foo", even though "foo" doesn't match "ctx" at all.
Note that fuzzy matching is behind the "useDeepCompletions" config
flag for the time being.
Change-Id: Ic7674f0cf885af770c30daef472f2e3c5ac4db78
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190099
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-08-13 14:45:19 -06:00
|
|
|
"strings"
|
2019-12-27 13:46:49 -07:00
|
|
|
"sync"
|
internal/lsp: limit deep completion search scope
Deep completions can take a long time (500ms+) if there are many
large, deeply nested structs in scope. To make sure we return
completion results in a timely manner we now notice if we have spent
"too long" searching for deep completions and reduce the search scope.
In particular, our overall completion budget is 100ms. This value is
often cited as the longest latency that still feels instantaneous to
most people. As we spend 25%, 50%, and 75% of our budget we limit our
deep completion candidate search depth to 4, 3, and 2,
respectively. If we hit 90% of our budget, we disable deep completions
entirely.
In my testing, limiting the search scope to 4 normally makes even
enormous searches finish in a few milliseconds. Of course, you can
have arbitrarily many objects in scope with arbitrarily many fields,
so to cover our bases we continue to dial down the search depth as
needed.
I replaced the "enabled" field with a "maxDepth" field that disables
deep search when set to 0.
Change-Id: I9b5a07de70709895c065503ae6082d1ea615d1af
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190978
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
2019-08-18 13:55:34 -06:00
|
|
|
"time"
|
2018-11-07 18:57:08 -07:00
|
|
|
|
|
|
|
"golang.org/x/tools/go/ast/astutil"
|
2019-11-13 15:03:07 -07:00
|
|
|
"golang.org/x/tools/internal/imports"
|
2019-07-01 15:08:29 -06:00
|
|
|
"golang.org/x/tools/internal/lsp/fuzzy"
|
2019-08-16 15:05:40 -06:00
|
|
|
"golang.org/x/tools/internal/lsp/protocol"
|
2019-04-28 21:19:54 -06:00
|
|
|
"golang.org/x/tools/internal/lsp/snippet"
|
2019-08-13 13:07:39 -06:00
|
|
|
"golang.org/x/tools/internal/telemetry/trace"
|
2019-08-06 13:13:11 -06:00
|
|
|
errors "golang.org/x/xerrors"
|
2018-11-07 18:57:08 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
type CompletionItem struct {
|
2019-04-28 21:19:54 -06:00
|
|
|
// Label is the primary text the user sees for this completion item.
|
|
|
|
Label string
|
|
|
|
|
2019-04-29 17:47:54 -06:00
|
|
|
// Detail is supplemental information to present to the user.
|
|
|
|
// This often contains the type or return type of the completion item.
|
2019-04-28 21:19:54 -06:00
|
|
|
Detail string
|
|
|
|
|
2019-04-29 17:47:54 -06:00
|
|
|
// InsertText is the text to insert if this item is selected.
|
|
|
|
// Any of the prefix that has already been typed is not trimmed.
|
|
|
|
// The insert text does not contain snippets.
|
|
|
|
InsertText string
|
2019-04-28 21:19:54 -06:00
|
|
|
|
2019-09-24 22:46:57 -06:00
|
|
|
Kind protocol.CompletionItemKind
|
2019-04-28 21:19:54 -06:00
|
|
|
|
2019-08-14 15:25:47 -06:00
|
|
|
// An optional array of additional TextEdits that are applied when
|
|
|
|
// selecting this completion.
|
|
|
|
//
|
|
|
|
// Additional text edits should be used to change text unrelated to the current cursor position
|
|
|
|
// (for example adding an import statement at the top of the file if the completion item will
|
|
|
|
// insert an unqualified type).
|
2019-08-16 15:05:40 -06:00
|
|
|
AdditionalTextEdits []protocol.TextEdit
|
2019-08-14 15:25:47 -06:00
|
|
|
|
2019-06-27 11:50:01 -06:00
|
|
|
// Depth is how many levels were searched to find this completion.
|
|
|
|
// For example when completing "foo<>", "fooBar" is depth 0, and
|
|
|
|
// "fooBar.Baz" is depth 1.
|
|
|
|
Depth int
|
|
|
|
|
2019-04-29 17:47:54 -06:00
|
|
|
// Score is the internal relevance score.
|
|
|
|
// A higher score indicates that this completion item is more relevant.
|
2019-04-28 21:19:54 -06:00
|
|
|
Score float64
|
|
|
|
|
2019-09-04 11:23:14 -06:00
|
|
|
// snippet is the LSP snippet for the completion item. The LSP
|
|
|
|
// specification contains details about LSP snippets. For example, a
|
|
|
|
// snippet for a function with the following signature:
|
2019-04-29 17:47:54 -06:00
|
|
|
//
|
|
|
|
// func foo(a, b, c int)
|
|
|
|
//
|
|
|
|
// would be:
|
|
|
|
//
|
|
|
|
// foo(${1:a int}, ${2: b int}, ${3: c int})
|
|
|
|
//
|
2019-09-04 11:23:14 -06:00
|
|
|
// If Placeholders is false in the CompletionOptions, the above
|
|
|
|
// snippet would instead be:
|
|
|
|
//
|
|
|
|
// foo(${1:})
|
|
|
|
snippet *snippet.Builder
|
2019-07-02 15:31:31 -06:00
|
|
|
|
|
|
|
// Documentation is the documentation for the completion item.
|
|
|
|
Documentation string
|
2019-05-14 12:15:18 -06:00
|
|
|
}
|
|
|
|
|
2019-09-04 11:23:14 -06:00
|
|
|
// Snippet is a convenience returns the snippet if available, otherwise
|
|
|
|
// the InsertText.
|
2019-05-14 12:15:18 -06:00
|
|
|
// used for an item, depending on if the callee wants placeholders or not.
|
2019-09-04 11:23:14 -06:00
|
|
|
func (i *CompletionItem) Snippet() string {
|
|
|
|
if i.snippet != nil {
|
|
|
|
return i.snippet.String()
|
2019-05-14 12:15:18 -06:00
|
|
|
}
|
|
|
|
return i.InsertText
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
|
2019-04-24 17:26:34 -06:00
|
|
|
// Scoring constants are used for weighting the relevance of different candidates.
|
|
|
|
const (
|
|
|
|
// stdScore is the base score for all completion items.
|
|
|
|
stdScore float64 = 1.0
|
|
|
|
|
|
|
|
// highScore indicates a very relevant completion item.
|
|
|
|
highScore float64 = 10.0
|
|
|
|
|
|
|
|
// lowScore indicates an irrelevant or not useful completion item.
|
|
|
|
lowScore float64 = 0.01
|
|
|
|
)
|
|
|
|
|
2019-09-13 23:13:55 -06:00
|
|
|
// matcher matches a candidate's label against the user input. The
|
|
|
|
// returned score reflects the quality of the match. A score of zero
|
|
|
|
// indicates no match, and a score of one means a perfect match.
|
internal/lsp: add fuzzy completion matching
Make use of the existing fuzzy matcher to perform server side fuzzy
completion matching. Previously the server did exact prefix matching
for completion candidates and left fancy filtering to the
client. Having the server do fuzzy matching has two main benefits:
- Deep completions now update as you type. The completion candidates
returned to the client are marked "incomplete", causing the client
to refresh the candidates after every keystroke. This lets the
server pick the most relevant set of deep completion candidates.
- All editors get fuzzy matching for free. VSCode has fuzzy matching
out of the box, but some editors either don't provide it, or it can
be difficult to set up.
I modified the fuzzy matcher to allow matches where the input doesn't
match the final segment of the candidate. For example, previously "ab"
would not match "abc.def" because the "b" in "ab" did not match the
final segment "def". I can see how this is useful when the text
matching happens in a vacuum and candidate's final segment is the most
specific part. But, in our case, we have various other methods to
order candidates, so we don't want to exclude them just because the
final segment doesn't match. For example, if we know our candidate
needs to be type "context.Context" and "foo.ctx" is of the right type,
we want to suggest "foo.ctx" as soon as the user starts inputting
"foo", even though "foo" doesn't match "ctx" at all.
Note that fuzzy matching is behind the "useDeepCompletions" config
flag for the time being.
Change-Id: Ic7674f0cf885af770c30daef472f2e3c5ac4db78
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190099
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-08-13 14:45:19 -06:00
|
|
|
type matcher interface {
|
|
|
|
Score(candidateLabel string) (score float32)
|
|
|
|
}
|
|
|
|
|
2019-09-26 05:59:06 -06:00
|
|
|
// prefixMatcher implements case sensitive prefix matching.
|
internal/lsp: add fuzzy completion matching
Make use of the existing fuzzy matcher to perform server side fuzzy
completion matching. Previously the server did exact prefix matching
for completion candidates and left fancy filtering to the
client. Having the server do fuzzy matching has two main benefits:
- Deep completions now update as you type. The completion candidates
returned to the client are marked "incomplete", causing the client
to refresh the candidates after every keystroke. This lets the
server pick the most relevant set of deep completion candidates.
- All editors get fuzzy matching for free. VSCode has fuzzy matching
out of the box, but some editors either don't provide it, or it can
be difficult to set up.
I modified the fuzzy matcher to allow matches where the input doesn't
match the final segment of the candidate. For example, previously "ab"
would not match "abc.def" because the "b" in "ab" did not match the
final segment "def". I can see how this is useful when the text
matching happens in a vacuum and candidate's final segment is the most
specific part. But, in our case, we have various other methods to
order candidates, so we don't want to exclude them just because the
final segment doesn't match. For example, if we know our candidate
needs to be type "context.Context" and "foo.ctx" is of the right type,
we want to suggest "foo.ctx" as soon as the user starts inputting
"foo", even though "foo" doesn't match "ctx" at all.
Note that fuzzy matching is behind the "useDeepCompletions" config
flag for the time being.
Change-Id: Ic7674f0cf885af770c30daef472f2e3c5ac4db78
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190099
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-08-13 14:45:19 -06:00
|
|
|
type prefixMatcher string
|
|
|
|
|
|
|
|
func (pm prefixMatcher) Score(candidateLabel string) float32 {
|
2019-09-26 05:59:06 -06:00
|
|
|
if strings.HasPrefix(candidateLabel, string(pm)) {
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
|
|
|
|
// insensitivePrefixMatcher implements case insensitive prefix matching.
|
|
|
|
type insensitivePrefixMatcher string
|
|
|
|
|
|
|
|
func (ipm insensitivePrefixMatcher) Score(candidateLabel string) float32 {
|
|
|
|
if strings.HasPrefix(strings.ToLower(candidateLabel), string(ipm)) {
|
internal/lsp: add fuzzy completion matching
Make use of the existing fuzzy matcher to perform server side fuzzy
completion matching. Previously the server did exact prefix matching
for completion candidates and left fancy filtering to the
client. Having the server do fuzzy matching has two main benefits:
- Deep completions now update as you type. The completion candidates
returned to the client are marked "incomplete", causing the client
to refresh the candidates after every keystroke. This lets the
server pick the most relevant set of deep completion candidates.
- All editors get fuzzy matching for free. VSCode has fuzzy matching
out of the box, but some editors either don't provide it, or it can
be difficult to set up.
I modified the fuzzy matcher to allow matches where the input doesn't
match the final segment of the candidate. For example, previously "ab"
would not match "abc.def" because the "b" in "ab" did not match the
final segment "def". I can see how this is useful when the text
matching happens in a vacuum and candidate's final segment is the most
specific part. But, in our case, we have various other methods to
order candidates, so we don't want to exclude them just because the
final segment doesn't match. For example, if we know our candidate
needs to be type "context.Context" and "foo.ctx" is of the right type,
we want to suggest "foo.ctx" as soon as the user starts inputting
"foo", even though "foo" doesn't match "ctx" at all.
Note that fuzzy matching is behind the "useDeepCompletions" config
flag for the time being.
Change-Id: Ic7674f0cf885af770c30daef472f2e3c5ac4db78
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190099
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-08-13 14:45:19 -06:00
|
|
|
return 1
|
|
|
|
}
|
2019-08-27 17:41:48 -06:00
|
|
|
return -1
|
internal/lsp: add fuzzy completion matching
Make use of the existing fuzzy matcher to perform server side fuzzy
completion matching. Previously the server did exact prefix matching
for completion candidates and left fancy filtering to the
client. Having the server do fuzzy matching has two main benefits:
- Deep completions now update as you type. The completion candidates
returned to the client are marked "incomplete", causing the client
to refresh the candidates after every keystroke. This lets the
server pick the most relevant set of deep completion candidates.
- All editors get fuzzy matching for free. VSCode has fuzzy matching
out of the box, but some editors either don't provide it, or it can
be difficult to set up.
I modified the fuzzy matcher to allow matches where the input doesn't
match the final segment of the candidate. For example, previously "ab"
would not match "abc.def" because the "b" in "ab" did not match the
final segment "def". I can see how this is useful when the text
matching happens in a vacuum and candidate's final segment is the most
specific part. But, in our case, we have various other methods to
order candidates, so we don't want to exclude them just because the
final segment doesn't match. For example, if we know our candidate
needs to be type "context.Context" and "foo.ctx" is of the right type,
we want to suggest "foo.ctx" as soon as the user starts inputting
"foo", even though "foo" doesn't match "ctx" at all.
Note that fuzzy matching is behind the "useDeepCompletions" config
flag for the time being.
Change-Id: Ic7674f0cf885af770c30daef472f2e3c5ac4db78
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190099
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-08-13 14:45:19 -06:00
|
|
|
}
|
|
|
|
|
2019-04-24 17:26:34 -06:00
|
|
|
// completer contains the necessary information for a single completion request.
|
|
|
|
type completer struct {
|
2019-09-27 11:17:59 -06:00
|
|
|
snapshot Snapshot
|
|
|
|
pkg Package
|
2019-09-09 18:22:42 -06:00
|
|
|
|
|
|
|
qf types.Qualifier
|
|
|
|
opts CompletionOptions
|
2019-04-29 19:08:16 -06:00
|
|
|
|
|
|
|
// ctx is the context associated with this completion request.
|
|
|
|
ctx context.Context
|
2019-04-24 17:26:34 -06:00
|
|
|
|
2019-08-14 15:25:47 -06:00
|
|
|
// filename is the name of the file associated with this completion request.
|
|
|
|
filename string
|
|
|
|
|
|
|
|
// file is the AST of the file associated with this completion request.
|
|
|
|
file *ast.File
|
|
|
|
|
2019-04-24 17:26:34 -06:00
|
|
|
// pos is the position at which the request was triggered.
|
|
|
|
pos token.Pos
|
2018-12-05 15:00:36 -07:00
|
|
|
|
2019-04-24 17:26:34 -06:00
|
|
|
// path is the path of AST nodes enclosing the position.
|
|
|
|
path []ast.Node
|
|
|
|
|
|
|
|
// seen is the map that ensures we do not return duplicate results.
|
|
|
|
seen map[types.Object]bool
|
|
|
|
|
|
|
|
// items is the list of completion items returned.
|
|
|
|
items []CompletionItem
|
|
|
|
|
2019-05-17 11:45:59 -06:00
|
|
|
// surrounding describes the identifier surrounding the position.
|
|
|
|
surrounding *Selection
|
2019-04-24 17:26:34 -06:00
|
|
|
|
2019-09-11 00:14:36 -06:00
|
|
|
// expectedType contains information about the type we expect the completion
|
2019-06-17 12:11:13 -06:00
|
|
|
// candidate to be. It will be the zero value if no information is available.
|
|
|
|
expectedType typeInference
|
2019-04-24 17:26:34 -06:00
|
|
|
|
2019-09-18 13:26:39 -06:00
|
|
|
// enclosingFunc contains information about the function enclosing
|
|
|
|
// the position.
|
|
|
|
enclosingFunc *funcInfo
|
2019-04-24 17:26:34 -06:00
|
|
|
|
2019-05-13 15:37:08 -06:00
|
|
|
// enclosingCompositeLiteral contains information about the composite literal
|
|
|
|
// enclosing the position.
|
|
|
|
enclosingCompositeLiteral *compLitInfo
|
2019-06-27 11:50:01 -06:00
|
|
|
|
|
|
|
// deepState contains the current state of our deep completion search.
|
|
|
|
deepState deepCompletionState
|
2019-07-01 15:08:29 -06:00
|
|
|
|
internal/lsp: add fuzzy completion matching
Make use of the existing fuzzy matcher to perform server side fuzzy
completion matching. Previously the server did exact prefix matching
for completion candidates and left fancy filtering to the
client. Having the server do fuzzy matching has two main benefits:
- Deep completions now update as you type. The completion candidates
returned to the client are marked "incomplete", causing the client
to refresh the candidates after every keystroke. This lets the
server pick the most relevant set of deep completion candidates.
- All editors get fuzzy matching for free. VSCode has fuzzy matching
out of the box, but some editors either don't provide it, or it can
be difficult to set up.
I modified the fuzzy matcher to allow matches where the input doesn't
match the final segment of the candidate. For example, previously "ab"
would not match "abc.def" because the "b" in "ab" did not match the
final segment "def". I can see how this is useful when the text
matching happens in a vacuum and candidate's final segment is the most
specific part. But, in our case, we have various other methods to
order candidates, so we don't want to exclude them just because the
final segment doesn't match. For example, if we know our candidate
needs to be type "context.Context" and "foo.ctx" is of the right type,
we want to suggest "foo.ctx" as soon as the user starts inputting
"foo", even though "foo" doesn't match "ctx" at all.
Note that fuzzy matching is behind the "useDeepCompletions" config
flag for the time being.
Change-Id: Ic7674f0cf885af770c30daef472f2e3c5ac4db78
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190099
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-08-13 14:45:19 -06:00
|
|
|
// matcher matches the candidates against the surrounding prefix.
|
|
|
|
matcher matcher
|
2019-08-16 10:45:09 -06:00
|
|
|
|
|
|
|
// methodSetCache caches the types.NewMethodSet call, which is relatively
|
|
|
|
// expensive and can be called many times for the same type while searching
|
|
|
|
// for deep completions.
|
|
|
|
methodSetCache map[methodSetKey]*types.MethodSet
|
2019-08-16 15:05:40 -06:00
|
|
|
|
|
|
|
// mapper converts the positions in the file from which the completion originated.
|
|
|
|
mapper *protocol.ColumnMapper
|
internal/lsp: limit deep completion search scope
Deep completions can take a long time (500ms+) if there are many
large, deeply nested structs in scope. To make sure we return
completion results in a timely manner we now notice if we have spent
"too long" searching for deep completions and reduce the search scope.
In particular, our overall completion budget is 100ms. This value is
often cited as the longest latency that still feels instantaneous to
most people. As we spend 25%, 50%, and 75% of our budget we limit our
deep completion candidate search depth to 4, 3, and 2,
respectively. If we hit 90% of our budget, we disable deep completions
entirely.
In my testing, limiting the search scope to 4 normally makes even
enormous searches finish in a few milliseconds. Of course, you can
have arbitrarily many objects in scope with arbitrarily many fields,
so to cover our bases we continue to dial down the search depth as
needed.
I replaced the "enabled" field with a "maxDepth" field that disables
deep search when set to 0.
Change-Id: I9b5a07de70709895c065503ae6082d1ea615d1af
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190978
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
2019-08-18 13:55:34 -06:00
|
|
|
|
|
|
|
// startTime is when we started processing this completion request. It does
|
|
|
|
// not include any time the request spent in the queue.
|
|
|
|
startTime time.Time
|
2019-05-13 15:37:08 -06:00
|
|
|
}
|
|
|
|
|
2019-09-18 13:26:39 -06:00
|
|
|
// funcInfo holds info about a function object.
|
|
|
|
type funcInfo struct {
|
|
|
|
// sig is the function declaration enclosing the position.
|
|
|
|
sig *types.Signature
|
|
|
|
|
|
|
|
// body is the function's body.
|
|
|
|
body *ast.BlockStmt
|
|
|
|
}
|
|
|
|
|
2019-05-13 15:37:08 -06:00
|
|
|
type compLitInfo struct {
|
|
|
|
// cl is the *ast.CompositeLit enclosing the position.
|
|
|
|
cl *ast.CompositeLit
|
|
|
|
|
|
|
|
// clType is the type of cl.
|
|
|
|
clType types.Type
|
2019-04-28 21:19:54 -06:00
|
|
|
|
2019-05-13 15:37:08 -06:00
|
|
|
// kv is the *ast.KeyValueExpr enclosing the position, if any.
|
|
|
|
kv *ast.KeyValueExpr
|
2019-04-28 21:19:54 -06:00
|
|
|
|
2019-05-13 15:37:08 -06:00
|
|
|
// inKey is true if we are certain the position is in the key side
|
|
|
|
// of a key-value pair.
|
|
|
|
inKey bool
|
|
|
|
|
|
|
|
// maybeInFieldName is true if inKey is false and it is possible
|
|
|
|
// we are completing a struct field name. For example,
|
|
|
|
// "SomeStruct{<>}" will be inKey=false, but maybeInFieldName=true
|
|
|
|
// because we _could_ be completing a field name.
|
|
|
|
maybeInFieldName bool
|
2019-04-24 17:26:34 -06:00
|
|
|
}
|
|
|
|
|
2019-11-05 12:53:55 -07:00
|
|
|
type importInfo struct {
|
|
|
|
importPath string
|
|
|
|
name string
|
|
|
|
pkg Package
|
|
|
|
}
|
|
|
|
|
2019-08-16 10:45:09 -06:00
|
|
|
type methodSetKey struct {
|
|
|
|
typ types.Type
|
|
|
|
addressable bool
|
|
|
|
}
|
|
|
|
|
2019-05-17 11:45:59 -06:00
|
|
|
// A Selection represents the cursor position and surrounding identifier.
|
|
|
|
type Selection struct {
|
2019-08-16 15:05:40 -06:00
|
|
|
content string
|
|
|
|
cursor token.Pos
|
|
|
|
mappedRange
|
2019-05-13 14:49:29 -06:00
|
|
|
}
|
|
|
|
|
2019-05-17 11:45:59 -06:00
|
|
|
func (p Selection) Prefix() string {
|
2019-08-16 15:05:40 -06:00
|
|
|
return p.content[:p.cursor-p.spanRange.Start]
|
2019-05-17 11:45:59 -06:00
|
|
|
}
|
|
|
|
|
2019-09-17 20:48:41 -06:00
|
|
|
func (p Selection) Suffix() string {
|
|
|
|
return p.content[p.cursor-p.spanRange.Start:]
|
|
|
|
}
|
|
|
|
|
2019-12-27 13:46:49 -07:00
|
|
|
func (c *completer) deepCompletionContext() (context.Context, context.CancelFunc) {
|
|
|
|
if c.opts.Budget == 0 {
|
|
|
|
return context.WithCancel(c.ctx)
|
|
|
|
}
|
|
|
|
return context.WithDeadline(c.ctx, c.startTime.Add(c.opts.Budget))
|
|
|
|
}
|
|
|
|
|
2019-05-17 11:45:59 -06:00
|
|
|
func (c *completer) setSurrounding(ident *ast.Ident) {
|
|
|
|
if c.surrounding != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if !(ident.Pos() <= c.pos && c.pos <= ident.End()) {
|
|
|
|
return
|
|
|
|
}
|
2019-09-17 20:48:41 -06:00
|
|
|
|
2019-05-17 11:45:59 -06:00
|
|
|
c.surrounding = &Selection{
|
2019-08-16 15:05:40 -06:00
|
|
|
content: ident.Name,
|
|
|
|
cursor: c.pos,
|
2019-11-22 13:20:08 -07:00
|
|
|
// Overwrite the prefix only.
|
|
|
|
mappedRange: newMappedRange(c.snapshot.View().Session().Cache().FileSet(), c.mapper, ident.Pos(), ident.End()),
|
2019-05-17 11:45:59 -06:00
|
|
|
}
|
internal/lsp: add fuzzy completion matching
Make use of the existing fuzzy matcher to perform server side fuzzy
completion matching. Previously the server did exact prefix matching
for completion candidates and left fancy filtering to the
client. Having the server do fuzzy matching has two main benefits:
- Deep completions now update as you type. The completion candidates
returned to the client are marked "incomplete", causing the client
to refresh the candidates after every keystroke. This lets the
server pick the most relevant set of deep completion candidates.
- All editors get fuzzy matching for free. VSCode has fuzzy matching
out of the box, but some editors either don't provide it, or it can
be difficult to set up.
I modified the fuzzy matcher to allow matches where the input doesn't
match the final segment of the candidate. For example, previously "ab"
would not match "abc.def" because the "b" in "ab" did not match the
final segment "def". I can see how this is useful when the text
matching happens in a vacuum and candidate's final segment is the most
specific part. But, in our case, we have various other methods to
order candidates, so we don't want to exclude them just because the
final segment doesn't match. For example, if we know our candidate
needs to be type "context.Context" and "foo.ctx" is of the right type,
we want to suggest "foo.ctx" as soon as the user starts inputting
"foo", even though "foo" doesn't match "ctx" at all.
Note that fuzzy matching is behind the "useDeepCompletions" config
flag for the time being.
Change-Id: Ic7674f0cf885af770c30daef472f2e3c5ac4db78
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190099
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-08-13 14:45:19 -06:00
|
|
|
|
2019-09-05 22:17:36 -06:00
|
|
|
if c.opts.FuzzyMatching {
|
2019-10-21 22:07:21 -06:00
|
|
|
c.matcher = fuzzy.NewMatcher(c.surrounding.Prefix())
|
2019-09-26 05:59:06 -06:00
|
|
|
} else if c.opts.CaseSensitive {
|
|
|
|
c.matcher = prefixMatcher(c.surrounding.Prefix())
|
internal/lsp: add fuzzy completion matching
Make use of the existing fuzzy matcher to perform server side fuzzy
completion matching. Previously the server did exact prefix matching
for completion candidates and left fancy filtering to the
client. Having the server do fuzzy matching has two main benefits:
- Deep completions now update as you type. The completion candidates
returned to the client are marked "incomplete", causing the client
to refresh the candidates after every keystroke. This lets the
server pick the most relevant set of deep completion candidates.
- All editors get fuzzy matching for free. VSCode has fuzzy matching
out of the box, but some editors either don't provide it, or it can
be difficult to set up.
I modified the fuzzy matcher to allow matches where the input doesn't
match the final segment of the candidate. For example, previously "ab"
would not match "abc.def" because the "b" in "ab" did not match the
final segment "def". I can see how this is useful when the text
matching happens in a vacuum and candidate's final segment is the most
specific part. But, in our case, we have various other methods to
order candidates, so we don't want to exclude them just because the
final segment doesn't match. For example, if we know our candidate
needs to be type "context.Context" and "foo.ctx" is of the right type,
we want to suggest "foo.ctx" as soon as the user starts inputting
"foo", even though "foo" doesn't match "ctx" at all.
Note that fuzzy matching is behind the "useDeepCompletions" config
flag for the time being.
Change-Id: Ic7674f0cf885af770c30daef472f2e3c5ac4db78
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190099
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-08-13 14:45:19 -06:00
|
|
|
} else {
|
2019-09-26 05:59:06 -06:00
|
|
|
c.matcher = insensitivePrefixMatcher(strings.ToLower(c.surrounding.Prefix()))
|
2019-07-01 15:08:29 -06:00
|
|
|
}
|
2019-05-17 11:45:59 -06:00
|
|
|
}
|
2019-05-13 14:49:29 -06:00
|
|
|
|
2019-08-16 15:05:40 -06:00
|
|
|
func (c *completer) getSurrounding() *Selection {
|
|
|
|
if c.surrounding == nil {
|
|
|
|
c.surrounding = &Selection{
|
2019-11-22 13:20:08 -07:00
|
|
|
content: "",
|
|
|
|
cursor: c.pos,
|
|
|
|
mappedRange: newMappedRange(c.snapshot.View().Session().Cache().FileSet(), c.mapper, c.pos, c.pos),
|
2019-08-16 15:05:40 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return c.surrounding
|
|
|
|
}
|
|
|
|
|
2019-06-27 11:50:01 -06:00
|
|
|
// found adds a candidate completion. We will also search through the object's
|
|
|
|
// members for more candidates.
|
2019-12-21 16:39:02 -07:00
|
|
|
func (c *completer) found(cand candidate) {
|
|
|
|
obj := cand.obj
|
|
|
|
|
2019-09-09 18:22:42 -06:00
|
|
|
if obj.Pkg() != nil && obj.Pkg() != c.pkg.GetTypes() && !obj.Exported() {
|
2019-08-16 10:45:09 -06:00
|
|
|
// obj is not accessible because it lives in another package and is not
|
|
|
|
// exported. Don't treat it as a completion candidate.
|
|
|
|
return
|
2019-04-24 17:26:34 -06:00
|
|
|
}
|
2019-06-27 11:50:01 -06:00
|
|
|
|
|
|
|
if c.inDeepCompletion() {
|
|
|
|
// When searching deep, just make sure we don't have a cycle in our chain.
|
|
|
|
// We don't dedupe by object because we want to allow both "foo.Baz" and
|
|
|
|
// "bar.Baz" even though "Baz" is represented the same types.Object in both.
|
|
|
|
for _, seenObj := range c.deepState.chain {
|
|
|
|
if seenObj == obj {
|
2019-08-16 10:45:09 -06:00
|
|
|
return
|
2019-06-27 11:50:01 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// At the top level, dedupe by object.
|
|
|
|
if c.seen[obj] {
|
2019-08-16 10:45:09 -06:00
|
|
|
return
|
2019-06-27 11:50:01 -06:00
|
|
|
}
|
|
|
|
c.seen[obj] = true
|
2019-04-24 17:26:34 -06:00
|
|
|
}
|
2019-06-19 16:24:05 -06:00
|
|
|
|
internal/lsp: limit deep completion search scope
Deep completions can take a long time (500ms+) if there are many
large, deeply nested structs in scope. To make sure we return
completion results in a timely manner we now notice if we have spent
"too long" searching for deep completions and reduce the search scope.
In particular, our overall completion budget is 100ms. This value is
often cited as the longest latency that still feels instantaneous to
most people. As we spend 25%, 50%, and 75% of our budget we limit our
deep completion candidate search depth to 4, 3, and 2,
respectively. If we hit 90% of our budget, we disable deep completions
entirely.
In my testing, limiting the search scope to 4 normally makes even
enormous searches finish in a few milliseconds. Of course, you can
have arbitrarily many objects in scope with arbitrarily many fields,
so to cover our bases we continue to dial down the search depth as
needed.
I replaced the "enabled" field with a "maxDepth" field that disables
deep search when set to 0.
Change-Id: I9b5a07de70709895c065503ae6082d1ea615d1af
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190978
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
2019-08-18 13:55:34 -06:00
|
|
|
// If we are running out of budgeted time we must limit our search for deep
|
|
|
|
// completion candidates.
|
|
|
|
if c.shouldPrune() {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
internal/lsp: add literal completion candidates
Add support for literal completion candidates such as "[]int{}" or
"make([]int, 0)". We support both named and unnamed types. I used the
existing type matching logic, so, for example, if the expected type is
an interface, we will suggest literal candidates that implement the
interface.
The literal candidates have a lower score than normal matching
candidates, so they shouldn't be disruptive in cases where you don't
want a literal candidate.
This commit adds support for slice, array, struct, map, and channel
literal candidates since they are pretty similar. Functions will be
supported in a subsequent commit.
I also added support for setting a snippet's final tab stop. This is
useful if you want the cursor to end up somewhere other than the
character after the snippet.
Change-Id: Id3b74260fff4d61703989b422267021b00cec005
Reviewed-on: https://go-review.googlesource.com/c/tools/+/193698
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-09-04 17:12:37 -06:00
|
|
|
if c.matchingCandidate(&cand) {
|
2019-06-19 16:24:05 -06:00
|
|
|
cand.score *= highScore
|
internal/lsp: add literal completion candidates
Add support for literal completion candidates such as "[]int{}" or
"make([]int, 0)". We support both named and unnamed types. I used the
existing type matching logic, so, for example, if the expected type is
an interface, we will suggest literal candidates that implement the
interface.
The literal candidates have a lower score than normal matching
candidates, so they shouldn't be disruptive in cases where you don't
want a literal candidate.
This commit adds support for slice, array, struct, map, and channel
literal candidates since they are pretty similar. Functions will be
supported in a subsequent commit.
I also added support for setting a snippet's final tab stop. This is
useful if you want the cursor to end up somewhere other than the
character after the snippet.
Change-Id: Id3b74260fff4d61703989b422267021b00cec005
Reviewed-on: https://go-review.googlesource.com/c/tools/+/193698
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-09-04 17:12:37 -06:00
|
|
|
} else if isTypeName(obj) {
|
|
|
|
// If obj is a *types.TypeName that didn't otherwise match, check
|
|
|
|
// if a literal object of this type makes a good candidate.
|
2019-12-06 15:29:09 -07:00
|
|
|
|
|
|
|
// We only care about named types (i.e. don't want builtin types).
|
|
|
|
if _, isNamed := obj.Type().(*types.Named); isNamed {
|
2019-12-21 16:39:02 -07:00
|
|
|
c.literal(obj.Type(), cand.imp)
|
2019-12-06 15:29:09 -07:00
|
|
|
}
|
2019-04-24 17:26:34 -06:00
|
|
|
}
|
2019-06-19 16:24:05 -06:00
|
|
|
|
2019-06-27 11:50:01 -06:00
|
|
|
// Favor shallow matches by lowering weight according to depth.
|
2019-08-27 17:41:48 -06:00
|
|
|
cand.score -= cand.score * float64(len(c.deepState.chain)) / 10
|
|
|
|
if cand.score < 0 {
|
|
|
|
cand.score = 0
|
|
|
|
}
|
internal/lsp: add fuzzy completion matching
Make use of the existing fuzzy matcher to perform server side fuzzy
completion matching. Previously the server did exact prefix matching
for completion candidates and left fancy filtering to the
client. Having the server do fuzzy matching has two main benefits:
- Deep completions now update as you type. The completion candidates
returned to the client are marked "incomplete", causing the client
to refresh the candidates after every keystroke. This lets the
server pick the most relevant set of deep completion candidates.
- All editors get fuzzy matching for free. VSCode has fuzzy matching
out of the box, but some editors either don't provide it, or it can
be difficult to set up.
I modified the fuzzy matcher to allow matches where the input doesn't
match the final segment of the candidate. For example, previously "ab"
would not match "abc.def" because the "b" in "ab" did not match the
final segment "def". I can see how this is useful when the text
matching happens in a vacuum and candidate's final segment is the most
specific part. But, in our case, we have various other methods to
order candidates, so we don't want to exclude them just because the
final segment doesn't match. For example, if we know our candidate
needs to be type "context.Context" and "foo.ctx" is of the right type,
we want to suggest "foo.ctx" as soon as the user starts inputting
"foo", even though "foo" doesn't match "ctx" at all.
Note that fuzzy matching is behind the "useDeepCompletions" config
flag for the time being.
Change-Id: Ic7674f0cf885af770c30daef472f2e3c5ac4db78
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190099
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-08-13 14:45:19 -06:00
|
|
|
|
2019-08-16 10:45:09 -06:00
|
|
|
cand.name = c.deepState.chainString(obj.Name())
|
|
|
|
matchScore := c.matcher.Score(cand.name)
|
2019-09-13 23:13:55 -06:00
|
|
|
if matchScore > 0 {
|
2019-08-16 10:45:09 -06:00
|
|
|
cand.score *= float64(matchScore)
|
|
|
|
|
|
|
|
// Avoid calling c.item() for deep candidates that wouldn't be in the top
|
|
|
|
// MaxDeepCompletions anyway.
|
|
|
|
if !c.inDeepCompletion() || c.deepState.isHighScore(cand.score) {
|
|
|
|
if item, err := c.item(cand); err == nil {
|
|
|
|
c.items = append(c.items, item)
|
|
|
|
}
|
internal/lsp: add fuzzy completion matching
Make use of the existing fuzzy matcher to perform server side fuzzy
completion matching. Previously the server did exact prefix matching
for completion candidates and left fancy filtering to the
client. Having the server do fuzzy matching has two main benefits:
- Deep completions now update as you type. The completion candidates
returned to the client are marked "incomplete", causing the client
to refresh the candidates after every keystroke. This lets the
server pick the most relevant set of deep completion candidates.
- All editors get fuzzy matching for free. VSCode has fuzzy matching
out of the box, but some editors either don't provide it, or it can
be difficult to set up.
I modified the fuzzy matcher to allow matches where the input doesn't
match the final segment of the candidate. For example, previously "ab"
would not match "abc.def" because the "b" in "ab" did not match the
final segment "def". I can see how this is useful when the text
matching happens in a vacuum and candidate's final segment is the most
specific part. But, in our case, we have various other methods to
order candidates, so we don't want to exclude them just because the
final segment doesn't match. For example, if we know our candidate
needs to be type "context.Context" and "foo.ctx" is of the right type,
we want to suggest "foo.ctx" as soon as the user starts inputting
"foo", even though "foo" doesn't match "ctx" at all.
Note that fuzzy matching is behind the "useDeepCompletions" config
flag for the time being.
Change-Id: Ic7674f0cf885af770c30daef472f2e3c5ac4db78
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190099
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-08-13 14:45:19 -06:00
|
|
|
}
|
|
|
|
}
|
2019-06-27 11:50:01 -06:00
|
|
|
|
2019-12-21 16:39:02 -07:00
|
|
|
c.deepSearch(cand)
|
2019-06-19 16:24:05 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
// candidate represents a completion candidate.
|
|
|
|
type candidate struct {
|
|
|
|
// obj is the types.Object to complete to.
|
|
|
|
obj types.Object
|
|
|
|
|
|
|
|
// score is used to rank candidates.
|
|
|
|
score float64
|
|
|
|
|
2019-08-16 10:45:09 -06:00
|
|
|
// name is the deep object name path, e.g. "foo.bar"
|
|
|
|
name string
|
|
|
|
|
2019-06-19 16:24:05 -06:00
|
|
|
// expandFuncCall is true if obj should be invoked in the completion.
|
|
|
|
// For example, expandFuncCall=true yields "foo()", expandFuncCall=false yields "foo".
|
|
|
|
expandFuncCall bool
|
2019-08-14 15:25:47 -06:00
|
|
|
|
2019-12-22 10:58:14 -07:00
|
|
|
// takeAddress is true if the completion should take a pointer to obj.
|
|
|
|
// For example, takeAddress=true yields "&foo", takeAddress=false yields "foo".
|
|
|
|
takeAddress bool
|
|
|
|
|
|
|
|
// addressable is true if a pointer can be taken to the candidate.
|
|
|
|
addressable bool
|
|
|
|
|
2019-08-14 15:25:47 -06:00
|
|
|
// imp is the import that needs to be added to this package in order
|
|
|
|
// for this candidate to be valid. nil if no import needed.
|
2019-11-05 12:53:55 -07:00
|
|
|
imp *importInfo
|
2019-04-24 17:26:34 -06:00
|
|
|
}
|
2018-12-05 15:00:36 -07:00
|
|
|
|
2019-09-17 16:52:19 -06:00
|
|
|
// ErrIsDefinition is an error that informs the user they got no
|
|
|
|
// completions because they tried to complete the name of a new object
|
|
|
|
// being defined.
|
|
|
|
type ErrIsDefinition struct {
|
|
|
|
objStr string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e ErrIsDefinition) Error() string {
|
|
|
|
msg := "this is a definition"
|
|
|
|
if e.objStr != "" {
|
|
|
|
msg += " of " + e.objStr
|
|
|
|
}
|
|
|
|
return msg
|
|
|
|
}
|
|
|
|
|
2018-12-05 15:00:36 -07:00
|
|
|
// Completion returns a list of possible candidates for completion, given a
|
2019-04-24 17:26:34 -06:00
|
|
|
// a file and a position.
|
|
|
|
//
|
2019-05-17 11:45:59 -06:00
|
|
|
// The selection is computed based on the preceding identifier and can be used by
|
2019-04-24 17:26:34 -06:00
|
|
|
// the client to score the quality of the completion. For instance, some clients
|
|
|
|
// may tolerate imperfect matches as valid completion results, since users may make typos.
|
2019-12-17 16:57:54 -07:00
|
|
|
func Completion(ctx context.Context, snapshot Snapshot, fh FileHandle, pos protocol.Position, opts CompletionOptions) ([]CompletionItem, *Selection, error) {
|
2019-06-26 20:46:12 -06:00
|
|
|
ctx, done := trace.StartSpan(ctx, "source.Completion")
|
|
|
|
defer done()
|
2019-07-11 19:05:55 -06:00
|
|
|
|
internal/lsp: limit deep completion search scope
Deep completions can take a long time (500ms+) if there are many
large, deeply nested structs in scope. To make sure we return
completion results in a timely manner we now notice if we have spent
"too long" searching for deep completions and reduce the search scope.
In particular, our overall completion budget is 100ms. This value is
often cited as the longest latency that still feels instantaneous to
most people. As we spend 25%, 50%, and 75% of our budget we limit our
deep completion candidate search depth to 4, 3, and 2,
respectively. If we hit 90% of our budget, we disable deep completions
entirely.
In my testing, limiting the search scope to 4 normally makes even
enormous searches finish in a few milliseconds. Of course, you can
have arbitrarily many objects in scope with arbitrarily many fields,
so to cover our bases we continue to dial down the search depth as
needed.
I replaced the "enabled" field with a "maxDepth" field that disables
deep search when set to 0.
Change-Id: I9b5a07de70709895c065503ae6082d1ea615d1af
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190978
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
2019-08-18 13:55:34 -06:00
|
|
|
startTime := time.Now()
|
|
|
|
|
2019-12-17 16:57:54 -07:00
|
|
|
pkg, pgh, err := getParsedFile(ctx, snapshot, fh, NarrowestCheckPackageHandle)
|
2019-09-09 17:26:26 -06:00
|
|
|
if err != nil {
|
2019-12-04 11:45:53 -07:00
|
|
|
return nil, nil, fmt.Errorf("getting file for Completion: %v", err)
|
2019-08-16 15:05:40 -06:00
|
|
|
}
|
2019-11-29 23:17:57 -07:00
|
|
|
file, m, _, err := pgh.Cached()
|
2019-09-17 09:19:11 -06:00
|
|
|
if err != nil {
|
2019-07-11 19:05:55 -06:00
|
|
|
return nil, nil, err
|
2019-05-20 13:23:02 -06:00
|
|
|
}
|
2019-08-16 15:05:40 -06:00
|
|
|
spn, err := m.PointSpan(pos)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
rng, err := spn.Range(m.Converter)
|
2019-07-09 15:52:23 -06:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
2019-03-11 15:14:55 -06:00
|
|
|
}
|
2019-04-23 16:00:40 -06:00
|
|
|
// Completion is based on what precedes the cursor.
|
2019-04-24 17:26:34 -06:00
|
|
|
// Find the path to the position before pos.
|
2019-08-16 15:05:40 -06:00
|
|
|
path, _ := astutil.PathEnclosingInterval(file, rng.Start-1, rng.Start-1)
|
2018-11-07 18:57:08 -07:00
|
|
|
if path == nil {
|
2019-08-06 13:13:11 -06:00
|
|
|
return nil, nil, errors.Errorf("cannot find node enclosing position")
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-12-10 14:40:37 -07:00
|
|
|
|
2019-04-23 16:34:23 -06:00
|
|
|
// Skip completion inside any kind of literal.
|
|
|
|
if _, ok := path[0].(*ast.BasicLit); ok {
|
2019-05-17 11:45:59 -06:00
|
|
|
return nil, nil, nil
|
2019-01-15 23:36:31 -07:00
|
|
|
}
|
|
|
|
|
2019-04-24 17:26:34 -06:00
|
|
|
c := &completer{
|
2019-09-09 18:22:42 -06:00
|
|
|
pkg: pkg,
|
2019-09-27 11:17:59 -06:00
|
|
|
snapshot: snapshot,
|
2019-04-28 21:19:54 -06:00
|
|
|
qf: qualifier(file, pkg.GetTypes(), pkg.GetTypesInfo()),
|
2019-04-29 19:08:16 -06:00
|
|
|
ctx: ctx,
|
2019-12-17 16:57:54 -07:00
|
|
|
filename: fh.Identity().URI.Filename(),
|
2019-08-14 15:25:47 -06:00
|
|
|
file: file,
|
2019-04-28 21:19:54 -06:00
|
|
|
path: path,
|
2019-08-16 15:05:40 -06:00
|
|
|
pos: rng.Start,
|
2019-04-28 21:19:54 -06:00
|
|
|
seen: make(map[types.Object]bool),
|
2019-09-18 13:26:39 -06:00
|
|
|
enclosingFunc: enclosingFunction(path, rng.Start, pkg.GetTypesInfo()),
|
|
|
|
enclosingCompositeLiteral: enclosingCompositeLiteral(path, rng.Start, pkg.GetTypesInfo()),
|
2019-07-02 15:31:31 -06:00
|
|
|
opts: opts,
|
2019-08-16 10:45:09 -06:00
|
|
|
// default to a matcher that always matches
|
|
|
|
matcher: prefixMatcher(""),
|
|
|
|
methodSetCache: make(map[methodSetKey]*types.MethodSet),
|
2019-08-16 15:05:40 -06:00
|
|
|
mapper: m,
|
internal/lsp: limit deep completion search scope
Deep completions can take a long time (500ms+) if there are many
large, deeply nested structs in scope. To make sure we return
completion results in a timely manner we now notice if we have spent
"too long" searching for deep completions and reduce the search scope.
In particular, our overall completion budget is 100ms. This value is
often cited as the longest latency that still feels instantaneous to
most people. As we spend 25%, 50%, and 75% of our budget we limit our
deep completion candidate search depth to 4, 3, and 2,
respectively. If we hit 90% of our budget, we disable deep completions
entirely.
In my testing, limiting the search scope to 4 normally makes even
enormous searches finish in a few milliseconds. Of course, you can
have arbitrarily many objects in scope with arbitrarily many fields,
so to cover our bases we continue to dial down the search depth as
needed.
I replaced the "enabled" field with a "maxDepth" field that disables
deep search when set to 0.
Change-Id: I9b5a07de70709895c065503ae6082d1ea615d1af
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190978
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
2019-08-18 13:55:34 -06:00
|
|
|
startTime: startTime,
|
2019-04-24 17:26:34 -06:00
|
|
|
}
|
2019-01-31 23:40:03 -07:00
|
|
|
|
2019-09-05 22:17:36 -06:00
|
|
|
if opts.Deep {
|
2019-08-27 17:41:48 -06:00
|
|
|
// Initialize max search depth to unlimited.
|
internal/lsp: limit deep completion search scope
Deep completions can take a long time (500ms+) if there are many
large, deeply nested structs in scope. To make sure we return
completion results in a timely manner we now notice if we have spent
"too long" searching for deep completions and reduce the search scope.
In particular, our overall completion budget is 100ms. This value is
often cited as the longest latency that still feels instantaneous to
most people. As we spend 25%, 50%, and 75% of our budget we limit our
deep completion candidate search depth to 4, 3, and 2,
respectively. If we hit 90% of our budget, we disable deep completions
entirely.
In my testing, limiting the search scope to 4 normally makes even
enormous searches finish in a few milliseconds. Of course, you can
have arbitrarily many objects in scope with arbitrarily many fields,
so to cover our bases we continue to dial down the search depth as
needed.
I replaced the "enabled" field with a "maxDepth" field that disables
deep search when set to 0.
Change-Id: I9b5a07de70709895c065503ae6082d1ea615d1af
Reviewed-on: https://go-review.googlesource.com/c/tools/+/190978
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
2019-08-18 13:55:34 -06:00
|
|
|
c.deepState.maxDepth = -1
|
|
|
|
}
|
2019-06-27 11:50:01 -06:00
|
|
|
|
2019-05-17 11:45:59 -06:00
|
|
|
// Set the filter surrounding.
|
2019-05-13 15:37:08 -06:00
|
|
|
if ident, ok := path[0].(*ast.Ident); ok {
|
2019-05-17 11:45:59 -06:00
|
|
|
c.setSurrounding(ident)
|
2019-05-13 15:37:08 -06:00
|
|
|
}
|
2019-05-10 10:26:15 -06:00
|
|
|
|
2019-05-13 15:37:08 -06:00
|
|
|
c.expectedType = expectedType(c)
|
2019-04-24 17:26:34 -06:00
|
|
|
|
2019-12-10 14:40:37 -07:00
|
|
|
// If we're inside a comment return comment completions
|
|
|
|
for _, comment := range file.Comments {
|
|
|
|
if comment.Pos() <= rng.Start && rng.Start <= comment.End() {
|
|
|
|
c.populateCommentCompletions(comment)
|
|
|
|
return c.items, c.getSurrounding(), nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-13 15:37:08 -06:00
|
|
|
// Struct literals are handled entirely separately.
|
|
|
|
if c.wantStructFieldCompletions() {
|
|
|
|
if err := c.structLiteralFieldName(); err != nil {
|
2019-05-17 11:45:59 -06:00
|
|
|
return nil, nil, err
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-08-16 15:05:40 -06:00
|
|
|
return c.items, c.getSurrounding(), nil
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
|
2019-09-18 13:26:39 -06:00
|
|
|
if lt := c.wantLabelCompletion(); lt != labelNone {
|
|
|
|
c.labels(lt)
|
|
|
|
return c.items, c.getSurrounding(), nil
|
|
|
|
}
|
|
|
|
|
2018-11-07 18:57:08 -07:00
|
|
|
switch n := path[0].(type) {
|
|
|
|
case *ast.Ident:
|
|
|
|
// Is this the Sel part of a selector?
|
|
|
|
if sel, ok := path[1].(*ast.SelectorExpr); ok && sel.Sel == n {
|
2019-04-24 17:26:34 -06:00
|
|
|
if err := c.selector(sel); err != nil {
|
2019-05-17 11:45:59 -06:00
|
|
|
return nil, nil, err
|
2019-04-24 17:26:34 -06:00
|
|
|
}
|
2019-08-16 15:05:40 -06:00
|
|
|
return c.items, c.getSurrounding(), nil
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
// reject defining identifiers
|
2019-03-06 14:33:47 -07:00
|
|
|
if obj, ok := pkg.GetTypesInfo().Defs[n]; ok {
|
2019-09-17 16:52:19 -06:00
|
|
|
if v, ok := obj.(*types.Var); ok && v.IsField() && v.Embedded() {
|
2018-11-07 18:57:08 -07:00
|
|
|
// An anonymous field is also a reference to a type.
|
|
|
|
} else {
|
2019-09-17 16:52:19 -06:00
|
|
|
objStr := ""
|
2018-11-07 18:57:08 -07:00
|
|
|
if obj != nil {
|
2019-03-06 14:33:47 -07:00
|
|
|
qual := types.RelativeTo(pkg.GetTypes())
|
2019-09-17 16:52:19 -06:00
|
|
|
objStr = types.ObjectString(obj, qual)
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-09-17 16:52:19 -06:00
|
|
|
return nil, nil, ErrIsDefinition{objStr: objStr}
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
}
|
2019-04-24 17:26:34 -06:00
|
|
|
if err := c.lexical(); err != nil {
|
2019-05-17 11:45:59 -06:00
|
|
|
return nil, nil, err
|
2019-04-24 17:26:34 -06:00
|
|
|
}
|
2019-09-20 14:01:33 -06:00
|
|
|
if err := c.keyword(); err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
|
|
|
|
// The function name hasn't been typed yet, but the parens are there:
|
|
|
|
// recv.‸(arg)
|
|
|
|
case *ast.TypeAssertExpr:
|
|
|
|
// Create a fake selector expression.
|
2019-04-24 17:26:34 -06:00
|
|
|
if err := c.selector(&ast.SelectorExpr{X: n.X}); err != nil {
|
2019-05-17 11:45:59 -06:00
|
|
|
return nil, nil, err
|
2019-04-24 17:26:34 -06:00
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
|
|
|
|
case *ast.SelectorExpr:
|
2019-05-20 15:31:13 -06:00
|
|
|
// The go parser inserts a phantom "_" Sel node when the selector is
|
|
|
|
// not followed by an identifier or a "(". The "_" isn't actually in
|
|
|
|
// the text, so don't think it is our surrounding.
|
|
|
|
// TODO: Find a way to differentiate between phantom "_" and real "_",
|
|
|
|
// perhaps by checking if "_" is present in file contents.
|
|
|
|
if n.Sel.Name != "_" || c.pos != n.Sel.Pos() {
|
|
|
|
c.setSurrounding(n.Sel)
|
|
|
|
}
|
2019-05-17 11:45:59 -06:00
|
|
|
|
2019-04-24 17:26:34 -06:00
|
|
|
if err := c.selector(n); err != nil {
|
2019-05-17 11:45:59 -06:00
|
|
|
return nil, nil, err
|
2019-04-24 17:26:34 -06:00
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
|
|
|
|
default:
|
|
|
|
// fallback to lexical completions
|
2019-04-24 17:26:34 -06:00
|
|
|
if err := c.lexical(); err != nil {
|
2019-05-17 11:45:59 -06:00
|
|
|
return nil, nil, err
|
2019-04-24 17:26:34 -06:00
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-05-13 15:37:08 -06:00
|
|
|
|
2019-08-16 15:05:40 -06:00
|
|
|
return c.items, c.getSurrounding(), nil
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
|
2019-12-22 10:58:14 -07:00
|
|
|
// populateCommentCompletions yields completions for an exported
|
|
|
|
// variable immediately preceding comment.
|
2019-12-10 14:40:37 -07:00
|
|
|
func (c *completer) populateCommentCompletions(comment *ast.CommentGroup) {
|
|
|
|
|
|
|
|
// Using the comment position find the line after
|
|
|
|
fset := c.snapshot.View().Session().Cache().FileSet()
|
|
|
|
file := fset.File(comment.Pos())
|
|
|
|
if file == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
line := file.Line(comment.Pos())
|
|
|
|
nextLinePos := file.LineStart(line + 1)
|
|
|
|
if !nextLinePos.IsValid() {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Using the next line pos, grab and parse the exported variable on that line
|
|
|
|
for _, n := range c.file.Decls {
|
|
|
|
if n.Pos() != nextLinePos {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
switch node := n.(type) {
|
|
|
|
case *ast.GenDecl:
|
|
|
|
if node.Tok != token.VAR {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
for _, spec := range node.Specs {
|
|
|
|
if value, ok := spec.(*ast.ValueSpec); ok {
|
|
|
|
for _, name := range value.Names {
|
|
|
|
if name.Name == "_" || !name.IsExported() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
exportedVar := c.pkg.GetTypesInfo().ObjectOf(name)
|
2019-12-21 16:39:02 -07:00
|
|
|
c.found(candidate{obj: exportedVar, score: stdScore})
|
2019-12-10 14:40:37 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-13 15:37:08 -06:00
|
|
|
func (c *completer) wantStructFieldCompletions() bool {
|
|
|
|
clInfo := c.enclosingCompositeLiteral
|
|
|
|
if clInfo == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return clInfo.isStruct() && (clInfo.inKey || clInfo.maybeInFieldName)
|
|
|
|
}
|
|
|
|
|
2019-06-17 12:11:13 -06:00
|
|
|
func (c *completer) wantTypeName() bool {
|
2019-09-13 13:15:53 -06:00
|
|
|
return c.expectedType.typeName.wantTypeName
|
2019-06-17 12:11:13 -06:00
|
|
|
}
|
|
|
|
|
2019-12-05 16:08:19 -07:00
|
|
|
// See https://golang.org/issue/36001. Unimported completions are expensive.
|
2019-12-23 11:19:17 -07:00
|
|
|
const unimportedTarget = 100
|
2019-12-05 16:08:19 -07:00
|
|
|
|
2019-04-24 17:26:34 -06:00
|
|
|
// selector finds completions for the specified selector expression.
|
|
|
|
func (c *completer) selector(sel *ast.SelectorExpr) error {
|
2018-11-07 18:57:08 -07:00
|
|
|
// Is sel a qualified identifier?
|
|
|
|
if id, ok := sel.X.(*ast.Ident); ok {
|
2019-09-09 18:22:42 -06:00
|
|
|
if pkgname, ok := c.pkg.GetTypesInfo().Uses[id].(*types.PkgName); ok {
|
2019-12-30 11:29:58 -07:00
|
|
|
c.packageMembers(pkgname.Imported(), stdScore, nil)
|
2019-04-24 17:26:34 -06:00
|
|
|
return nil
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-24 17:26:34 -06:00
|
|
|
// Invariant: sel is a true selector.
|
2019-09-09 18:22:42 -06:00
|
|
|
tv, ok := c.pkg.GetTypesInfo().Types[sel.X]
|
2019-11-01 11:50:21 -06:00
|
|
|
if ok {
|
|
|
|
return c.methodsAndFields(tv.Type, tv.Addressable(), nil)
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
|
2019-11-01 11:50:21 -06:00
|
|
|
// Try unimported packages.
|
2019-12-23 11:19:17 -07:00
|
|
|
if id, ok := sel.X.(*ast.Ident); ok && c.opts.Unimported && len(c.items) < unimportedTarget {
|
2019-12-30 11:29:58 -07:00
|
|
|
if err := c.unimportedMembers(id); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *completer) unimportedMembers(id *ast.Ident) error {
|
|
|
|
// Try loaded packages first. They're relevant, fast, and fully typed.
|
|
|
|
known := c.snapshot.KnownImportPaths()
|
|
|
|
for path, pkg := range known {
|
|
|
|
if pkg.GetTypes().Name() != id.Name {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// We don't know what this is, so assign it the highest score.
|
|
|
|
score := 0.01 * imports.MaxRelevance
|
|
|
|
c.packageMembers(pkg.GetTypes(), score, &importInfo{
|
|
|
|
importPath: path,
|
|
|
|
name: pkg.GetTypes().Name(),
|
|
|
|
pkg: pkg,
|
|
|
|
})
|
|
|
|
if len(c.items) >= unimportedTarget {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx, cancel := c.deepCompletionContext()
|
|
|
|
defer cancel()
|
|
|
|
var mu sync.Mutex
|
|
|
|
add := func(pkgExport imports.PackageExport) {
|
|
|
|
mu.Lock()
|
|
|
|
defer mu.Unlock()
|
|
|
|
if _, ok := known[pkgExport.Fix.StmtInfo.ImportPath]; ok {
|
|
|
|
return // We got this one above.
|
|
|
|
}
|
|
|
|
|
|
|
|
// Continue with untyped proposals.
|
|
|
|
pkg := types.NewPackage(pkgExport.Fix.StmtInfo.ImportPath, pkgExport.Fix.IdentName)
|
|
|
|
for _, export := range pkgExport.Exports {
|
|
|
|
score := 0.01 * float64(pkgExport.Fix.Relevance)
|
|
|
|
c.found(candidate{
|
|
|
|
obj: types.NewVar(0, pkg, export, nil),
|
|
|
|
score: score,
|
|
|
|
imp: &importInfo{
|
2019-11-05 12:53:55 -07:00
|
|
|
importPath: pkgExport.Fix.StmtInfo.ImportPath,
|
|
|
|
name: pkgExport.Fix.StmtInfo.Name,
|
2019-12-30 11:29:58 -07:00
|
|
|
},
|
|
|
|
})
|
2019-11-01 11:50:21 -06:00
|
|
|
}
|
2019-12-30 11:29:58 -07:00
|
|
|
if len(c.items) >= unimportedTarget {
|
|
|
|
cancel()
|
2019-12-27 13:46:49 -07:00
|
|
|
}
|
2019-11-01 11:50:21 -06:00
|
|
|
}
|
2019-12-30 11:29:58 -07:00
|
|
|
return c.snapshot.View().RunProcessEnvFunc(ctx, func(opts *imports.Options) error {
|
2019-12-30 14:18:34 -07:00
|
|
|
return imports.GetPackageExports(ctx, add, id.Name, c.filename, c.pkg.GetTypes().Name(), opts)
|
2019-12-30 11:29:58 -07:00
|
|
|
})
|
2019-06-27 11:50:01 -06:00
|
|
|
}
|
|
|
|
|
2019-12-30 11:29:58 -07:00
|
|
|
func (c *completer) packageMembers(pkg *types.Package, score float64, imp *importInfo) {
|
2019-10-15 15:42:30 -06:00
|
|
|
scope := pkg.Scope()
|
2019-06-27 11:50:01 -06:00
|
|
|
for _, name := range scope.Names() {
|
2019-12-22 10:58:14 -07:00
|
|
|
obj := scope.Lookup(name)
|
2019-12-21 16:39:02 -07:00
|
|
|
c.found(candidate{
|
2019-12-22 10:58:14 -07:00
|
|
|
obj: obj,
|
2019-12-30 11:29:58 -07:00
|
|
|
score: score,
|
2019-12-22 10:58:14 -07:00
|
|
|
imp: imp,
|
|
|
|
addressable: isVar(obj),
|
2019-12-21 16:39:02 -07:00
|
|
|
})
|
2019-06-27 11:50:01 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-05 12:53:55 -07:00
|
|
|
func (c *completer) methodsAndFields(typ types.Type, addressable bool, imp *importInfo) error {
|
2019-08-16 10:45:09 -06:00
|
|
|
mset := c.methodSetCache[methodSetKey{typ, addressable}]
|
|
|
|
if mset == nil {
|
|
|
|
if addressable && !types.IsInterface(typ) && !isPointer(typ) {
|
|
|
|
// Add methods of *T, which includes methods with receiver T.
|
|
|
|
mset = types.NewMethodSet(types.NewPointer(typ))
|
|
|
|
} else {
|
|
|
|
// Add methods of T.
|
|
|
|
mset = types.NewMethodSet(typ)
|
|
|
|
}
|
|
|
|
c.methodSetCache[methodSetKey{typ, addressable}] = mset
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
|
2019-06-27 11:50:01 -06:00
|
|
|
for i := 0; i < mset.Len(); i++ {
|
2019-12-21 16:39:02 -07:00
|
|
|
c.found(candidate{
|
2019-12-22 10:58:14 -07:00
|
|
|
obj: mset.At(i).Obj(),
|
|
|
|
score: stdScore,
|
|
|
|
imp: imp,
|
|
|
|
addressable: addressable || isPointer(typ),
|
2019-12-21 16:39:02 -07:00
|
|
|
})
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
|
2019-04-24 17:26:34 -06:00
|
|
|
// Add fields of T.
|
2019-06-27 11:50:01 -06:00
|
|
|
for _, f := range fieldSelections(typ) {
|
2019-12-21 16:39:02 -07:00
|
|
|
c.found(candidate{
|
2019-12-22 10:58:14 -07:00
|
|
|
obj: f,
|
2019-12-27 13:45:09 -07:00
|
|
|
score: stdScore - 0.01,
|
2019-12-22 10:58:14 -07:00
|
|
|
imp: imp,
|
|
|
|
addressable: addressable || isPointer(typ),
|
2019-12-21 16:39:02 -07:00
|
|
|
})
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-04-24 17:26:34 -06:00
|
|
|
return nil
|
2019-01-31 23:40:03 -07:00
|
|
|
}
|
|
|
|
|
2018-11-07 18:57:08 -07:00
|
|
|
// lexical finds completions in the lexical environment.
|
2019-04-24 17:26:34 -06:00
|
|
|
func (c *completer) lexical() error {
|
2018-11-07 18:57:08 -07:00
|
|
|
var scopes []*types.Scope // scopes[i], where i<len(path), is the possibly nil Scope of path[i].
|
2019-04-24 17:26:34 -06:00
|
|
|
for _, n := range c.path {
|
2019-09-17 16:10:05 -06:00
|
|
|
// Include *FuncType scope if pos is inside the function body.
|
2018-11-07 18:57:08 -07:00
|
|
|
switch node := n.(type) {
|
|
|
|
case *ast.FuncDecl:
|
2019-09-17 16:10:05 -06:00
|
|
|
if node.Body != nil && nodeContains(node.Body, c.pos) {
|
|
|
|
n = node.Type
|
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
case *ast.FuncLit:
|
2019-09-17 16:10:05 -06:00
|
|
|
if node.Body != nil && nodeContains(node.Body, c.pos) {
|
|
|
|
n = node.Type
|
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-09-09 18:22:42 -06:00
|
|
|
scopes = append(scopes, c.pkg.GetTypesInfo().Scopes[n])
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-09-09 18:22:42 -06:00
|
|
|
scopes = append(scopes, c.pkg.GetTypes().Scope(), types.Universe)
|
2018-11-07 18:57:08 -07:00
|
|
|
|
2019-12-09 11:41:28 -07:00
|
|
|
var (
|
|
|
|
builtinIota = types.Universe.Lookup("iota")
|
|
|
|
builtinNil = types.Universe.Lookup("nil")
|
|
|
|
)
|
2019-09-12 14:21:36 -06:00
|
|
|
|
2019-04-25 15:19:24 -06:00
|
|
|
// Track seen variables to avoid showing completions for shadowed variables.
|
|
|
|
// This works since we look at scopes from innermost to outermost.
|
|
|
|
seen := make(map[string]struct{})
|
|
|
|
|
2018-11-07 18:57:08 -07:00
|
|
|
// Process scopes innermost first.
|
|
|
|
for i, scope := range scopes {
|
|
|
|
if scope == nil {
|
|
|
|
continue
|
|
|
|
}
|
2019-12-22 16:04:15 -07:00
|
|
|
|
|
|
|
Names:
|
2018-11-07 18:57:08 -07:00
|
|
|
for _, name := range scope.Names() {
|
2019-04-24 17:26:34 -06:00
|
|
|
declScope, obj := scope.LookupParent(name, c.pos)
|
2018-11-07 18:57:08 -07:00
|
|
|
if declScope != scope {
|
|
|
|
continue // Name was declared in some enclosing scope, or not at all.
|
|
|
|
}
|
2019-12-22 16:04:15 -07:00
|
|
|
|
2018-11-07 18:57:08 -07:00
|
|
|
// If obj's type is invalid, find the AST node that defines the lexical block
|
|
|
|
// containing the declaration of obj. Don't resolve types for packages.
|
2019-12-06 10:59:56 -07:00
|
|
|
if _, ok := obj.(*types.PkgName); !ok && !typeIsValid(obj.Type()) {
|
2018-11-07 18:57:08 -07:00
|
|
|
// Match the scope to its ast.Node. If the scope is the package scope,
|
|
|
|
// use the *ast.File as the starting node.
|
|
|
|
var node ast.Node
|
2019-04-24 17:26:34 -06:00
|
|
|
if i < len(c.path) {
|
|
|
|
node = c.path[i]
|
|
|
|
} else if i == len(c.path) { // use the *ast.File for package scope
|
|
|
|
node = c.path[i-1]
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
if node != nil {
|
2019-12-06 10:59:56 -07:00
|
|
|
fset := c.snapshot.View().Session().Cache().FileSet()
|
|
|
|
if resolved := resolveInvalid(fset, obj, node, c.pkg.GetTypesInfo()); resolved != nil {
|
2018-11-07 18:57:08 -07:00
|
|
|
obj = resolved
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-22 16:04:15 -07:00
|
|
|
// Don't use LHS of value spec in RHS.
|
|
|
|
if vs := enclosingValueSpec(c.path, c.pos); vs != nil {
|
|
|
|
for _, ident := range vs.Names {
|
|
|
|
if obj.Pos() == ident.Pos() {
|
|
|
|
continue Names
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-12 14:21:36 -06:00
|
|
|
// Don't suggest "iota" outside of const decls.
|
|
|
|
if obj == builtinIota && !c.inConstDecl() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-12-27 13:45:09 -07:00
|
|
|
// Rank outer scopes lower than inner.
|
|
|
|
score := stdScore * math.Pow(.99, float64(i))
|
2019-12-09 11:41:28 -07:00
|
|
|
|
|
|
|
// Dowrank "nil" a bit so it is ranked below more interesting candidates.
|
|
|
|
if obj == builtinNil {
|
|
|
|
score /= 2
|
|
|
|
}
|
|
|
|
|
2019-04-25 15:19:24 -06:00
|
|
|
// If we haven't already added a candidate for an object with this name.
|
|
|
|
if _, ok := seen[obj.Name()]; !ok {
|
|
|
|
seen[obj.Name()] = struct{}{}
|
2019-12-21 16:39:02 -07:00
|
|
|
c.found(candidate{
|
2019-12-22 10:58:14 -07:00
|
|
|
obj: obj,
|
|
|
|
score: score,
|
|
|
|
addressable: isVar(obj),
|
2019-12-21 16:39:02 -07:00
|
|
|
})
|
2019-08-14 15:25:47 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-15 15:42:30 -06:00
|
|
|
if c.expectedType.objType != nil {
|
|
|
|
if named, _ := deref(c.expectedType.objType).(*types.Named); named != nil {
|
|
|
|
// If we expected a named type, check the type's package for
|
|
|
|
// completion items. This is useful when the current file hasn't
|
|
|
|
// imported the type's package yet.
|
|
|
|
|
|
|
|
if named.Obj() != nil && named.Obj().Pkg() != nil {
|
|
|
|
pkg := named.Obj().Pkg()
|
|
|
|
|
|
|
|
// Make sure the package name isn't already in use by another
|
|
|
|
// object, and that this file doesn't import the package yet.
|
|
|
|
if _, ok := seen[pkg.Name()]; !ok && pkg != c.pkg.GetTypes() && !alreadyImports(c.file, pkg.Path()) {
|
|
|
|
seen[pkg.Name()] = struct{}{}
|
|
|
|
obj := types.NewPkgName(0, nil, pkg.Name(), pkg)
|
2019-11-13 15:03:07 -07:00
|
|
|
imp := &importInfo{
|
2019-11-05 12:53:55 -07:00
|
|
|
importPath: pkg.Path(),
|
2019-11-13 15:03:07 -07:00
|
|
|
}
|
|
|
|
if imports.ImportPathToAssumedName(pkg.Path()) != pkg.Name() {
|
|
|
|
imp.name = pkg.Name()
|
|
|
|
}
|
2019-12-21 16:39:02 -07:00
|
|
|
c.found(candidate{
|
|
|
|
obj: obj,
|
|
|
|
score: stdScore,
|
|
|
|
imp: imp,
|
|
|
|
})
|
2019-10-15 15:42:30 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-23 11:19:17 -07:00
|
|
|
if c.opts.Unimported && len(c.items) < unimportedTarget {
|
2019-12-27 13:46:49 -07:00
|
|
|
ctx, cancel := c.deepCompletionContext()
|
2019-12-26 17:13:58 -07:00
|
|
|
defer cancel()
|
2019-08-14 15:25:47 -06:00
|
|
|
// Suggest packages that have not been imported yet.
|
2019-12-26 17:13:58 -07:00
|
|
|
prefix := ""
|
|
|
|
if c.surrounding != nil {
|
|
|
|
prefix = c.surrounding.Prefix()
|
|
|
|
}
|
2019-12-27 13:46:49 -07:00
|
|
|
var mu sync.Mutex
|
|
|
|
add := func(pkg imports.ImportFix) {
|
|
|
|
mu.Lock()
|
|
|
|
defer mu.Unlock()
|
|
|
|
if _, ok := seen[pkg.IdentName]; ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Rank unimported packages significantly lower than other results.
|
|
|
|
score := 0.01 * float64(pkg.Relevance)
|
|
|
|
|
|
|
|
// Do not add the unimported packages to seen, since we can have
|
|
|
|
// multiple packages of the same name as completion suggestions, since
|
|
|
|
// only one will be chosen.
|
|
|
|
obj := types.NewPkgName(0, nil, pkg.IdentName, types.NewPackage(pkg.StmtInfo.ImportPath, pkg.IdentName))
|
|
|
|
c.found(candidate{
|
|
|
|
obj: obj,
|
|
|
|
score: score,
|
|
|
|
imp: &importInfo{
|
|
|
|
importPath: pkg.StmtInfo.ImportPath,
|
|
|
|
name: pkg.StmtInfo.Name,
|
|
|
|
},
|
|
|
|
})
|
2019-12-05 16:08:19 -07:00
|
|
|
|
2019-12-23 11:19:17 -07:00
|
|
|
if len(c.items) >= unimportedTarget {
|
2019-12-27 13:46:49 -07:00
|
|
|
cancel()
|
2019-04-25 15:19:24 -06:00
|
|
|
}
|
2019-12-27 13:46:49 -07:00
|
|
|
c.found(candidate{
|
|
|
|
obj: obj,
|
|
|
|
score: score,
|
|
|
|
imp: &importInfo{
|
|
|
|
importPath: pkg.StmtInfo.ImportPath,
|
|
|
|
name: pkg.StmtInfo.Name,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
if err := c.snapshot.View().RunProcessEnvFunc(ctx, func(opts *imports.Options) error {
|
2019-12-30 14:18:34 -07:00
|
|
|
return imports.GetAllCandidates(ctx, add, prefix, c.filename, c.pkg.GetTypes().Name(), opts)
|
2019-12-27 16:25:19 -07:00
|
|
|
}); err != nil {
|
2019-12-27 13:46:49 -07:00
|
|
|
return err
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
}
|
internal/lsp: add literal completion candidates
Add support for literal completion candidates such as "[]int{}" or
"make([]int, 0)". We support both named and unnamed types. I used the
existing type matching logic, so, for example, if the expected type is
an interface, we will suggest literal candidates that implement the
interface.
The literal candidates have a lower score than normal matching
candidates, so they shouldn't be disruptive in cases where you don't
want a literal candidate.
This commit adds support for slice, array, struct, map, and channel
literal candidates since they are pretty similar. Functions will be
supported in a subsequent commit.
I also added support for setting a snippet's final tab stop. This is
useful if you want the cursor to end up somewhere other than the
character after the snippet.
Change-Id: Id3b74260fff4d61703989b422267021b00cec005
Reviewed-on: https://go-review.googlesource.com/c/tools/+/193698
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-09-04 17:12:37 -06:00
|
|
|
|
|
|
|
if c.expectedType.objType != nil {
|
|
|
|
// If we have an expected type and it is _not_ a named type, see
|
2019-10-15 15:42:30 -06:00
|
|
|
// if an object literal makes a good candidate. For example, if
|
|
|
|
// our expected type is "[]int", this will add a candidate of
|
internal/lsp: add literal completion candidates
Add support for literal completion candidates such as "[]int{}" or
"make([]int, 0)". We support both named and unnamed types. I used the
existing type matching logic, so, for example, if the expected type is
an interface, we will suggest literal candidates that implement the
interface.
The literal candidates have a lower score than normal matching
candidates, so they shouldn't be disruptive in cases where you don't
want a literal candidate.
This commit adds support for slice, array, struct, map, and channel
literal candidates since they are pretty similar. Functions will be
supported in a subsequent commit.
I also added support for setting a snippet's final tab stop. This is
useful if you want the cursor to end up somewhere other than the
character after the snippet.
Change-Id: Id3b74260fff4d61703989b422267021b00cec005
Reviewed-on: https://go-review.googlesource.com/c/tools/+/193698
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-09-04 17:12:37 -06:00
|
|
|
// "[]int{}".
|
2019-09-05 13:04:13 -06:00
|
|
|
if _, named := deref(c.expectedType.objType).(*types.Named); !named {
|
2019-10-15 15:42:30 -06:00
|
|
|
c.literal(c.expectedType.objType, nil)
|
internal/lsp: add literal completion candidates
Add support for literal completion candidates such as "[]int{}" or
"make([]int, 0)". We support both named and unnamed types. I used the
existing type matching logic, so, for example, if the expected type is
an interface, we will suggest literal candidates that implement the
interface.
The literal candidates have a lower score than normal matching
candidates, so they shouldn't be disruptive in cases where you don't
want a literal candidate.
This commit adds support for slice, array, struct, map, and channel
literal candidates since they are pretty similar. Functions will be
supported in a subsequent commit.
I also added support for setting a snippet's final tab stop. This is
useful if you want the cursor to end up somewhere other than the
character after the snippet.
Change-Id: Id3b74260fff4d61703989b422267021b00cec005
Reviewed-on: https://go-review.googlesource.com/c/tools/+/193698
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-09-04 17:12:37 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-24 17:26:34 -06:00
|
|
|
return nil
|
2019-01-15 23:36:31 -07:00
|
|
|
}
|
|
|
|
|
2019-11-12 14:58:00 -07:00
|
|
|
// alreadyImports reports whether f has an import with the specified path.
|
|
|
|
func alreadyImports(f *ast.File, path string) bool {
|
|
|
|
for _, s := range f.Imports {
|
|
|
|
if importPath(s) == path {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// importPath returns the unquoted import path of s,
|
|
|
|
// or "" if the path is not properly quoted.
|
|
|
|
func importPath(s *ast.ImportSpec) string {
|
|
|
|
t, err := strconv.Unquote(s.Path.Value)
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return t
|
|
|
|
}
|
|
|
|
|
2019-09-17 16:10:05 -06:00
|
|
|
func nodeContains(n ast.Node, pos token.Pos) bool {
|
2019-11-20 12:15:53 -07:00
|
|
|
return n != nil && n.Pos() <= pos && pos <= n.End()
|
2019-09-17 16:10:05 -06:00
|
|
|
}
|
|
|
|
|
2019-09-12 14:21:36 -06:00
|
|
|
func (c *completer) inConstDecl() bool {
|
|
|
|
for _, n := range c.path {
|
|
|
|
if decl, ok := n.(*ast.GenDecl); ok && decl.Tok == token.CONST {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-05-13 15:37:08 -06:00
|
|
|
// structLiteralFieldName finds completions for struct field names inside a struct literal.
|
|
|
|
func (c *completer) structLiteralFieldName() error {
|
|
|
|
clInfo := c.enclosingCompositeLiteral
|
|
|
|
|
2018-11-07 18:57:08 -07:00
|
|
|
// Mark fields of the composite literal that have already been set,
|
|
|
|
// except for the current field.
|
|
|
|
addedFields := make(map[*types.Var]bool)
|
2019-05-13 15:37:08 -06:00
|
|
|
for _, el := range clInfo.cl.Elts {
|
2019-04-24 17:26:34 -06:00
|
|
|
if kvExpr, ok := el.(*ast.KeyValueExpr); ok {
|
2019-05-13 15:37:08 -06:00
|
|
|
if clInfo.kv == kvExpr {
|
2018-11-07 18:57:08 -07:00
|
|
|
continue
|
|
|
|
}
|
2019-04-24 17:26:34 -06:00
|
|
|
|
|
|
|
if key, ok := kvExpr.Key.(*ast.Ident); ok {
|
2019-09-09 18:22:42 -06:00
|
|
|
if used, ok := c.pkg.GetTypesInfo().Uses[key]; ok {
|
2018-11-07 18:57:08 -07:00
|
|
|
if usedVar, ok := used.(*types.Var); ok {
|
|
|
|
addedFields[usedVar] = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-05-13 15:37:08 -06:00
|
|
|
|
|
|
|
switch t := clInfo.clType.(type) {
|
|
|
|
case *types.Struct:
|
|
|
|
for i := 0; i < t.NumFields(); i++ {
|
|
|
|
field := t.Field(i)
|
|
|
|
if !addedFields[field] {
|
2019-12-21 16:39:02 -07:00
|
|
|
c.found(candidate{
|
|
|
|
obj: field,
|
|
|
|
score: highScore,
|
|
|
|
})
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-05-13 15:37:08 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add lexical completions if we aren't certain we are in the key part of a
|
|
|
|
// key-value pair.
|
|
|
|
if clInfo.maybeInFieldName {
|
2019-04-24 17:26:34 -06:00
|
|
|
return c.lexical()
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-05-13 15:37:08 -06:00
|
|
|
default:
|
|
|
|
return c.lexical()
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-05-13 15:37:08 -06:00
|
|
|
|
2019-04-24 17:26:34 -06:00
|
|
|
return nil
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
|
2019-05-13 15:37:08 -06:00
|
|
|
func (cl *compLitInfo) isStruct() bool {
|
|
|
|
_, ok := cl.clType.(*types.Struct)
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
|
|
|
// enclosingCompositeLiteral returns information about the composite literal enclosing the
|
|
|
|
// position.
|
|
|
|
func enclosingCompositeLiteral(path []ast.Node, pos token.Pos, info *types.Info) *compLitInfo {
|
2019-04-28 21:19:54 -06:00
|
|
|
for _, n := range path {
|
2019-04-23 16:00:40 -06:00
|
|
|
switch n := n.(type) {
|
|
|
|
case *ast.CompositeLit:
|
2019-04-24 17:26:34 -06:00
|
|
|
// The enclosing node will be a composite literal if the user has just
|
|
|
|
// opened the curly brace (e.g. &x{<>) or the completion request is triggered
|
|
|
|
// from an already completed composite literal expression (e.g. &x{foo: 1, <>})
|
|
|
|
//
|
|
|
|
// The position is not part of the composite literal unless it falls within the
|
|
|
|
// curly braces (e.g. "foo.Foo<>Struct{}").
|
2019-09-13 13:15:53 -06:00
|
|
|
if !(n.Lbrace < pos && pos <= n.Rbrace) {
|
|
|
|
// Keep searching since we may yet be inside a composite literal.
|
|
|
|
// For example "Foo{B: Ba<>{}}".
|
|
|
|
break
|
2019-05-13 15:37:08 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
tv, ok := info.Types[n]
|
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
clInfo := compLitInfo{
|
|
|
|
cl: n,
|
2019-08-28 21:53:48 -06:00
|
|
|
clType: deref(tv.Type).Underlying(),
|
2019-05-13 15:37:08 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
expr ast.Expr
|
|
|
|
hasKeys bool
|
|
|
|
)
|
|
|
|
for _, el := range n.Elts {
|
|
|
|
// Remember the expression that the position falls in, if any.
|
|
|
|
if el.Pos() <= pos && pos <= el.End() {
|
|
|
|
expr = el
|
|
|
|
}
|
|
|
|
|
|
|
|
if kv, ok := el.(*ast.KeyValueExpr); ok {
|
|
|
|
hasKeys = true
|
|
|
|
// If expr == el then we know the position falls in this expression,
|
|
|
|
// so also record kv as the enclosing *ast.KeyValueExpr.
|
|
|
|
if expr == el {
|
|
|
|
clInfo.kv = kv
|
|
|
|
break
|
|
|
|
}
|
2019-04-23 16:00:40 -06:00
|
|
|
}
|
|
|
|
}
|
2019-05-13 15:37:08 -06:00
|
|
|
|
|
|
|
if clInfo.kv != nil {
|
|
|
|
// If in a *ast.KeyValueExpr, we know we are in the key if the position
|
|
|
|
// is to the left of the colon (e.g. "Foo{F<>: V}".
|
|
|
|
clInfo.inKey = pos <= clInfo.kv.Colon
|
|
|
|
} else if hasKeys {
|
|
|
|
// If we aren't in a *ast.KeyValueExpr but the composite literal has
|
|
|
|
// other *ast.KeyValueExprs, we must be on the key side of a new
|
|
|
|
// *ast.KeyValueExpr (e.g. "Foo{F: V, <>}").
|
|
|
|
clInfo.inKey = true
|
|
|
|
} else {
|
|
|
|
switch clInfo.clType.(type) {
|
|
|
|
case *types.Struct:
|
|
|
|
if len(n.Elts) == 0 {
|
|
|
|
// If the struct literal is empty, next could be a struct field
|
|
|
|
// name or an expression (e.g. "Foo{<>}" could become "Foo{F:}"
|
|
|
|
// or "Foo{someVar}").
|
|
|
|
clInfo.maybeInFieldName = true
|
|
|
|
} else if len(n.Elts) == 1 {
|
|
|
|
// If there is one expression and the position is in that expression
|
|
|
|
// and the expression is an identifier, we may be writing a field
|
|
|
|
// name or an expression (e.g. "Foo{F<>}").
|
|
|
|
_, clInfo.maybeInFieldName = expr.(*ast.Ident)
|
|
|
|
}
|
|
|
|
case *types.Map:
|
|
|
|
// If we aren't in a *ast.KeyValueExpr we must be adding a new key
|
|
|
|
// to the map.
|
|
|
|
clInfo.inKey = true
|
|
|
|
}
|
2019-04-24 17:26:34 -06:00
|
|
|
}
|
2019-05-13 15:37:08 -06:00
|
|
|
|
|
|
|
return &clInfo
|
2019-05-10 10:26:15 -06:00
|
|
|
default:
|
|
|
|
if breaksExpectedTypeInference(n) {
|
2019-05-13 15:37:08 -06:00
|
|
|
return nil
|
2019-05-10 10:26:15 -06:00
|
|
|
}
|
2019-04-23 16:00:40 -06:00
|
|
|
}
|
|
|
|
}
|
2019-05-13 15:37:08 -06:00
|
|
|
|
|
|
|
return nil
|
2019-04-23 16:00:40 -06:00
|
|
|
}
|
|
|
|
|
2019-09-18 13:26:39 -06:00
|
|
|
// enclosingFunction returns the signature and body of the function
|
|
|
|
// enclosing the given position.
|
|
|
|
func enclosingFunction(path []ast.Node, pos token.Pos, info *types.Info) *funcInfo {
|
2018-11-07 18:57:08 -07:00
|
|
|
for _, node := range path {
|
|
|
|
switch t := node.(type) {
|
|
|
|
case *ast.FuncDecl:
|
|
|
|
if obj, ok := info.Defs[t.Name]; ok {
|
2019-09-18 13:26:39 -06:00
|
|
|
return &funcInfo{
|
|
|
|
sig: obj.Type().(*types.Signature),
|
|
|
|
body: t.Body,
|
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
case *ast.FuncLit:
|
|
|
|
if typ, ok := info.Types[t]; ok {
|
2019-09-18 13:26:39 -06:00
|
|
|
return &funcInfo{
|
|
|
|
sig: typ.Type.(*types.Signature),
|
|
|
|
body: t.Body,
|
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-05-13 15:37:08 -06:00
|
|
|
func (c *completer) expectedCompositeLiteralType() types.Type {
|
|
|
|
clInfo := c.enclosingCompositeLiteral
|
|
|
|
switch t := clInfo.clType.(type) {
|
2019-04-23 16:00:40 -06:00
|
|
|
case *types.Slice:
|
2019-05-13 15:37:08 -06:00
|
|
|
if clInfo.inKey {
|
|
|
|
return types.Typ[types.Int]
|
|
|
|
}
|
2019-04-23 16:00:40 -06:00
|
|
|
return t.Elem()
|
|
|
|
case *types.Array:
|
2019-05-13 15:37:08 -06:00
|
|
|
if clInfo.inKey {
|
|
|
|
return types.Typ[types.Int]
|
|
|
|
}
|
2019-04-23 16:00:40 -06:00
|
|
|
return t.Elem()
|
|
|
|
case *types.Map:
|
2019-05-13 15:37:08 -06:00
|
|
|
if clInfo.inKey {
|
2019-04-23 16:00:40 -06:00
|
|
|
return t.Key()
|
|
|
|
}
|
|
|
|
return t.Elem()
|
|
|
|
case *types.Struct:
|
2019-05-13 15:37:08 -06:00
|
|
|
// If we are completing a key (i.e. field name), there is no expected type.
|
|
|
|
if clInfo.inKey {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we are in a key-value pair, but not in the key, then we must be on the
|
|
|
|
// value side. The expected type of the value will be determined from the key.
|
|
|
|
if clInfo.kv != nil {
|
|
|
|
if key, ok := clInfo.kv.Key.(*ast.Ident); ok {
|
2019-04-23 16:00:40 -06:00
|
|
|
for i := 0; i < t.NumFields(); i++ {
|
2019-04-24 17:26:34 -06:00
|
|
|
if field := t.Field(i); field.Name() == key.Name {
|
2019-04-23 16:00:40 -06:00
|
|
|
return field.Type()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-05-13 15:37:08 -06:00
|
|
|
} else {
|
|
|
|
// If we aren't in a key-value pair and aren't in the key, we must be using
|
|
|
|
// implicit field names.
|
|
|
|
|
|
|
|
// The order of the literal fields must match the order in the struct definition.
|
|
|
|
// Find the element that the position belongs to and suggest that field's type.
|
|
|
|
if i := indexExprAtPos(c.pos, clInfo.cl.Elts); i < t.NumFields() {
|
|
|
|
return t.Field(i).Type()
|
2019-04-23 16:00:40 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-05-15 16:29:19 -06:00
|
|
|
// typeModifier represents an operator that changes the expected type.
|
2019-09-13 13:15:53 -06:00
|
|
|
type typeModifier struct {
|
|
|
|
mod typeMod
|
|
|
|
arrayLen int64
|
|
|
|
}
|
|
|
|
|
|
|
|
type typeMod int
|
2019-05-15 16:29:19 -06:00
|
|
|
|
|
|
|
const (
|
2019-12-22 10:58:14 -07:00
|
|
|
star typeMod = iota // pointer indirection for expressions, pointer indicator for types
|
|
|
|
address // address operator ("&")
|
|
|
|
chanRead // channel read operator ("<-")
|
|
|
|
slice // make a slice type ("[]" in "[]int")
|
|
|
|
array // make an array type ("[2]" in "[2]int")
|
2019-05-15 16:29:19 -06:00
|
|
|
)
|
|
|
|
|
2019-06-17 12:11:13 -06:00
|
|
|
// typeInference holds information we have inferred about a type that can be
|
|
|
|
// used at the current position.
|
|
|
|
type typeInference struct {
|
|
|
|
// objType is the desired type of an object used at the query position.
|
|
|
|
objType types.Type
|
|
|
|
|
internal/lsp: add literal completion candidates
Add support for literal completion candidates such as "[]int{}" or
"make([]int, 0)". We support both named and unnamed types. I used the
existing type matching logic, so, for example, if the expected type is
an interface, we will suggest literal candidates that implement the
interface.
The literal candidates have a lower score than normal matching
candidates, so they shouldn't be disruptive in cases where you don't
want a literal candidate.
This commit adds support for slice, array, struct, map, and channel
literal candidates since they are pretty similar. Functions will be
supported in a subsequent commit.
I also added support for setting a snippet's final tab stop. This is
useful if you want the cursor to end up somewhere other than the
character after the snippet.
Change-Id: Id3b74260fff4d61703989b422267021b00cec005
Reviewed-on: https://go-review.googlesource.com/c/tools/+/193698
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-09-04 17:12:37 -06:00
|
|
|
// variadic is true if objType is a slice type from an initial
|
|
|
|
// variadic param.
|
|
|
|
variadic bool
|
|
|
|
|
2019-09-13 13:15:53 -06:00
|
|
|
// modifiers are prefixes such as "*", "&" or "<-" that influence how
|
|
|
|
// a candidate type relates to the expected type.
|
|
|
|
modifiers []typeModifier
|
|
|
|
|
|
|
|
// convertibleTo is a type our candidate type must be convertible to.
|
|
|
|
convertibleTo types.Type
|
|
|
|
|
|
|
|
// typeName holds information about the expected type name at
|
|
|
|
// position, if any.
|
|
|
|
typeName typeNameInference
|
|
|
|
}
|
|
|
|
|
|
|
|
// typeNameInference holds information about the expected type name at
|
|
|
|
// position.
|
|
|
|
type typeNameInference struct {
|
2019-06-17 12:11:13 -06:00
|
|
|
// wantTypeName is true if we expect the name of a type.
|
|
|
|
wantTypeName bool
|
2019-06-19 10:12:57 -06:00
|
|
|
|
|
|
|
// modifiers are prefixes such as "*", "&" or "<-" that influence how
|
|
|
|
// a candidate type relates to the expected type.
|
|
|
|
modifiers []typeModifier
|
2019-06-26 16:30:01 -06:00
|
|
|
|
|
|
|
// assertableFrom is a type that must be assertable to our candidate type.
|
|
|
|
assertableFrom types.Type
|
2019-09-17 15:59:27 -06:00
|
|
|
|
|
|
|
// wantComparable is true if we want a comparable type.
|
|
|
|
wantComparable bool
|
2019-06-17 12:11:13 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
// expectedType returns information about the expected type for an expression at
|
|
|
|
// the query position.
|
2019-11-06 12:39:30 -07:00
|
|
|
func expectedType(c *completer) (inf typeInference) {
|
|
|
|
inf.typeName = expectTypeName(c)
|
2019-06-17 12:11:13 -06:00
|
|
|
|
2019-05-13 15:37:08 -06:00
|
|
|
if c.enclosingCompositeLiteral != nil {
|
2019-09-13 13:15:53 -06:00
|
|
|
inf.objType = c.expectedCompositeLiteralType()
|
|
|
|
return inf
|
2019-05-13 15:37:08 -06:00
|
|
|
}
|
|
|
|
|
2019-05-10 10:26:15 -06:00
|
|
|
Nodes:
|
2019-05-15 16:29:19 -06:00
|
|
|
for i, node := range c.path {
|
|
|
|
switch node := node.(type) {
|
2018-11-07 18:57:08 -07:00
|
|
|
case *ast.BinaryExpr:
|
|
|
|
// Determine if query position comes from left or right of op.
|
2019-05-15 16:29:19 -06:00
|
|
|
e := node.X
|
|
|
|
if c.pos < node.OpPos {
|
|
|
|
e = node.Y
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-09-09 18:22:42 -06:00
|
|
|
if tv, ok := c.pkg.GetTypesInfo().Types[e]; ok {
|
2019-09-13 13:15:53 -06:00
|
|
|
inf.objType = tv.Type
|
2019-05-10 10:26:15 -06:00
|
|
|
break Nodes
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
case *ast.AssignStmt:
|
|
|
|
// Only rank completions if you are on the right side of the token.
|
2019-05-15 16:29:19 -06:00
|
|
|
if c.pos > node.TokPos {
|
|
|
|
i := indexExprAtPos(c.pos, node.Rhs)
|
|
|
|
if i >= len(node.Lhs) {
|
|
|
|
i = len(node.Lhs) - 1
|
2019-05-10 10:26:15 -06:00
|
|
|
}
|
2019-09-09 18:22:42 -06:00
|
|
|
if tv, ok := c.pkg.GetTypesInfo().Types[node.Lhs[i]]; ok {
|
2019-09-13 13:15:53 -06:00
|
|
|
inf.objType = tv.Type
|
2019-05-10 10:26:15 -06:00
|
|
|
break Nodes
|
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-09-13 13:15:53 -06:00
|
|
|
return inf
|
2019-12-22 16:04:15 -07:00
|
|
|
case *ast.ValueSpec:
|
|
|
|
if node.Type != nil && c.pos > node.Type.End() {
|
|
|
|
inf.objType = c.pkg.GetTypesInfo().TypeOf(node.Type)
|
|
|
|
}
|
|
|
|
break Nodes
|
2018-11-07 18:57:08 -07:00
|
|
|
case *ast.CallExpr:
|
2019-05-10 10:26:15 -06:00
|
|
|
// Only consider CallExpr args if position falls between parens.
|
2019-05-15 16:29:19 -06:00
|
|
|
if node.Lparen <= c.pos && c.pos <= node.Rparen {
|
2019-06-27 16:37:50 -06:00
|
|
|
// For type conversions like "int64(foo)" we can only infer our
|
|
|
|
// desired type is convertible to int64.
|
2019-09-09 18:22:42 -06:00
|
|
|
if typ := typeConversion(node, c.pkg.GetTypesInfo()); typ != nil {
|
2019-09-13 13:15:53 -06:00
|
|
|
inf.convertibleTo = typ
|
2019-06-27 16:37:50 -06:00
|
|
|
break Nodes
|
|
|
|
}
|
|
|
|
|
2019-09-09 18:22:42 -06:00
|
|
|
if tv, ok := c.pkg.GetTypesInfo().Types[node.Fun]; ok {
|
2019-05-10 10:26:15 -06:00
|
|
|
if sig, ok := tv.Type.(*types.Signature); ok {
|
2019-11-03 16:57:27 -07:00
|
|
|
numParams := sig.Params().Len()
|
|
|
|
if numParams == 0 {
|
2019-09-13 13:15:53 -06:00
|
|
|
return inf
|
2019-05-10 10:26:15 -06:00
|
|
|
}
|
2019-11-03 16:57:27 -07:00
|
|
|
|
|
|
|
var (
|
|
|
|
exprIdx = indexExprAtPos(c.pos, node.Args)
|
|
|
|
isLastParam = exprIdx == numParams-1
|
|
|
|
beyondLastParam = exprIdx >= numParams
|
|
|
|
)
|
|
|
|
|
|
|
|
if sig.Variadic() {
|
|
|
|
// If we are beyond the last param or we are the last
|
|
|
|
// param w/ further expressions, we expect a single
|
|
|
|
// variadic item.
|
|
|
|
if beyondLastParam || isLastParam && len(node.Args) > numParams {
|
|
|
|
inf.objType = sig.Params().At(numParams - 1).Type().(*types.Slice).Elem()
|
|
|
|
break Nodes
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise if we are at the last param then we are
|
|
|
|
// completing the variadic positition (i.e. we expect a
|
|
|
|
// slice type []T or an individual item T).
|
|
|
|
if isLastParam {
|
|
|
|
inf.variadic = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-10 10:26:15 -06:00
|
|
|
// Make sure not to run past the end of expected parameters.
|
2019-11-03 16:57:27 -07:00
|
|
|
if beyondLastParam {
|
|
|
|
inf.objType = sig.Params().At(numParams - 1).Type()
|
|
|
|
} else {
|
|
|
|
inf.objType = sig.Params().At(exprIdx).Type()
|
2019-05-10 10:26:15 -06:00
|
|
|
}
|
2019-11-03 16:57:27 -07:00
|
|
|
|
2019-05-10 10:26:15 -06:00
|
|
|
break Nodes
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-05-10 10:26:15 -06:00
|
|
|
}
|
2019-11-06 12:39:30 -07:00
|
|
|
|
|
|
|
if funIdent, ok := node.Fun.(*ast.Ident); ok {
|
|
|
|
switch c.pkg.GetTypesInfo().ObjectOf(funIdent) {
|
|
|
|
case types.Universe.Lookup("append"):
|
|
|
|
defer func() {
|
|
|
|
exprIdx := indexExprAtPos(c.pos, node.Args)
|
|
|
|
|
|
|
|
// Check if we are completing the variadic append()
|
|
|
|
// param. We defer this since we don't want to inherit
|
|
|
|
// variadicity from the next node.
|
|
|
|
inf.variadic = exprIdx == 1 && len(node.Args) <= 2
|
|
|
|
|
|
|
|
// If we are completing an individual element of the
|
|
|
|
// variadic param, "deslice" the expected type.
|
|
|
|
if !inf.variadic && exprIdx > 0 {
|
|
|
|
if slice, ok := inf.objType.(*types.Slice); ok {
|
|
|
|
inf.objType = slice.Elem()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
// The expected type of append() arguments is the expected
|
|
|
|
// type of the append() call itself. For example:
|
|
|
|
//
|
|
|
|
// var foo []int
|
|
|
|
// foo = append(<>)
|
|
|
|
//
|
|
|
|
// To find the expected type at <> we "skip" the append()
|
|
|
|
// node and get the expected type one level up, which is
|
|
|
|
// []int.
|
|
|
|
continue Nodes
|
|
|
|
}
|
|
|
|
}
|
2019-05-10 10:26:15 -06:00
|
|
|
}
|
2019-09-13 13:15:53 -06:00
|
|
|
return inf
|
2019-05-10 10:26:15 -06:00
|
|
|
case *ast.ReturnStmt:
|
2019-09-18 13:26:39 -06:00
|
|
|
if c.enclosingFunc != nil {
|
|
|
|
sig := c.enclosingFunc.sig
|
2019-05-15 16:29:19 -06:00
|
|
|
// Find signature result that corresponds to our return statement.
|
|
|
|
if resultIdx := indexExprAtPos(c.pos, node.Results); resultIdx < len(node.Results) {
|
2019-05-10 10:26:15 -06:00
|
|
|
if resultIdx < sig.Results().Len() {
|
2019-09-13 13:15:53 -06:00
|
|
|
inf.objType = sig.Results().At(resultIdx).Type()
|
2019-05-10 10:26:15 -06:00
|
|
|
break Nodes
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-09-13 13:15:53 -06:00
|
|
|
return inf
|
2019-05-15 16:29:19 -06:00
|
|
|
case *ast.CaseClause:
|
|
|
|
if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, node).(*ast.SwitchStmt); ok {
|
2019-09-09 18:22:42 -06:00
|
|
|
if tv, ok := c.pkg.GetTypesInfo().Types[swtch.Tag]; ok {
|
2019-09-13 13:15:53 -06:00
|
|
|
inf.objType = tv.Type
|
2019-05-15 16:29:19 -06:00
|
|
|
break Nodes
|
|
|
|
}
|
|
|
|
}
|
2019-09-13 13:15:53 -06:00
|
|
|
return inf
|
2019-05-15 16:29:19 -06:00
|
|
|
case *ast.SliceExpr:
|
|
|
|
// Make sure position falls within the brackets (e.g. "foo[a:<>]").
|
|
|
|
if node.Lbrack < c.pos && c.pos <= node.Rbrack {
|
2019-09-13 13:15:53 -06:00
|
|
|
inf.objType = types.Typ[types.Int]
|
2019-05-15 16:29:19 -06:00
|
|
|
break Nodes
|
|
|
|
}
|
2019-09-13 13:15:53 -06:00
|
|
|
return inf
|
2019-05-15 16:29:19 -06:00
|
|
|
case *ast.IndexExpr:
|
|
|
|
// Make sure position falls within the brackets (e.g. "foo[<>]").
|
|
|
|
if node.Lbrack < c.pos && c.pos <= node.Rbrack {
|
2019-09-09 18:22:42 -06:00
|
|
|
if tv, ok := c.pkg.GetTypesInfo().Types[node.X]; ok {
|
2019-05-15 16:29:19 -06:00
|
|
|
switch t := tv.Type.Underlying().(type) {
|
|
|
|
case *types.Map:
|
2019-09-13 13:15:53 -06:00
|
|
|
inf.objType = t.Key()
|
2019-05-15 16:29:19 -06:00
|
|
|
case *types.Slice, *types.Array:
|
2019-09-13 13:15:53 -06:00
|
|
|
inf.objType = types.Typ[types.Int]
|
2019-05-15 16:29:19 -06:00
|
|
|
default:
|
2019-09-13 13:15:53 -06:00
|
|
|
return inf
|
2019-05-15 16:29:19 -06:00
|
|
|
}
|
|
|
|
break Nodes
|
|
|
|
}
|
|
|
|
}
|
2019-09-13 13:15:53 -06:00
|
|
|
return inf
|
2019-05-15 16:29:19 -06:00
|
|
|
case *ast.SendStmt:
|
|
|
|
// Make sure we are on right side of arrow (e.g. "foo <- <>").
|
|
|
|
if c.pos > node.Arrow+1 {
|
2019-09-09 18:22:42 -06:00
|
|
|
if tv, ok := c.pkg.GetTypesInfo().Types[node.Chan]; ok {
|
2019-05-15 16:29:19 -06:00
|
|
|
if ch, ok := tv.Type.Underlying().(*types.Chan); ok {
|
2019-09-13 13:15:53 -06:00
|
|
|
inf.objType = ch.Elem()
|
2019-05-15 16:29:19 -06:00
|
|
|
break Nodes
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-09-13 13:15:53 -06:00
|
|
|
return inf
|
2019-05-10 10:26:15 -06:00
|
|
|
case *ast.StarExpr:
|
2019-09-13 13:15:53 -06:00
|
|
|
inf.modifiers = append(inf.modifiers, typeModifier{mod: star})
|
2019-05-10 10:26:15 -06:00
|
|
|
case *ast.UnaryExpr:
|
2019-05-15 16:29:19 -06:00
|
|
|
switch node.Op {
|
|
|
|
case token.AND:
|
2019-12-22 10:58:14 -07:00
|
|
|
inf.modifiers = append(inf.modifiers, typeModifier{mod: address})
|
2019-05-15 16:29:19 -06:00
|
|
|
case token.ARROW:
|
2019-09-13 13:15:53 -06:00
|
|
|
inf.modifiers = append(inf.modifiers, typeModifier{mod: chanRead})
|
2019-05-10 10:26:15 -06:00
|
|
|
}
|
|
|
|
default:
|
|
|
|
if breaksExpectedTypeInference(node) {
|
2019-09-13 13:15:53 -06:00
|
|
|
return inf
|
2019-05-10 10:26:15 -06:00
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
}
|
2019-05-10 10:26:15 -06:00
|
|
|
|
2019-09-13 13:15:53 -06:00
|
|
|
return inf
|
2019-06-19 10:12:57 -06:00
|
|
|
}
|
2019-05-10 10:26:15 -06:00
|
|
|
|
2019-06-19 10:12:57 -06:00
|
|
|
// applyTypeModifiers applies the list of type modifiers to a type.
|
2019-12-22 10:58:14 -07:00
|
|
|
// It returns nil if the modifiers could not be applied.
|
|
|
|
func (ti typeInference) applyTypeModifiers(typ types.Type, addressable bool) types.Type {
|
2019-06-19 10:12:57 -06:00
|
|
|
for _, mod := range ti.modifiers {
|
2019-09-13 13:15:53 -06:00
|
|
|
switch mod.mod {
|
2019-06-26 16:30:01 -06:00
|
|
|
case star:
|
2019-12-22 10:58:14 -07:00
|
|
|
// For every "*" indirection operator, remove a pointer layer
|
|
|
|
// from candidate type.
|
|
|
|
if ptr, ok := typ.Underlying().(*types.Pointer); ok {
|
|
|
|
typ = ptr.Elem()
|
|
|
|
} else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
case address:
|
|
|
|
// For every "&" address operator, add another pointer layer to
|
|
|
|
// candidate type, if the candidate is addressable.
|
|
|
|
if addressable {
|
|
|
|
typ = types.NewPointer(typ)
|
|
|
|
} else {
|
|
|
|
return nil
|
|
|
|
}
|
2019-06-19 10:12:57 -06:00
|
|
|
case chanRead:
|
|
|
|
// For every "<-" operator, remove a layer of channelness.
|
|
|
|
if ch, ok := typ.(*types.Chan); ok {
|
|
|
|
typ = ch.Elem()
|
2019-12-22 10:58:14 -07:00
|
|
|
} else {
|
|
|
|
return nil
|
2019-06-19 10:12:57 -06:00
|
|
|
}
|
|
|
|
}
|
2019-06-17 12:11:13 -06:00
|
|
|
}
|
2019-12-22 10:58:14 -07:00
|
|
|
|
2019-06-19 10:12:57 -06:00
|
|
|
return typ
|
2019-05-10 10:26:15 -06:00
|
|
|
}
|
|
|
|
|
2019-06-26 16:30:01 -06:00
|
|
|
// applyTypeNameModifiers applies the list of type modifiers to a type name.
|
|
|
|
func (ti typeInference) applyTypeNameModifiers(typ types.Type) types.Type {
|
2019-09-13 13:15:53 -06:00
|
|
|
for _, mod := range ti.typeName.modifiers {
|
|
|
|
switch mod.mod {
|
2019-06-26 16:30:01 -06:00
|
|
|
case star:
|
|
|
|
// For every "*" indicator, add a pointer layer to type name.
|
|
|
|
typ = types.NewPointer(typ)
|
2019-09-13 13:15:53 -06:00
|
|
|
case array:
|
|
|
|
typ = types.NewArray(typ, mod.arrayLen)
|
|
|
|
case slice:
|
|
|
|
typ = types.NewSlice(typ)
|
2019-06-26 16:30:01 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return typ
|
|
|
|
}
|
|
|
|
|
2019-11-03 16:57:27 -07:00
|
|
|
// matchesVariadic returns true if we are completing a variadic
|
|
|
|
// parameter and candType is a compatible slice type.
|
|
|
|
func (ti typeInference) matchesVariadic(candType types.Type) bool {
|
|
|
|
return ti.variadic && types.AssignableTo(ti.objType, candType)
|
|
|
|
}
|
|
|
|
|
2019-05-15 16:29:19 -06:00
|
|
|
// findSwitchStmt returns an *ast.CaseClause's corresponding *ast.SwitchStmt or
|
|
|
|
// *ast.TypeSwitchStmt. path should start from the case clause's first ancestor.
|
|
|
|
func findSwitchStmt(path []ast.Node, pos token.Pos, c *ast.CaseClause) ast.Stmt {
|
|
|
|
// Make sure position falls within a "case <>:" clause.
|
|
|
|
if exprAtPos(pos, c.List) == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
// A case clause is always nested within a block statement in a switch statement.
|
|
|
|
if len(path) < 2 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if _, ok := path[0].(*ast.BlockStmt); !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
switch s := path[1].(type) {
|
|
|
|
case *ast.SwitchStmt:
|
|
|
|
return s
|
|
|
|
case *ast.TypeSwitchStmt:
|
|
|
|
return s
|
|
|
|
default:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-10 10:26:15 -06:00
|
|
|
// breaksExpectedTypeInference reports if an expression node's type is unrelated
|
|
|
|
// to its child expression node types. For example, "Foo{Bar: x.Baz(<>)}" should
|
|
|
|
// expect a function argument, not a composite literal value.
|
|
|
|
func breaksExpectedTypeInference(n ast.Node) bool {
|
|
|
|
switch n.(type) {
|
|
|
|
case *ast.FuncLit, *ast.CallExpr, *ast.TypeAssertExpr, *ast.IndexExpr, *ast.SliceExpr, *ast.CompositeLit:
|
|
|
|
return true
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
|
2019-06-17 12:11:13 -06:00
|
|
|
// expectTypeName returns information about the expected type name at position.
|
2019-09-13 13:15:53 -06:00
|
|
|
func expectTypeName(c *completer) typeNameInference {
|
2019-06-26 16:30:01 -06:00
|
|
|
var (
|
|
|
|
wantTypeName bool
|
2019-09-17 15:59:27 -06:00
|
|
|
wantComparable bool
|
2019-06-26 16:30:01 -06:00
|
|
|
modifiers []typeModifier
|
|
|
|
assertableFrom types.Type
|
|
|
|
)
|
2019-06-17 12:11:13 -06:00
|
|
|
|
|
|
|
Nodes:
|
|
|
|
for i, p := range c.path {
|
2019-04-24 17:26:34 -06:00
|
|
|
switch n := p.(type) {
|
2019-09-17 16:52:19 -06:00
|
|
|
case *ast.FieldList:
|
|
|
|
// Expect a type name if pos is in a FieldList. This applies to
|
|
|
|
// FuncType params/results, FuncDecl receiver, StructType, and
|
|
|
|
// InterfaceType. We don't need to worry about the field name
|
|
|
|
// because completion bails out early if pos is in an *ast.Ident
|
|
|
|
// that defines an object.
|
|
|
|
wantTypeName = true
|
|
|
|
break Nodes
|
2019-05-15 16:29:19 -06:00
|
|
|
case *ast.CaseClause:
|
2019-06-17 12:11:13 -06:00
|
|
|
// Expect type names in type switch case clauses.
|
2019-06-26 16:30:01 -06:00
|
|
|
if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, n).(*ast.TypeSwitchStmt); ok {
|
|
|
|
// The case clause types must be assertable from the type switch parameter.
|
|
|
|
ast.Inspect(swtch.Assign, func(n ast.Node) bool {
|
|
|
|
if ta, ok := n.(*ast.TypeAssertExpr); ok {
|
2019-09-09 18:22:42 -06:00
|
|
|
assertableFrom = c.pkg.GetTypesInfo().TypeOf(ta.X)
|
2019-06-26 16:30:01 -06:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
})
|
2019-06-17 12:11:13 -06:00
|
|
|
wantTypeName = true
|
|
|
|
break Nodes
|
|
|
|
}
|
2019-09-13 13:15:53 -06:00
|
|
|
return typeNameInference{}
|
2019-05-15 16:29:19 -06:00
|
|
|
case *ast.TypeAssertExpr:
|
2019-06-17 12:11:13 -06:00
|
|
|
// Expect type names in type assert expressions.
|
|
|
|
if n.Lparen < c.pos && c.pos <= n.Rparen {
|
2019-06-26 16:30:01 -06:00
|
|
|
// The type in parens must be assertable from the expression type.
|
2019-09-09 18:22:42 -06:00
|
|
|
assertableFrom = c.pkg.GetTypesInfo().TypeOf(n.X)
|
2019-06-17 12:11:13 -06:00
|
|
|
wantTypeName = true
|
|
|
|
break Nodes
|
|
|
|
}
|
2019-09-13 13:15:53 -06:00
|
|
|
return typeNameInference{}
|
2019-06-26 16:30:01 -06:00
|
|
|
case *ast.StarExpr:
|
2019-09-13 13:15:53 -06:00
|
|
|
modifiers = append(modifiers, typeModifier{mod: star})
|
|
|
|
case *ast.CompositeLit:
|
|
|
|
// We want a type name if position is in the "Type" part of a
|
|
|
|
// composite literal (e.g. "Foo<>{}").
|
|
|
|
if n.Type != nil && n.Type.Pos() <= c.pos && c.pos <= n.Type.End() {
|
|
|
|
wantTypeName = true
|
|
|
|
}
|
|
|
|
break Nodes
|
|
|
|
case *ast.ArrayType:
|
|
|
|
// If we are inside the "Elt" part of an array type, we want a type name.
|
|
|
|
if n.Elt.Pos() <= c.pos && c.pos <= n.Elt.End() {
|
|
|
|
wantTypeName = true
|
|
|
|
if n.Len == nil {
|
|
|
|
// No "Len" expression means a slice type.
|
|
|
|
modifiers = append(modifiers, typeModifier{mod: slice})
|
|
|
|
} else {
|
|
|
|
// Try to get the array type using the constant value of "Len".
|
|
|
|
tv, ok := c.pkg.GetTypesInfo().Types[n.Len]
|
|
|
|
if ok && tv.Value != nil && tv.Value.Kind() == constant.Int {
|
|
|
|
if arrayLen, ok := constant.Int64Val(tv.Value); ok {
|
|
|
|
modifiers = append(modifiers, typeModifier{mod: array, arrayLen: arrayLen})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ArrayTypes can be nested, so keep going if our parent is an
|
|
|
|
// ArrayType.
|
|
|
|
if i < len(c.path)-1 {
|
|
|
|
if _, ok := c.path[i+1].(*ast.ArrayType); ok {
|
|
|
|
continue Nodes
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
break Nodes
|
|
|
|
}
|
2019-09-17 15:59:27 -06:00
|
|
|
case *ast.MapType:
|
|
|
|
wantTypeName = true
|
|
|
|
if n.Key != nil {
|
|
|
|
wantComparable = n.Key.Pos() <= c.pos && c.pos <= n.Key.End()
|
|
|
|
} else {
|
|
|
|
// If the key is empty, assume we are completing the key if
|
|
|
|
// pos is directly after the "map[".
|
|
|
|
wantComparable = c.pos == n.Pos()+token.Pos(len("map["))
|
|
|
|
}
|
|
|
|
break Nodes
|
2019-06-17 12:11:13 -06:00
|
|
|
default:
|
|
|
|
if breaksExpectedTypeInference(p) {
|
2019-09-13 13:15:53 -06:00
|
|
|
return typeNameInference{}
|
2019-05-15 16:29:19 -06:00
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-13 13:15:53 -06:00
|
|
|
return typeNameInference{
|
2019-06-26 16:30:01 -06:00
|
|
|
wantTypeName: wantTypeName,
|
2019-09-17 15:59:27 -06:00
|
|
|
wantComparable: wantComparable,
|
2019-06-26 16:30:01 -06:00
|
|
|
modifiers: modifiers,
|
|
|
|
assertableFrom: assertableFrom,
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-06-17 12:11:13 -06:00
|
|
|
}
|
|
|
|
|
2019-12-22 10:58:14 -07:00
|
|
|
func (c *completer) fakeObj(T types.Type) *types.Var {
|
|
|
|
return types.NewVar(token.NoPos, c.pkg.GetTypes(), "", T)
|
internal/lsp: add literal completion candidates
Add support for literal completion candidates such as "[]int{}" or
"make([]int, 0)". We support both named and unnamed types. I used the
existing type matching logic, so, for example, if the expected type is
an interface, we will suggest literal candidates that implement the
interface.
The literal candidates have a lower score than normal matching
candidates, so they shouldn't be disruptive in cases where you don't
want a literal candidate.
This commit adds support for slice, array, struct, map, and channel
literal candidates since they are pretty similar. Functions will be
supported in a subsequent commit.
I also added support for setting a snippet's final tab stop. This is
useful if you want the cursor to end up somewhere other than the
character after the snippet.
Change-Id: Id3b74260fff4d61703989b422267021b00cec005
Reviewed-on: https://go-review.googlesource.com/c/tools/+/193698
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-09-04 17:12:37 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
// matchingCandidate reports whether a candidate matches our type
|
|
|
|
// inferences.
|
|
|
|
func (c *completer) matchingCandidate(cand *candidate) bool {
|
2019-06-26 16:30:01 -06:00
|
|
|
if isTypeName(cand.obj) {
|
|
|
|
return c.matchingTypeName(cand)
|
2019-09-13 13:15:53 -06:00
|
|
|
} else if c.wantTypeName() {
|
|
|
|
// If we want a type, a non-type object never matches.
|
|
|
|
return false
|
2019-06-26 16:30:01 -06:00
|
|
|
}
|
|
|
|
|
2019-11-15 17:14:15 -07:00
|
|
|
candType := cand.obj.Type()
|
|
|
|
if candType == nil {
|
2019-11-01 11:50:21 -06:00
|
|
|
return true
|
|
|
|
}
|
2019-06-19 16:24:05 -06:00
|
|
|
|
|
|
|
// Default to invoking *types.Func candidates. This is so function
|
|
|
|
// completions in an empty statement (or other cases with no expected type)
|
|
|
|
// are invoked by default.
|
|
|
|
cand.expandFuncCall = isFunc(cand.obj)
|
|
|
|
|
2019-11-15 17:14:15 -07:00
|
|
|
typeMatches := func(expType, candType types.Type) bool {
|
|
|
|
if expType == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-06-19 16:24:05 -06:00
|
|
|
// Take into account any type modifiers on the expected type.
|
2019-12-22 10:58:14 -07:00
|
|
|
candType = c.expectedType.applyTypeModifiers(candType, cand.addressable)
|
|
|
|
if candType == nil {
|
|
|
|
return false
|
|
|
|
}
|
2019-06-19 16:24:05 -06:00
|
|
|
|
2019-11-15 17:14:15 -07:00
|
|
|
// Handle untyped values specially since AssignableTo gives false negatives
|
|
|
|
// for them (see https://golang.org/issue/32146).
|
|
|
|
if candBasic, ok := candType.Underlying().(*types.Basic); ok {
|
|
|
|
if wantBasic, ok := expType.Underlying().(*types.Basic); ok {
|
|
|
|
// Make sure at least one of them is untyped.
|
|
|
|
if isUntyped(candType) || isUntyped(expType) {
|
2019-07-01 15:28:46 -06:00
|
|
|
// Check that their constant kind (bool|int|float|complex|string) matches.
|
|
|
|
// This doesn't take into account the constant value, so there will be some
|
|
|
|
// false positives due to integer sign and overflow.
|
2019-10-22 22:50:40 -06:00
|
|
|
if candBasic.Info()&types.IsConstType == wantBasic.Info()&types.IsConstType {
|
2020-01-02 14:26:21 -07:00
|
|
|
// Lower candidate score if the types are not identical. This avoids
|
|
|
|
// ranking untyped constants above candidates with an exact type
|
|
|
|
// match. Don't lower score of builtin constants (e.g. "true").
|
|
|
|
if !types.Identical(candType, expType) && cand.obj.Parent() != types.Universe {
|
2019-10-22 22:50:40 -06:00
|
|
|
cand.score /= 2
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
2019-07-01 15:28:46 -06:00
|
|
|
}
|
|
|
|
}
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-06-19 16:24:05 -06:00
|
|
|
|
2019-11-15 17:14:15 -07:00
|
|
|
// AssignableTo covers the case where the types are equal, but also handles
|
|
|
|
// cases like assigning a concrete type to an interface type.
|
|
|
|
return types.AssignableTo(candType, expType)
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-06-17 12:11:13 -06:00
|
|
|
|
2019-11-15 17:14:15 -07:00
|
|
|
if typeMatches(c.expectedType.objType, candType) {
|
2019-06-19 16:24:05 -06:00
|
|
|
// If obj's type matches, we don't want to expand to an invocation of obj.
|
|
|
|
cand.expandFuncCall = false
|
|
|
|
return true
|
|
|
|
}
|
2019-06-19 10:12:57 -06:00
|
|
|
|
2019-06-19 16:24:05 -06:00
|
|
|
// Try using a function's return type as its type.
|
2019-11-15 17:14:15 -07:00
|
|
|
if sig, ok := candType.Underlying().(*types.Signature); ok && sig.Results().Len() == 1 {
|
|
|
|
if typeMatches(c.expectedType.objType, sig.Results().At(0).Type()) {
|
2019-06-19 16:24:05 -06:00
|
|
|
// If obj's return value matches the expected type, we need to invoke obj
|
|
|
|
// in the completion.
|
|
|
|
cand.expandFuncCall = true
|
|
|
|
return true
|
|
|
|
}
|
2019-06-17 12:11:13 -06:00
|
|
|
}
|
|
|
|
|
2019-11-15 17:14:15 -07:00
|
|
|
// When completing the variadic parameter, if the expected type is
|
|
|
|
// []T then check candType against T.
|
|
|
|
if c.expectedType.variadic {
|
|
|
|
if slice, ok := c.expectedType.objType.(*types.Slice); ok && typeMatches(slice.Elem(), candType) {
|
|
|
|
return true
|
|
|
|
}
|
2019-11-03 16:57:27 -07:00
|
|
|
}
|
|
|
|
|
2019-12-22 10:58:14 -07:00
|
|
|
if c.expectedType.convertibleTo != nil && types.ConvertibleTo(candType, c.expectedType.convertibleTo) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if cand is addressable and a pointer to cand matches our type inference.
|
|
|
|
if cand.addressable && c.matchingCandidate(&candidate{obj: c.fakeObj(types.NewPointer(candType))}) {
|
|
|
|
// Mark the candidate so we know to prepend "&" when formatting.
|
|
|
|
cand.takeAddress = true
|
|
|
|
return true
|
2019-06-27 16:37:50 -06:00
|
|
|
}
|
|
|
|
|
2019-06-17 12:11:13 -06:00
|
|
|
return false
|
2018-11-07 18:57:08 -07:00
|
|
|
}
|
2019-06-26 16:30:01 -06:00
|
|
|
|
|
|
|
func (c *completer) matchingTypeName(cand *candidate) bool {
|
|
|
|
if !c.wantTypeName() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Take into account any type name modifier prefixes.
|
|
|
|
actual := c.expectedType.applyTypeNameModifiers(cand.obj.Type())
|
|
|
|
|
2019-09-13 13:15:53 -06:00
|
|
|
if c.expectedType.typeName.assertableFrom != nil {
|
2019-06-26 16:30:01 -06:00
|
|
|
// Don't suggest the starting type in type assertions. For example,
|
|
|
|
// if "foo" is an io.Writer, don't suggest "foo.(io.Writer)".
|
2019-09-13 13:15:53 -06:00
|
|
|
if types.Identical(c.expectedType.typeName.assertableFrom, actual) {
|
2019-06-26 16:30:01 -06:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-09-13 13:15:53 -06:00
|
|
|
if intf, ok := c.expectedType.typeName.assertableFrom.Underlying().(*types.Interface); ok {
|
2019-06-26 16:30:01 -06:00
|
|
|
if !types.AssertableTo(intf, actual) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-17 15:59:27 -06:00
|
|
|
if c.expectedType.typeName.wantComparable && !types.Comparable(actual) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-09-13 13:15:53 -06:00
|
|
|
// We can expect a type name and have an expected type in cases like:
|
|
|
|
//
|
|
|
|
// var foo []int
|
|
|
|
// foo = []i<>
|
|
|
|
//
|
|
|
|
// Where our expected type is "[]int", and we expect a type name.
|
|
|
|
if c.expectedType.objType != nil {
|
|
|
|
return types.AssignableTo(actual, c.expectedType.objType)
|
|
|
|
}
|
|
|
|
|
2019-06-26 16:30:01 -06:00
|
|
|
// Default to saying any type name is a match.
|
|
|
|
return true
|
|
|
|
}
|