Debian Codegraph @

gopls/internal/golang/completion/literal.go

raw symbols SCIP
1 // Copyright 2019 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 "context"
9 "fmt"
10 "go/types"
11 "strings"
12 "unicode"
13
14 "golang.org/x/tools/gopls/internal/golang"
15 "golang.org/x/tools/gopls/internal/golang/completion/snippet"
16 "golang.org/x/tools/gopls/internal/protocol"
17 "golang.org/x/tools/internal/event"
18 "golang.org/x/tools/internal/typesinternal"
19 )
20
21 // literal generates composite literal, function literal, and make()
22 // completion items.
23 func (c *completer) literal(ctx context.Context, literalType types.Type, imp *importInfo) {
24 if !c.opts.snippets {
25 return
26 }
27
28 expType := c.inference.objType
29
30 if c.inference.matchesVariadic(literalType) {
31 // Don't offer literal slice candidates for variadic arguments.
32 // For example, don't offer "[]interface{}{}" in "fmt.Print(<>)".
33 return
34 }
35
36 // Avoid literal candidates if the expected type is an empty
37 // interface. It isn't very useful to suggest a literal candidate of
38 // every possible type.
39 if expType != nil && isEmptyInterface(expType) {
40 return
41 }
42
43 // We handle unnamed literal completions explicitly before searching
44 // for candidates. Avoid named-type literal completions for
45 // unnamed-type expected type since that results in duplicate
46 // candidates. For example, in
47 //
48 // type mySlice []int
49 // var []int = <>
50 //
51 // don't offer "mySlice{}" since we have already added a candidate
52 // of "[]int{}".
53
54 // TODO(adonovan): think about aliases:
55 // they should probably be treated more like Named.
56 // Should this use Deref not Unpointer?
57 if is[*types.Named](types.Unalias(literalType)) &&
58 expType != nil &&
59 !is[*types.Named](types.Unalias(typesinternal.Unpointer(expType))) {
60
61 return
62 }
63
64 // Check if an object of type literalType would match our expected type.
65 cand := candidate{
66 obj: c.fakeObj(literalType),
67 }
68
69 switch literalType.Underlying().(type) {
70 // These literal types are addressable (e.g. "&[]int{}"), others are
71 // not (e.g. can't do "&(func(){})").
72 case *types.Struct, *types.Array, *types.Slice, *types.Map:
73 cand.addressable = true
74 }
75
76 // Only suggest a literal conversion if the exact type is known.
77 if !c.matchingCandidate(&cand) || (cand.convertTo != nil && !c.inference.needsExactType) {
78 return
79 }
80
81 var (
82 qual = c.qual
83 sel = enclosingSelector(c.path, c.pos)
84 conversion conversionEdits
85 )
86
87 if cand.convertTo != nil {
88 conversion = c.formatConversion(cand.convertTo)
89 }
90
91 // Don't qualify the type name if we are in a selector expression
92 // since the package name is already present.
93 if sel != nil {
94 qual = func(_ *types.Package) string { return "" }
95 }
96
97 snip, typeName := c.typeNameSnippet(literalType, qual)
98
99 // A type name of "[]int" doesn't work very will with the matcher
100 // since "[" isn't a valid identifier prefix. Here we strip off the
101 // slice (and array) prefix yielding just "int".
102 matchName := typeName
103 switch t := literalType.(type) {
104 case *types.Slice:
105 matchName = types.TypeString(t.Elem(), qual)
106 case *types.Array:
107 matchName = types.TypeString(t.Elem(), qual)
108 }
109
110 addlEdits, err := c.importEdits(imp)
111 if err != nil {
112 event.Error(ctx, "error adding import for literal candidate", err)
113 return
114 }
115
116 // If prefix matches the type name, client may want a composite literal.
117 if score := c.matcher.Score(matchName); score > 0 {
118 if cand.hasMod(reference) {
119 if sel != nil {
120 // If we are in a selector we must place the "&" before the selector.
121 // For example, "foo.B<>" must complete to "&foo.Bar{}", not
122 // "foo.&Bar{}".
123 edits, err := c.editText(sel.Pos(), sel.Pos(), "&")
124 if err != nil {
125 event.Error(ctx, "error making edit for literal pointer completion", err)
126 return
127 }
128 addlEdits = append(addlEdits, edits...)
129 } else {
130 // Otherwise we can stick the "&" directly before the type name.
131 typeName = "&" + typeName
132 snip.PrependText("&")
133 }
134 }
135
136 switch t := literalType.Underlying().(type) {
137 case *types.Struct, *types.Array, *types.Slice, *types.Map:
138 item := c.compositeLiteral(t, snip.Clone(), typeName, float64(score), addlEdits)
139 item.addConversion(c, conversion)
140 c.items = append(c.items, item)
141 case *types.Signature:
142 // Add a literal completion for a signature type that implements
143 // an interface. For example, offer "http.HandlerFunc()" when
144 // expected type is "http.Handler".
145 if expType != nil && types.IsInterface(expType) {
146 if item, ok := c.basicLiteral(t, snip.Clone(), typeName, float64(score), addlEdits); ok {
147 item.addConversion(c, conversion)
148 c.items = append(c.items, item)
149 }
150 }
151 case *types.Basic:
152 // Add a literal completion for basic types that implement our
153 // expected interface (e.g. named string type http.Dir
154 // implements http.FileSystem), or are identical to our expected
155 // type (i.e. yielding a type conversion such as "float64()").
156 if expType != nil && (types.IsInterface(expType) || types.Identical(expType, literalType)) {
157 if item, ok := c.basicLiteral(t, snip.Clone(), typeName, float64(score), addlEdits); ok {
158 item.addConversion(c, conversion)
159 c.items = append(c.items, item)
160 }
161 }
162 }
163 }
164
165 // If prefix matches "make", client may want a "make()"
166 // invocation. We also include the type name to allow for more
167 // flexible fuzzy matching.
168 if score := c.matcher.Score("make." + matchName); !cand.hasMod(reference) && score > 0 {
169 switch literalType.Underlying().(type) {
170 case *types.Slice:
171 // The second argument to "make()" for slices is required, so default to "0".
172 item := c.makeCall(snip.Clone(), typeName, "0", float64(score), addlEdits)
173 item.addConversion(c, conversion)
174 c.items = append(c.items, item)
175 case *types.Map, *types.Chan:
176 // Maps and channels don't require the second argument, so omit
177 // to keep things simple for now.
178 item := c.makeCall(snip.Clone(), typeName, "", float64(score), addlEdits)
179 item.addConversion(c, conversion)
180 c.items = append(c.items, item)
181 }
182 }
183
184 // If prefix matches "func", client may want a function literal.
185 if score := c.matcher.Score("func"); !cand.hasMod(reference) && score > 0 && (expType == nil || !types.IsInterface(expType)) {
186 switch t := literalType.Underlying().(type) {
187 case *types.Signature:
188 if item, ok := c.functionLiteral(ctx, t, float64(score)); ok {
189 item.addConversion(c, conversion)
190 c.items = append(c.items, item)
191 }
192 }
193 }
194 }
195
196 // literalCandidateScore is the base score for literal candidates.
197 // Literal candidates match the expected type so they should be high
198 // scoring, but we want them ranked below lexical objects of the
199 // correct type, so scale down highScore.
200 const literalCandidateScore = highScore / 2
201
202 // functionLiteral returns a function literal completion item for the
203 // given signature, if applicable.
204 func (c *completer) functionLiteral(ctx context.Context, sig *types.Signature, matchScore float64) (CompletionItem, bool) {
205 snip := &snippet.Builder{}
206 snip.WriteText("func(")
207
208 // First we generate names for each param and keep a seen count so
209 // we know if we need to uniquify param names. For example,
210 // "func(int)" will become "func(i int)", but "func(int, int64)"
211 // will become "func(i1 int, i2 int64)".
212 var (
213 paramNames = make([]string, sig.Params().Len())
214 paramNameCount = make(map[string]int)
215 hasTypeParams bool
216 )
217 for i := range sig.Params().Len() {
218 var (
219 p = sig.Params().At(i)
220 name = p.Name()
221 )
222
223 if tp, _ := types.Unalias(p.Type()).(*types.TypeParam); tp != nil && !c.typeParamInScope(tp) {
224 hasTypeParams = true
225 }
226
227 if name == "" {
228 // If the param has no name in the signature, guess a name based
229 // on the type. Use an empty qualifier to ignore the package.
230 // For example, we want to name "http.Request" "r", not "hr".
231 typeName, err := golang.FormatVarType(ctx, c.snapshot, c.pkg, p,
232 func(p *types.Package) string { return "" },
233 func(golang.PackageName, golang.ImportPath, golang.PackagePath) string { return "" })
234 if err != nil {
235 // In general, the only error we should encounter while formatting is
236 // context cancellation.
237 if ctx.Err() == nil {
238 event.Error(ctx, "formatting var type", err)
239 }
240 return CompletionItem{}, false
241 }
242 name = abbreviateTypeName(typeName)
243 }
244 paramNames[i] = name
245 if name != "_" {
246 paramNameCount[name]++
247 }
248 }
249
250 for n, c := range paramNameCount {
251 // Any names we saw more than once will need a unique suffix added
252 // on. Reset the count to 1 to act as the suffix for the first
253 // name.
254 if c >= 2 {
255 paramNameCount[n] = 1
256 } else {
257 delete(paramNameCount, n)
258 }
259 }
260
261 for i := range sig.Params().Len() {
262 if hasTypeParams && !c.opts.placeholders {
263 // If there are type params in the args then the user must
264 // choose the concrete types. If placeholders are disabled just
265 // drop them between the parens and let them fill things in.
266 snip.WritePlaceholder(nil)
267 break
268 }
269
270 if i > 0 {
271 snip.WriteText(", ")
272 }
273
274 var (
275 p = sig.Params().At(i)
276 name = paramNames[i]
277 )
278
279 // Uniquify names by adding on an incrementing numeric suffix.
280 if idx, found := paramNameCount[name]; found {
281 paramNameCount[name]++
282 name = fmt.Sprintf("%s%d", name, idx)
283 }
284
285 if name != p.Name() && c.opts.placeholders {
286 // If we didn't use the signature's param name verbatim then we
287 // may have chosen a poor name. Give the user a placeholder so
288 // they can easily fix the name.
289 snip.WritePlaceholder(func(b *snippet.Builder) {
290 b.WriteText(name)
291 })
292 } else {
293 snip.WriteText(name)
294 }
295
296 // If the following param's type is identical to this one, omit
297 // this param's type string. For example, emit "i, j int" instead
298 // of "i int, j int".
299 if i == sig.Params().Len()-1 || !types.Identical(p.Type(), sig.Params().At(i+1).Type()) {
300 snip.WriteText(" ")
301 typeStr, err := golang.FormatVarType(ctx, c.snapshot, c.pkg, p, c.qual, c.mq)
302 if err != nil {
303 // In general, the only error we should encounter while formatting is
304 // context cancellation.
305 if ctx.Err() == nil {
306 event.Error(ctx, "formatting var type", err)
307 }
308 return CompletionItem{}, false
309 }
310 if sig.Variadic() && i == sig.Params().Len()-1 {
311 typeStr = strings.Replace(typeStr, "[]", "...", 1)
312 }
313
314 if tp, ok := types.Unalias(p.Type()).(*types.TypeParam); ok && !c.typeParamInScope(tp) {
315 snip.WritePlaceholder(func(snip *snippet.Builder) {
316 snip.WriteText(typeStr)
317 })
318 } else {
319 snip.WriteText(typeStr)
320 }
321 }
322 }
323 snip.WriteText(")")
324
325 results := sig.Results()
326 if results.Len() > 0 {
327 snip.WriteText(" ")
328 }
329
330 resultsNeedParens := results.Len() > 1 ||
331 results.Len() == 1 && results.At(0).Name() != ""
332
333 var resultHasTypeParams bool
334 for v := range results.Variables() {
335 if tp, ok := types.Unalias(v.Type()).(*types.TypeParam); ok && !c.typeParamInScope(tp) {
336 resultHasTypeParams = true
337 }
338 }
339
340 if resultsNeedParens {
341 snip.WriteText("(")
342 }
343 for i := range results.Len() {
344 if resultHasTypeParams && !c.opts.placeholders {
345 // Leave an empty tabstop if placeholders are disabled and there
346 // are type args that need specifying.
347 snip.WritePlaceholder(nil)
348 break
349 }
350
351 if i > 0 {
352 snip.WriteText(", ")
353 }
354 r := results.At(i)
355 if name := r.Name(); name != "" {
356 snip.WriteText(name + " ")
357 }
358
359 text, err := golang.FormatVarType(ctx, c.snapshot, c.pkg, r, c.qual, c.mq)
360 if err != nil {
361 // In general, the only error we should encounter while formatting is
362 // context cancellation.
363 if ctx.Err() == nil {
364 event.Error(ctx, "formatting var type", err)
365 }
366 return CompletionItem{}, false
367 }
368 if tp, ok := types.Unalias(r.Type()).(*types.TypeParam); ok && !c.typeParamInScope(tp) {
369 snip.WritePlaceholder(func(snip *snippet.Builder) {
370 snip.WriteText(text)
371 })
372 } else {
373 snip.WriteText(text)
374 }
375 }
376 if resultsNeedParens {
377 snip.WriteText(")")
378 }
379
380 snip.WriteText(" {")
381 snip.WriteFinalTabstop()
382 snip.WriteText("}")
383
384 return CompletionItem{
385 Label: "func(...) {}",
386 Score: matchScore * literalCandidateScore,
387 Kind: protocol.VariableCompletion,
388 snippet: snip,
389 }, true
390 }
391
392 // conventionalAcronyms contains conventional acronyms for type names
393 // in lower case. For example, "ctx" for "context" and "err" for "error".
394 //
395 // Keep this up to date with golang.conventionalVarNames.
396 var conventionalAcronyms = map[string]string{
397 "context": "ctx",
398 "error": "err",
399 "tx": "tx",
400 "responsewriter": "w",
401 }
402
403 // abbreviateTypeName abbreviates type names into acronyms. For
404 // example, "fooBar" is abbreviated "fb". Care is taken to ignore
405 // non-identifier runes. For example, "[]int" becomes "i", and
406 // "struct { i int }" becomes "s".
407 func abbreviateTypeName(s string) string {
408 // Trim off leading non-letters. We trim everything between "[" and
409 // "]" to handle array types like "[someConst]int".
410 var inBracket bool
411 s = strings.TrimFunc(s, func(r rune) bool {
412 if inBracket {
413 inBracket = r != ']'
414 return true
415 }
416
417 if r == '[' {
418 inBracket = true
419 }
420
421 return !unicode.IsLetter(r)
422 })
423
424 if acr, ok := conventionalAcronyms[strings.ToLower(s)]; ok {
425 return acr
426 }
427
428 return golang.AbbreviateVarName(s)
429 }
430
431 // compositeLiteral returns a composite literal completion item for the given typeName.
432 // T is an (unnamed, unaliased) struct, array, slice, or map type.
433 func (c *completer) compositeLiteral(T types.Type, snip *snippet.Builder, typeName string, matchScore float64, edits []protocol.TextEdit) CompletionItem {
434 snip.WriteText("{")
435 // Don't put the tab stop inside the composite literal curlies "{}"
436 // for structs that have no accessible fields.
437 if strct, ok := T.(*types.Struct); !ok || fieldsAccessible(strct, c.pkg.Types()) {
438 snip.WriteFinalTabstop()
439 }
440 snip.WriteText("}")
441
442 nonSnippet := typeName + "{}"
443
444 return CompletionItem{
445 Label: nonSnippet,
446 InsertText: nonSnippet,
447 Score: matchScore * literalCandidateScore,
448 Kind: protocol.VariableCompletion,
449 AdditionalTextEdits: edits,
450 snippet: snip,
451 }
452 }
453
454 // basicLiteral returns a literal completion item for the given basic
455 // type name typeName.
456 //
457 // If T is untyped, this function returns false.
458 func (c *completer) basicLiteral(T types.Type, snip *snippet.Builder, typeName string, matchScore float64, edits []protocol.TextEdit) (CompletionItem, bool) {
459 // Never give type conversions like "untyped int()".
460 if isUntyped(T) {
461 return CompletionItem{}, false
462 }
463
464 snip.WriteText("(")
465 snip.WriteFinalTabstop()
466 snip.WriteText(")")
467
468 nonSnippet := typeName + "()"
469
470 return CompletionItem{
471 Label: nonSnippet,
472 InsertText: nonSnippet,
473 Detail: T.String(),
474 Score: matchScore * literalCandidateScore,
475 Kind: protocol.VariableCompletion,
476 AdditionalTextEdits: edits,
477 snippet: snip,
478 }, true
479 }
480
481 // makeCall returns a completion item for a "make()" call given a specific type.
482 func (c *completer) makeCall(snip *snippet.Builder, typeName string, secondArg string, matchScore float64, edits []protocol.TextEdit) CompletionItem {
483 // Keep it simple and don't add any placeholders for optional "make()" arguments.
484
485 snip.PrependText("make(")
486 if secondArg != "" {
487 snip.WriteText(", ")
488 snip.WritePlaceholder(func(b *snippet.Builder) {
489 if c.opts.placeholders {
490 b.WriteText(secondArg)
491 }
492 })
493 }
494 snip.WriteText(")")
495
496 var nonSnippet strings.Builder
497 nonSnippet.WriteString("make(" + typeName)
498 if secondArg != "" {
499 nonSnippet.WriteString(", ")
500 nonSnippet.WriteString(secondArg)
501 }
502 nonSnippet.WriteByte(')')
503
504 return CompletionItem{
505 Label: nonSnippet.String(),
506 InsertText: nonSnippet.String(),
507 // make() should be just below other literal completions
508 Score: matchScore * literalCandidateScore * 0.99,
509 Kind: protocol.FunctionCompletion,
510 AdditionalTextEdits: edits,
511 snippet: snip,
512 }
513 }
514
515 // Create a snippet for a type name where type params become placeholders.
516 func (c *completer) typeNameSnippet(literalType types.Type, qual types.Qualifier) (*snippet.Builder, string) {
517 var (
518 snip snippet.Builder
519 typeName string
520 tparams *types.TypeParamList
521 )
522
523 t, ok := literalType.(typesinternal.NamedOrAlias) // = *Named | *Alias
524 if ok {
525 tparams = t.TypeParams()
526 }
527 if tparams.Len() > 0 && !c.fullyInstantiated(t) {
528 // tparams.Len() > 0 implies t != nil.
529 // Inv: t is not "error" or "unsafe.Pointer", so t.Obj() != nil and has a Pkg().
530
531 // We are not "fully instantiated" meaning we have type params that must be specified.
532 if pkg := qual(t.Obj().Pkg()); pkg != "" {
533 typeName = pkg + "."
534 }
535
536 // We do this to get "someType" instead of "someType[T]".
537 typeName += t.Obj().Name()
538 snip.WriteText(typeName + "[")
539
540 if c.opts.placeholders {
541 for i := range tparams.Len() {
542 if i > 0 {
543 snip.WriteText(", ")
544 }
545 snip.WritePlaceholder(func(snip *snippet.Builder) {
546 snip.WriteText(types.TypeString(tparams.At(i), qual))
547 })
548 }
549 } else {
550 snip.WritePlaceholder(nil)
551 }
552 snip.WriteText("]")
553 typeName += "[...]"
554 } else {
555 // We don't have unspecified type params so use default type formatting.
556 typeName = types.TypeString(literalType, qual)
557 snip.WriteText(typeName)
558 }
559
560 return &snip, typeName
561 }
562
563 // fullyInstantiated reports whether all of t's type params have
564 // specified type args.
565 func (c *completer) fullyInstantiated(t typesinternal.NamedOrAlias) bool {
566 targs := t.TypeArgs()
567 tparams := t.TypeParams()
568
569 if tparams.Len() != targs.Len() {
570 return false
571 }
572
573 for targ := range targs.Types() {
574
575 // The expansion of an alias can have free type parameters,
576 // whether or not the alias itself has type parameters:
577 //
578 // func _[K comparable]() {
579 // type Set = map[K]bool // free(Set) = {K}
580 // type MapTo[V] = map[K]V // free(Map[foo]) = {V}
581 // }
582 //
583 // So, we must Unalias.
584 switch targ := types.Unalias(targ).(type) {
585 case *types.TypeParam:
586 // A *TypeParam only counts as specified if it is currently in
587 // scope (i.e. we are in a generic definition).
588 if !c.typeParamInScope(targ) {
589 return false
590 }
591 case *types.Named:
592 if !c.fullyInstantiated(targ) {
593 return false
594 }
595 }
596 }
597 return true
598 }
599
600 // typeParamInScope returns whether tp's object is in scope at c.pos.
601 // This tells you whether you are in a generic definition and can
602 // assume tp has been specified.
603 func (c *completer) typeParamInScope(tp *types.TypeParam) bool {
604 obj := tp.Obj()
605 if obj == nil {
606 return false
607 }
608
609 scope := c.innermostScope()
610 if scope == nil {
611 return false
612 }
613
614 _, foundObj := scope.LookupParent(obj.Name(), c.pos)
615 return obj == foundObj
616 }