Debian Codegraph @

gopls/internal/golang/completion/statements.go

raw symbols SCIP
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package completion
6
7 import (
8 "fmt"
9 "go/ast"
10 "go/token"
11 "go/types"
12 "strings"
13
14 "golang.org/x/tools/gopls/internal/cache"
15 "golang.org/x/tools/gopls/internal/golang"
16 "golang.org/x/tools/gopls/internal/golang/completion/snippet"
17 "golang.org/x/tools/gopls/internal/protocol"
18 "golang.org/x/tools/internal/typesinternal"
19 )
20
21 // addStatementCandidates adds full statement completion candidates
22 // appropriate for the current context.
23 func (c *completer) addStatementCandidates() {
24 c.addErrCheck()
25 c.addAssignAppend()
26 c.addReturnZeroValues()
27 }
28
29 // addAssignAppend offers a completion candidate of the form:
30 //
31 // someSlice = append(someSlice, )
32 //
33 // It will offer the "append" completion in either of two situations:
34 //
35 // 1. Position is in RHS of assign, prefix matches "append", and
36 // corresponding LHS object is a slice. For example,
37 // "foo = ap<>" completes to "foo = append(foo, )".
38 //
39 // 2. Prefix is an ident or selector in an *ast.ExprStmt (i.e.
40 // beginning of statement), and our best matching candidate is a
41 // slice. For example: "foo.ba" completes to "foo.bar = append(foo.bar, )".
42 func (c *completer) addAssignAppend() {
43 if len(c.path) < 3 {
44 return
45 }
46
47 ident, _ := c.path[0].(*ast.Ident)
48 if ident == nil {
49 return
50 }
51
52 var (
53 // sliceText is the full name of our slice object, e.g. "s.abc" in
54 // "s.abc = app<>".
55 sliceText string
56 // needsLHS is true if we need to prepend the LHS slice name and
57 // "=" to our candidate.
58 needsLHS = false
59 fset = c.pkg.FileSet()
60 )
61
62 switch n := c.path[1].(type) {
63 case *ast.AssignStmt:
64 // We are already in an assignment. Make sure our prefix matches "append".
65 if c.matcher.Score("append") <= 0 {
66 return
67 }
68
69 exprIdx := exprAtPos(c.pos, n.Rhs)
70 if exprIdx == len(n.Rhs) || exprIdx > len(n.Lhs)-1 {
71 return
72 }
73
74 lhsType := c.pkg.TypesInfo().TypeOf(n.Lhs[exprIdx])
75 if lhsType == nil {
76 return
77 }
78
79 // Make sure our corresponding LHS object is a slice.
80 if _, isSlice := lhsType.Underlying().(*types.Slice); !isSlice {
81 return
82 }
83
84 // The name or our slice is whatever's in the LHS expression.
85 sliceText = golang.FormatNode(fset, n.Lhs[exprIdx])
86 case *ast.SelectorExpr:
87 // Make sure we are a selector at the beginning of a statement.
88 if _, parentIsExprtStmt := c.path[2].(*ast.ExprStmt); !parentIsExprtStmt {
89 return
90 }
91
92 // So far we only know the first part of our slice name. For
93 // example in "s.a<>" we only know our slice begins with "s."
94 // since the user could still be typing.
95 sliceText = golang.FormatNode(fset, n.X) + "."
96 needsLHS = true
97 case *ast.ExprStmt:
98 needsLHS = true
99 default:
100 return
101 }
102
103 var (
104 label string
105 snip snippet.Builder
106 score = highScore
107 )
108
109 if needsLHS {
110 // Offer the long form assign + append candidate if our best
111 // candidate is a slice.
112 bestItem := c.topCandidate()
113 if bestItem == nil || !bestItem.isSlice {
114 return
115 }
116
117 // Don't rank the full form assign + append candidate above the
118 // slice itself.
119 score = bestItem.Score - 0.01
120
121 // Fill in rest of sliceText now that we have the object name.
122 sliceText += bestItem.Label
123
124 // Fill in the candidate's LHS bits.
125 label = fmt.Sprintf("%s = ", bestItem.Label)
126 snip.WriteText(label)
127 }
128
129 snip.WriteText(fmt.Sprintf("append(%s, ", sliceText))
130 snip.WritePlaceholder(nil)
131 snip.WriteText(")")
132
133 c.items = append(c.items, CompletionItem{
134 Label: label + fmt.Sprintf("append(%s, )", sliceText),
135 Kind: protocol.FunctionCompletion,
136 Score: score,
137 snippet: &snip,
138 })
139 }
140
141 // topCandidate returns the strictly highest scoring candidate
142 // collected so far. If the top two candidates have the same score,
143 // nil is returned.
144 func (c *completer) topCandidate() *CompletionItem {
145 var bestItem, secondBestItem *CompletionItem
146 for i := range c.items {
147 if bestItem == nil || c.items[i].Score > bestItem.Score {
148 bestItem = &c.items[i]
149 } else if secondBestItem == nil || c.items[i].Score > secondBestItem.Score {
150 secondBestItem = &c.items[i]
151 }
152 }
153
154 // If secondBestItem has the same score, bestItem isn't
155 // the strict best.
156 if secondBestItem != nil && secondBestItem.Score == bestItem.Score {
157 return nil
158 }
159
160 return bestItem
161 }
162
163 // addErrCheck offers a completion candidate of the form:
164 //
165 // if err != nil {
166 // return nil, err
167 // }
168 //
169 // In the case of test functions, it offers a completion candidate of the form:
170 //
171 // if err != nil {
172 // t.Fatal(err)
173 // }
174 //
175 // The position must be in a function that returns an error, and the
176 // statement preceding the position must be an assignment where the
177 // final LHS object is an error. addErrCheck will synthesize
178 // zero values as necessary to make the return statement valid.
179 func (c *completer) addErrCheck() {
180 if len(c.path) < 2 || c.enclosingFunc == nil || !c.opts.placeholders {
181 return
182 }
183
184 var (
185 errorType = types.Universe.Lookup("error").Type()
186 result = c.enclosingFunc.sig.Results()
187 testVar = getTestVar(c.enclosingFunc, c.pkg)
188 isTest = testVar != ""
189 doesNotReturnErr = result.Len() == 0 || !types.Identical(result.At(result.Len()-1).Type(), errorType)
190 )
191 // Make sure our enclosing function is a Test func or returns an error.
192 if !isTest && doesNotReturnErr {
193 return
194 }
195
196 prevLine := prevStmt(c.pos, c.path)
197 if prevLine == nil {
198 return
199 }
200
201 // Make sure our preceding statement was as assignment.
202 assign, _ := prevLine.(*ast.AssignStmt)
203 if assign == nil || len(assign.Lhs) == 0 {
204 return
205 }
206
207 lastAssignee := assign.Lhs[len(assign.Lhs)-1]
208
209 // Make sure the final assignee is an error.
210 if !types.Identical(c.pkg.TypesInfo().TypeOf(lastAssignee), errorType) {
211 return
212 }
213
214 var (
215 // errVar is e.g. "err" in "foo, err := bar()".
216 errVar = golang.FormatNode(c.pkg.FileSet(), lastAssignee)
217
218 // Whether we need to include the "if" keyword in our candidate.
219 needsIf = true
220 )
221
222 // If the returned error from the previous statement is "_", it is not a real object.
223 // If we don't have an error, and the function signature takes a testing.TB that is either ignored
224 // or an "_", then we also can't call t.Fatal(err).
225 if errVar == "_" {
226 return
227 }
228
229 // Below we try to detect if the user has already started typing "if
230 // err" so we can replace what they've typed with our complete
231 // statement.
232 switch n := c.path[0].(type) {
233 case *ast.Ident:
234 switch c.path[1].(type) {
235 case *ast.ExprStmt:
236 // This handles:
237 //
238 // f, err := os.Open("foo")
239 // i<>
240
241 // Make sure they are typing "if".
242 if c.matcher.Score("if") <= 0 {
243 return
244 }
245 case *ast.IfStmt:
246 // This handles:
247 //
248 // f, err := os.Open("foo")
249 // if er<>
250
251 // Make sure they are typing the error's name.
252 if c.matcher.Score(errVar) <= 0 {
253 return
254 }
255
256 needsIf = false
257 default:
258 return
259 }
260 case *ast.IfStmt:
261 // This handles:
262 //
263 // f, err := os.Open("foo")
264 // if <>
265
266 // Avoid false positives by ensuring the if's cond is a bad
267 // expression. For example, don't offer the completion in cases
268 // like "if <> somethingElse".
269 if _, bad := n.Cond.(*ast.BadExpr); !bad {
270 return
271 }
272
273 // If "if" is our direct prefix, we need to include it in our
274 // candidate since the existing "if" will be overwritten.
275 needsIf = c.pos == n.Pos()+token.Pos(len("if"))
276 }
277
278 // Build up a snippet that looks like:
279 //
280 // if err != nil {
281 // return <zero value>, ..., ${1:err}
282 // }
283 //
284 // We make the error a placeholder so it is easy to alter the error.
285 var snip snippet.Builder
286 if needsIf {
287 snip.WriteText("if ")
288 }
289 snip.WriteText(fmt.Sprintf("%s != nil {\n\t", errVar))
290
291 var label string
292 if isTest {
293 snip.WriteText(fmt.Sprintf("%s.Fatal(%s)", testVar, errVar))
294 label = fmt.Sprintf("%[1]s != nil { %[2]s.Fatal(%[1]s) }", errVar, testVar)
295 } else {
296 snip.WriteText("return ")
297 for i := range result.Len() - 1 {
298 if zero, isValid := typesinternal.ZeroString(result.At(i).Type(), c.qual); isValid {
299 snip.WriteText(zero)
300 }
301 snip.WriteText(", ")
302 }
303 snip.WritePlaceholder(func(b *snippet.Builder) {
304 b.WriteText(errVar)
305 })
306 label = fmt.Sprintf("%[1]s != nil { return %[1]s }", errVar)
307 }
308
309 snip.WriteText("\n}")
310
311 if needsIf {
312 label = "if " + label
313 }
314
315 c.items = append(c.items, CompletionItem{
316 Label: label,
317 Kind: protocol.SnippetCompletion,
318 Score: highScore,
319 snippet: &snip,
320 })
321 }
322
323 // getTestVar checks the function signature's input parameters and returns
324 // the name of the first parameter that implements "testing.TB". For example,
325 // func someFunc(t *testing.T) returns the string "t", func someFunc(b *testing.B)
326 // returns "b" etc. An empty string indicates that the function signature
327 // does not take a testing.TB parameter or does so but is ignored such
328 // as func someFunc(*testing.T).
329 func getTestVar(enclosingFunc *funcInfo, pkg *cache.Package) string {
330 if enclosingFunc == nil || enclosingFunc.sig == nil {
331 return ""
332 }
333
334 var testingPkg *types.Package
335 for _, p := range pkg.Types().Imports() {
336 if p.Path() == "testing" {
337 testingPkg = p
338 break
339 }
340 }
341 if testingPkg == nil {
342 return ""
343 }
344 tbObj := testingPkg.Scope().Lookup("TB")
345 if tbObj == nil {
346 return ""
347 }
348 iface, ok := tbObj.Type().Underlying().(*types.Interface)
349 if !ok {
350 return ""
351 }
352
353 sig := enclosingFunc.sig
354 for param := range sig.Params().Variables() {
355 if param.Name() == "_" {
356 continue
357 }
358 if !types.Implements(param.Type(), iface) {
359 continue
360 }
361 return param.Name()
362 }
363
364 return ""
365 }
366
367 // addReturnZeroValues offers a snippet candidate on the form:
368 //
369 // return 0, "", nil
370 //
371 // Requires a partially or fully written return keyword at position.
372 // Requires current position to be in a function with more than
373 // zero return parameters.
374 func (c *completer) addReturnZeroValues() {
375 if len(c.path) < 2 || c.enclosingFunc == nil || !c.opts.placeholders {
376 return
377 }
378 result := c.enclosingFunc.sig.Results()
379 if result.Len() == 0 {
380 return
381 }
382
383 // Offer just less than we expect from return as a keyword.
384 var score = stdScore - 0.01
385 switch c.path[0].(type) {
386 case *ast.ReturnStmt, *ast.Ident:
387 f := c.matcher.Score("return")
388 if f <= 0 {
389 return
390 }
391 score *= float64(f)
392 default:
393 return
394 }
395
396 // The snippet will have a placeholder over each return value.
397 // The label will not.
398 var snip snippet.Builder
399 var label strings.Builder
400 snip.WriteText("return ")
401 fmt.Fprintf(&label, "return ")
402
403 for i := range result.Len() {
404 if i > 0 {
405 snip.WriteText(", ")
406 fmt.Fprintf(&label, ", ")
407 }
408
409 zero, isValid := typesinternal.ZeroString(result.At(i).Type(), c.qual)
410 if !isValid {
411 zero = ""
412 }
413 snip.WritePlaceholder(func(b *snippet.Builder) {
414 b.WriteText(zero)
415 })
416 fmt.Fprint(&label, zero)
417 }
418
419 c.items = append(c.items, CompletionItem{
420 Label: label.String(),
421 Kind: protocol.SnippetCompletion,
422 Score: score,
423 snippet: &snip,
424 })
425 }