Debian Codegraph @

gopls/internal/golang/completion/format.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 "errors"
10 "fmt"
11 "go/ast"
12 "go/doc"
13 "go/types"
14 "strings"
15
16 "golang.org/x/tools/gopls/internal/golang"
17 "golang.org/x/tools/gopls/internal/golang/completion/snippet"
18 "golang.org/x/tools/gopls/internal/protocol"
19 "golang.org/x/tools/gopls/internal/util/safetoken"
20 "golang.org/x/tools/gopls/internal/util/typesutil"
21 internalastutil "golang.org/x/tools/internal/astutil"
22 "golang.org/x/tools/internal/event"
23 "golang.org/x/tools/internal/imports"
24 )
25
26 var (
27 errNoMatch = errors.New("not a surrounding match")
28 errLowScore = errors.New("not a high scoring candidate")
29 )
30
31 // item formats a candidate to a CompletionItem.
32 func (c *completer) item(ctx context.Context, cand candidate) (CompletionItem, error) {
33 obj := cand.obj
34
35 // if the object isn't a valid match against the surrounding, return early.
36 matchScore := c.matcher.Score(cand.name)
37 if matchScore <= 0 {
38 return CompletionItem{}, errNoMatch
39 }
40 cand.score *= float64(matchScore)
41
42 // Ignore deep candidates that won't be in the MaxDeepCompletions anyway.
43 if len(cand.path) != 0 && !c.deepState.isHighScore(cand.score) {
44 return CompletionItem{}, errLowScore
45 }
46
47 // Handle builtin types separately.
48 if obj.Parent() == types.Universe {
49 return c.formatBuiltin(ctx, cand)
50 }
51
52 var (
53 label = cand.name
54 detail = types.TypeString(obj.Type(), c.qual)
55 insert = label
56 kind = protocol.TextCompletion
57 snip snippet.Builder
58 protocolEdits []protocol.TextEdit
59 )
60 if obj.Type() == nil {
61 detail = ""
62 }
63
64 type hasTypeParams interface{ TypeParams() *types.TypeParamList }
65 if genericType, _ := obj.Type().(hasTypeParams); genericType != nil && isTypeName(obj) && c.wantTypeParams() {
66 // golang/go#71044: note that type names can be basic types, even in
67 // receiver position, for invalid code.
68 tparams := genericType.TypeParams()
69 label += typesutil.FormatTypeParams(tparams)
70 insert = label // maintain invariant above (label == insert)
71 }
72
73 snip.WriteText(insert)
74
75 switch obj := obj.(type) {
76 case *types.TypeName:
77 detail, kind = golang.FormatType(obj.Type(), c.qual)
78 case *types.Const:
79 kind = protocol.ConstantCompletion
80 case *types.Var:
81 if _, ok := obj.Type().(*types.Struct); ok {
82 detail = "struct{...}" // for anonymous unaliased struct types
83 } else if obj.IsField() {
84 var err error
85 detail, err = golang.FormatVarType(ctx, c.snapshot, c.pkg, obj, c.qual, c.mq)
86 if err != nil {
87 return CompletionItem{}, err
88 }
89 }
90 if obj.IsField() {
91 kind = protocol.FieldCompletion
92 c.structFieldSnippet(cand, detail, &snip)
93 } else {
94 kind = protocol.VariableCompletion
95 }
96 if obj.Type() == nil {
97 break
98 }
99 case *types.Func:
100 if obj.Signature().Recv() == nil {
101 kind = protocol.FunctionCompletion
102 } else {
103 kind = protocol.MethodCompletion
104 }
105 case *types.PkgName:
106 kind = protocol.ModuleCompletion
107 detail = fmt.Sprintf("%q", obj.Imported().Path())
108 case *types.Label:
109 kind = protocol.ConstantCompletion
110 detail = "label"
111 }
112
113 var prefix string
114 for _, mod := range cand.mods {
115 switch mod {
116 case reference:
117 prefix = "&" + prefix
118 case dereference:
119 prefix = "*" + prefix
120 case chanRead:
121 prefix = "<-" + prefix
122 }
123 }
124
125 var (
126 suffix string
127 funcType = obj.Type()
128 )
129 Suffixes:
130 for _, mod := range cand.mods {
131 switch mod {
132 case invoke:
133 if sig, ok := funcType.Underlying().(*types.Signature); ok {
134 s, err := golang.NewSignature(ctx, c.snapshot, c.pkg, sig, nil, c.qual, c.mq)
135 if err != nil {
136 return CompletionItem{}, err
137 }
138
139 tparams := s.TypeParams()
140 if len(tparams) > 0 {
141 // Eliminate the suffix of type parameters that are
142 // likely redundant because they can probably be
143 // inferred from the argument types (#51783).
144 //
145 // We don't bother doing the reverse inference from
146 // result types as result-only type parameters are
147 // quite unusual.
148 free := inferableTypeParams(sig)
149 for i := sig.TypeParams().Len() - 1; i >= 0; i-- {
150 tparam := sig.TypeParams().At(i)
151 if !free[tparam] {
152 break
153 }
154 tparams = tparams[:i] // eliminate
155 }
156 }
157
158 c.functionCallSnippet("", tparams, s.Params(), &snip)
159 if sig.Results().Len() == 1 {
160 funcType = sig.Results().At(0).Type()
161 }
162 detail = "func" + s.Format()
163 }
164
165 if !c.opts.snippets {
166 // Without snippets the candidate will not include "()". Don't
167 // add further suffixes since they will be invalid. For
168 // example, with snippets "foo()..." would become "foo..."
169 // without snippets if we added the dotDotDot.
170 break Suffixes
171 }
172 case takeSlice:
173 suffix += "[:]"
174 case takeDotDotDot:
175 suffix += "..."
176 case index:
177 snip.WriteText("[")
178 snip.WritePlaceholder(nil)
179 snip.WriteText("]")
180 }
181 }
182
183 // If this candidate needs an additional import statement,
184 // add the additional text edits needed.
185 if cand.imp != nil {
186 addlEdits, err := c.importEdits(cand.imp)
187
188 if err != nil {
189 return CompletionItem{}, err
190 }
191
192 protocolEdits = append(protocolEdits, addlEdits...)
193 if kind != protocol.ModuleCompletion {
194 if detail != "" {
195 detail += " "
196 }
197 detail += fmt.Sprintf("(from %q)", cand.imp.importPath)
198 }
199 }
200
201 if cand.convertTo != nil {
202 conv := c.formatConversion(cand.convertTo)
203 prefix = conv.prefix + prefix
204 suffix = conv.suffix
205 }
206
207 if prefix != "" {
208 // If we are in a selector, add an edit to place prefix before selector.
209 if sel := enclosingSelector(c.path, c.pos); sel != nil {
210 edits, err := c.editText(sel.Pos(), sel.Pos(), prefix)
211 if err != nil {
212 return CompletionItem{}, err
213 }
214 protocolEdits = append(protocolEdits, edits...)
215 } else {
216 // If there is no selector, just stick the prefix at the start.
217 insert = prefix + insert
218 snip.PrependText(prefix)
219 }
220 }
221
222 if suffix != "" {
223 insert += suffix
224 snip.WriteText(suffix)
225 }
226
227 detail = strings.TrimPrefix(detail, "untyped ")
228 // override computed detail with provided detail, if something is provided.
229 if cand.detail != "" {
230 detail = cand.detail
231 }
232
233 // When completing right after "//" (cursor at the slashes with no space),
234 // prepend a space so the result is "// Name" rather than "//Name".
235 if c.completionContext.commentNeedsLeadingSpace {
236 insert = " " + insert
237 snip.PrependText(" ")
238 }
239
240 item := CompletionItem{
241 Label: label,
242 InsertText: insert,
243 AdditionalTextEdits: protocolEdits,
244 Detail: detail,
245 Kind: kind,
246 Score: cand.score,
247 Depth: len(cand.path),
248 snippet: &snip,
249 isSlice: isSlice(obj),
250 }
251 // If the user doesn't want documentation for completion items.
252 if !c.opts.documentation {
253 return item, nil
254 }
255 pos := safetoken.StartPosition(c.pkg.FileSet(), obj.Pos())
256
257 // We ignore errors here, because some types, like "unsafe" or "error",
258 // may not have valid positions that we can use to get documentation.
259 if !pos.IsValid() {
260 return item, nil
261 }
262
263 comment, err := golang.HoverDocForObject(ctx, c.snapshot, c.pkg.FileSet(), obj)
264 if err != nil {
265 event.Error(ctx, fmt.Sprintf("failed to find Hover for %q", obj.Name()), err)
266 return item, nil
267 }
268 if c.opts.fullDocumentation {
269 item.Documentation = comment.Text()
270 } else {
271 item.Documentation = doc.Synopsis(comment.Text())
272 }
273 if internalastutil.Deprecation(comment) != "" {
274 if c.snapshot.Options().CompletionTags {
275 item.Tags = []protocol.CompletionItemTag{protocol.ComplDeprecated}
276 } else if c.snapshot.Options().CompletionDeprecated {
277 item.Deprecated = true
278 }
279 }
280
281 return item, nil
282 }
283
284 // conversionEdits represents the string edits needed to make a type conversion
285 // of an expression.
286 type conversionEdits struct {
287 prefix, suffix string
288 }
289
290 // formatConversion returns the edits needed to make a type conversion
291 // expression, including parentheses if necessary.
292 //
293 // Returns empty conversionEdits if convertTo is nil.
294 func (c *completer) formatConversion(convertTo types.Type) conversionEdits {
295 if convertTo == nil {
296 return conversionEdits{}
297 }
298
299 typeName := types.TypeString(convertTo, c.qual)
300 switch t := convertTo.(type) {
301 // We need extra parens when casting to these types. For example,
302 // we need "(*int)(foo)", not "*int(foo)".
303 case *types.Pointer, *types.Signature:
304 typeName = "(" + typeName + ")"
305 case *types.Basic:
306 // If the types are incompatible (as determined by typeMatches), then we
307 // must need a conversion here. However, if the target type is untyped,
308 // don't suggest converting to e.g. "untyped float" (golang/go#62141).
309 if t.Info()&types.IsUntyped != 0 {
310 typeName = types.TypeString(types.Default(convertTo), c.qual)
311 }
312 }
313 return conversionEdits{prefix: typeName + "(", suffix: ")"}
314 }
315
316 // importEdits produces the text edits necessary to add the given import to the current file.
317 func (c *completer) importEdits(imp *importInfo) ([]protocol.TextEdit, error) {
318 if imp == nil {
319 return nil, nil
320 }
321
322 pgf, err := c.pkg.File(protocol.URIFromPath(c.filename))
323 if err != nil {
324 return nil, err
325 }
326
327 return golang.ComputeImportFixEdits(c.snapshot.Options().Local, pgf.Src, &imports.ImportFix{
328 StmtInfo: imports.ImportInfo{
329 ImportPath: imp.importPath,
330 Name: imp.name,
331 },
332 // IdentName is unused on this path and is difficult to get.
333 FixType: imports.AddImport,
334 })
335 }
336
337 func (c *completer) formatBuiltin(ctx context.Context, cand candidate) (CompletionItem, error) {
338 obj := cand.obj
339 item := CompletionItem{
340 Label: obj.Name(),
341 InsertText: obj.Name(),
342 Score: cand.score,
343 }
344 switch obj.(type) {
345 case *types.Const:
346 item.Kind = protocol.ConstantCompletion
347 case *types.Builtin:
348 item.Kind = protocol.FunctionCompletion
349 sig, err := golang.NewBuiltinSignature(ctx, c.snapshot, obj.Name())
350 if err != nil {
351 return CompletionItem{}, err
352 }
353 item.Detail = "func" + sig.Format()
354 item.snippet = &snippet.Builder{}
355 // The signature inferred for a built-in is instantiated, so TypeParams=∅.
356 c.functionCallSnippet(obj.Name(), sig.TypeParams(), sig.Params(), item.snippet)
357 case *types.TypeName:
358 if types.IsInterface(obj.Type()) {
359 item.Kind = protocol.InterfaceCompletion
360 } else {
361 item.Kind = protocol.ClassCompletion
362 }
363 case *types.Nil:
364 item.Kind = protocol.VariableCompletion
365 }
366 return item, nil
367 }
368
369 // decide if the type params (if any) should be part of the completion
370 // which only possible for types.Named and types.Signature
371 // (so far, only in receivers, e.g.; func (s *GENERIC[K, V])..., which is a types.Named)
372 func (c *completer) wantTypeParams() bool {
373 // Need to be lexically in a receiver, and a child of an IndexListExpr
374 // (but IndexListExpr only exists with go1.18)
375 start := c.path[0].Pos()
376 for i, nd := range c.path {
377 if fd, ok := nd.(*ast.FuncDecl); ok {
378 if i > 0 && fd.Recv != nil && start < fd.Recv.End() {
379 return true
380 } else {
381 return false
382 }
383 }
384 }
385 return false
386 }
387
388 // inferableTypeParams returns the set of type parameters
389 // of sig that are constrained by (inferred from) the argument types.
390 func inferableTypeParams(sig *types.Signature) map[*types.TypeParam]bool {
391 free := make(map[*types.TypeParam]bool)
392
393 // visit adds to free all the free type parameters of t.
394 var visit func(t types.Type)
395 visit = func(t types.Type) {
396 switch t := t.(type) {
397 case *types.Array:
398 visit(t.Elem())
399 case *types.Chan:
400 visit(t.Elem())
401 case *types.Map:
402 visit(t.Key())
403 visit(t.Elem())
404 case *types.Pointer:
405 visit(t.Elem())
406 case *types.Slice:
407 visit(t.Elem())
408 case *types.Interface:
409 for method := range t.ExplicitMethods() {
410 visit(method.Type())
411 }
412 for etyp := range t.EmbeddedTypes() {
413 visit(etyp)
414 }
415 case *types.Union:
416 for term := range t.Terms() {
417 visit(term.Type())
418 }
419 case *types.Signature:
420 if tp := t.TypeParams(); tp != nil {
421 // Generic signatures only appear as the type of generic
422 // function or method declarations, so this isn't really
423 // reachable.
424 for tparam := range tp.TypeParams() {
425 visit(tparam.Constraint())
426 }
427 }
428 visit(t.Params())
429 visit(t.Results())
430 case *types.Tuple:
431 for v := range t.Variables() {
432 visit(v.Type())
433 }
434 case *types.Struct:
435 for field := range t.Fields() {
436 visit(field.Type())
437 }
438 case *types.TypeParam:
439 free[t] = true
440 case *types.Alias:
441 visit(types.Unalias(t))
442 case *types.Named:
443 targs := t.TypeArgs()
444 for t0 := range targs.Types() {
445 visit(t0)
446 }
447 case *types.Basic:
448 // nop
449 default:
450 panic(t)
451 }
452 }
453
454 visit(sig.Params())
455
456 // Perform induction through constraints.
457 restart:
458 for tp := range sig.TypeParams().TypeParams() {
459 if free[tp] {
460 n := len(free)
461 visit(tp.Constraint())
462 if len(free) > n {
463 goto restart // iterate until fixed point
464 }
465 }
466 }
467 return free
468 }