Debian Codegraph @

gopls/internal/golang/types_format.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 golang
6
7 import (
8 "bytes"
9 "context"
10 "fmt"
11 "go/ast"
12 "go/doc"
13 "go/printer"
14 "go/token"
15 "go/types"
16 "strings"
17
18 "golang.org/x/tools/gopls/internal/cache"
19 "golang.org/x/tools/gopls/internal/protocol"
20 "golang.org/x/tools/gopls/internal/settings"
21 "golang.org/x/tools/gopls/internal/util/bug"
22 "golang.org/x/tools/gopls/internal/util/tokeninternal"
23 "golang.org/x/tools/internal/event"
24 "golang.org/x/tools/internal/typeparams"
25 )
26
27 // FormatType returns the detail and kind for a types.Type.
28 func FormatType(typ types.Type, qual types.Qualifier) (detail string, kind protocol.CompletionItemKind) {
29 typ = typ.Underlying()
30 if types.IsInterface(typ) {
31 detail = "interface{...}"
32 kind = protocol.InterfaceCompletion
33 } else if _, ok := typ.(*types.Struct); ok {
34 detail = "struct{...}"
35 kind = protocol.StructCompletion
36 } else {
37 detail = types.TypeString(typ, qual)
38 kind = protocol.ClassCompletion
39 }
40 return detail, kind
41 }
42
43 type signature struct {
44 name, doc string
45 typeParams, params, results []string
46 variadic bool
47 needResultParens bool
48 }
49
50 func (s *signature) Format() string {
51 var b strings.Builder
52 b.WriteByte('(')
53 for i, p := range s.params {
54 if i > 0 {
55 b.WriteString(", ")
56 }
57 b.WriteString(p)
58 }
59 b.WriteByte(')')
60
61 // Add space between parameters and results.
62 if len(s.results) > 0 {
63 b.WriteByte(' ')
64 }
65 if s.needResultParens {
66 b.WriteByte('(')
67 }
68 for i, r := range s.results {
69 if i > 0 {
70 b.WriteString(", ")
71 }
72 b.WriteString(r)
73 }
74 if s.needResultParens {
75 b.WriteByte(')')
76 }
77 return b.String()
78 }
79
80 func (s *signature) TypeParams() []string {
81 return s.typeParams
82 }
83
84 func (s *signature) Params() []string {
85 return s.params
86 }
87
88 // NewBuiltinSignature returns signature for the builtin object with a given
89 // name, if a builtin object with the name exists.
90 func NewBuiltinSignature(ctx context.Context, s *cache.Snapshot, name string) (*signature, error) {
91 builtin, err := s.BuiltinFile(ctx)
92 if err != nil {
93 return nil, err
94 }
95 obj := builtin.File.Scope.Lookup(name)
96 if obj == nil {
97 return nil, fmt.Errorf("no builtin object for %s", name)
98 }
99 decl, ok := obj.Decl.(*ast.FuncDecl)
100 if !ok {
101 return nil, fmt.Errorf("no function declaration for builtin: %s", name)
102 }
103 if decl.Type == nil {
104 return nil, fmt.Errorf("no type for builtin decl %s", decl.Name)
105 }
106 var variadic bool
107 if decl.Type.Params.List != nil {
108 numParams := len(decl.Type.Params.List)
109 lastParam := decl.Type.Params.List[numParams-1]
110 if _, ok := lastParam.Type.(*ast.Ellipsis); ok {
111 variadic = true
112 }
113 }
114 fset := tokeninternal.FileSetFor(builtin.Tok)
115 params, _ := formatFieldList(ctx, fset, decl.Type.Params, variadic)
116 results, needResultParens := formatFieldList(ctx, fset, decl.Type.Results, false)
117 d := decl.Doc.Text()
118 switch s.Options().HoverKind {
119 case settings.SynopsisDocumentation:
120 d = doc.Synopsis(d)
121 case settings.NoDocumentation:
122 d = ""
123 }
124 return &signature{
125 doc: d,
126 name: name,
127 needResultParens: needResultParens,
128 params: params,
129 results: results,
130 variadic: variadic,
131 }, nil
132 }
133
134 // replacer replaces some synthetic "type classes" used in the builtin file
135 // with their most common constituent type.
136 var replacer = strings.NewReplacer(
137 `ComplexType`, `complex128`,
138 `FloatType`, `float64`,
139 `IntegerType`, `int`,
140 )
141
142 func formatFieldList(ctx context.Context, fset *token.FileSet, list *ast.FieldList, variadic bool) ([]string, bool) {
143 if list == nil {
144 return nil, false
145 }
146 var writeResultParens bool
147 var result []string
148 for i := 0; i < len(list.List); i++ {
149 if i >= 1 {
150 writeResultParens = true
151 }
152 p := list.List[i]
153 cfg := printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 4}
154 b := &bytes.Buffer{}
155 if err := cfg.Fprint(b, fset, p.Type); err != nil {
156 event.Error(ctx, fmt.Sprintf("error printing type %s", types.ExprString(p.Type)), err)
157 continue
158 }
159 typ := replacer.Replace(b.String())
160 if len(p.Names) == 0 {
161 result = append(result, typ)
162 }
163 for _, name := range p.Names {
164 if name.Name != "" {
165 if i == 0 {
166 writeResultParens = true
167 }
168 result = append(result, fmt.Sprintf("%s %s", name.Name, typ))
169 } else {
170 result = append(result, typ)
171 }
172 }
173 }
174 if variadic {
175 result[len(result)-1] = strings.Replace(result[len(result)-1], "[]", "...", 1)
176 }
177 return result, writeResultParens
178 }
179
180 // NewSignature returns formatted signature for a types.Signature struct.
181 func NewSignature(ctx context.Context, s *cache.Snapshot, pkg *cache.Package, sig *types.Signature, comment *ast.CommentGroup, qual types.Qualifier, mq MetadataQualifier) (*signature, error) {
182 var tparams []string
183 tpList := sig.TypeParams()
184 for tparam := range tpList.TypeParams() {
185 // TODO: is it possible to reuse the logic from FormatVarType here?
186 s := tparam.Obj().Name() + " " + tparam.Constraint().String()
187 tparams = append(tparams, s)
188 }
189
190 params := make([]string, 0, sig.Params().Len())
191 for i := 0; i < sig.Params().Len(); i++ {
192 el := sig.Params().At(i)
193 typ, err := FormatVarType(ctx, s, pkg, el, qual, mq)
194 if err != nil {
195 return nil, err
196 }
197 if sig.Variadic() && i == sig.Params().Len()-1 {
198 typ = strings.Replace(typ, "[]", "...", 1)
199 }
200 p := typ
201 if el.Name() != "" {
202 p = el.Name() + " " + typ
203 }
204 params = append(params, p)
205 }
206
207 var needResultParens bool
208 results := make([]string, 0, sig.Results().Len())
209 for i := 0; i < sig.Results().Len(); i++ {
210 if i >= 1 {
211 needResultParens = true
212 }
213 el := sig.Results().At(i)
214 typ, err := FormatVarType(ctx, s, pkg, el, qual, mq)
215 if err != nil {
216 return nil, err
217 }
218 if el.Name() == "" {
219 results = append(results, typ)
220 } else {
221 if i == 0 {
222 needResultParens = true
223 }
224 results = append(results, el.Name()+" "+typ)
225 }
226 }
227 var d string
228 if comment != nil {
229 d = comment.Text()
230 }
231 switch s.Options().HoverKind {
232 case settings.SynopsisDocumentation:
233 d = doc.Synopsis(d)
234 case settings.NoDocumentation:
235 d = ""
236 }
237 return &signature{
238 doc: d,
239 typeParams: tparams,
240 params: params,
241 results: results,
242 variadic: sig.Variadic(),
243 needResultParens: needResultParens,
244 }, nil
245 }
246
247 // We look for 'invalidTypeString' to determine if we can use the fast path for
248 // FormatVarType.
249 var invalidTypeString = types.Typ[types.Invalid].String()
250
251 // FormatVarType formats a *types.Var, accounting for type aliases.
252 // To do this, it looks in the AST of the file in which the object is declared.
253 // On any errors, it always falls back to types.TypeString.
254 //
255 // TODO(rfindley): this function could return the actual name used in syntax,
256 // for better parameter names.
257 func FormatVarType(ctx context.Context, snapshot *cache.Snapshot, srcpkg *cache.Package, obj *types.Var, qual types.Qualifier, mq MetadataQualifier) (string, error) {
258 typeString := types.TypeString(obj.Type(), qual)
259 // Fast path: if the type string does not contain 'invalid type', we no
260 // longer need to do any special handling, thanks to materialized aliases in
261 // Go 1.23+.
262 //
263 // Unfortunately, due to the handling of invalid types, we can't quite delete
264 // the rather complicated preexisting logic of FormatVarType--it isn't an
265 // acceptable regression to start printing "invalid type" in completion or
266 // signature help. strings.Contains is conservative: the type string of a
267 // valid type may actually contain "invalid type" (due to struct tags or
268 // field formatting), but such cases should be exceedingly rare.
269 if !strings.Contains(typeString, invalidTypeString) {
270 return typeString, nil
271 }
272
273 // TODO(rfindley): This looks wrong. The previous comment said:
274 // "If the given expr refers to a type parameter, then use the
275 // object's Type instead of the type parameter declaration. This helps
276 // format the instantiated type as opposed to the original undeclared
277 // generic type".
278 //
279 // But of course, if obj is a type param, we are formatting a generic type
280 // and not an instantiated type. Handling for instantiated types must be done
281 // at a higher level.
282 //
283 // Left this during refactoring in order to preserve pre-existing logic.
284 if typeparams.IsTypeParam(obj.Type()) {
285 return typeString, nil
286 }
287
288 if isBuiltin(obj) {
289 // This is defensive, though it is extremely unlikely we'll ever have a
290 // builtin var.
291 return typeString, nil
292 }
293
294 // TODO(rfindley): parsing to produce candidates can be costly; consider
295 // using faster methods.
296 targetpgf, pos, err := parseFull(ctx, snapshot, srcpkg.FileSet(), obj)
297 if err != nil {
298 return "", err // e.g. ctx cancelled
299 }
300
301 targetMeta := findFileInDeps(snapshot, srcpkg.Metadata(), targetpgf.URI)
302 if targetMeta == nil {
303 // If we have an object from type-checking, it should exist in a file in
304 // the forward transitive closure.
305 return "", bug.Errorf("failed to find file %q in deps of %q", targetpgf.URI, srcpkg.Metadata().ID)
306 }
307
308 decl, spec, field, _ := findDeclInfo([]*ast.File{targetpgf.File}, pos)
309
310 // We can't handle type parameters correctly, so we fall back on TypeString
311 // for parameterized decls.
312 if decl, _ := decl.(*ast.FuncDecl); decl != nil {
313 if decl.Type.TypeParams.NumFields() > 0 {
314 return typeString, nil // in generic function
315 }
316 if decl.Recv != nil && len(decl.Recv.List) > 0 {
317 rtype := decl.Recv.List[0].Type
318 if e, ok := rtype.(*ast.StarExpr); ok {
319 rtype = e.X
320 }
321 if x, _, _, _ := typeparams.UnpackIndexExpr(rtype); x != nil {
322 return typeString, nil // in method of generic type
323 }
324 }
325 }
326 if spec, _ := spec.(*ast.TypeSpec); spec != nil && spec.TypeParams.NumFields() > 0 {
327 return typeString, nil // in generic type decl
328 }
329
330 if field == nil {
331 // TODO(rfindley): we should never reach here from an ordinary var, so
332 // should probably return an error here.
333 return typeString, nil
334 }
335 expr := field.Type
336
337 rq := requalifier(snapshot, targetpgf.File, targetMeta, mq)
338
339 // The type names in the AST may not be correctly qualified.
340 // Determine the package name to use based on the package that originated
341 // the query and the package in which the type is declared.
342 // We then qualify the value by cloning the AST node and editing it.
343 expr = qualifyTypeExpr(expr, rq)
344
345 // If the request came from a different package than the one in which the
346 // types are defined, we may need to modify the qualifiers.
347 return formatNodeFile(targetpgf.Tok, expr), nil
348 }
349
350 // qualifyTypeExpr clones the type expression expr after re-qualifying type
351 // names using the given function, which accepts the current syntactic
352 // qualifier (possibly "" for unqualified idents), and returns a new qualifier
353 // (again, possibly "" if the identifier should be unqualified).
354 //
355 // The resulting expression may be inaccurate: without type-checking we don't
356 // properly account for "." imported identifiers or builtins.
357 //
358 // TODO(rfindley): add many more tests for this function.
359 func qualifyTypeExpr(expr ast.Expr, qf func(string) string) ast.Expr {
360 switch expr := expr.(type) {
361 case *ast.ArrayType:
362 return &ast.ArrayType{
363 Lbrack: expr.Lbrack,
364 Elt: qualifyTypeExpr(expr.Elt, qf),
365 Len: expr.Len,
366 }
367
368 case *ast.BinaryExpr:
369 if expr.Op != token.OR {
370 return expr
371 }
372 return &ast.BinaryExpr{
373 X: qualifyTypeExpr(expr.X, qf),
374 OpPos: expr.OpPos,
375 Op: expr.Op,
376 Y: qualifyTypeExpr(expr.Y, qf),
377 }
378
379 case *ast.ChanType:
380 return &ast.ChanType{
381 Arrow: expr.Arrow,
382 Begin: expr.Begin,
383 Dir: expr.Dir,
384 Value: qualifyTypeExpr(expr.Value, qf),
385 }
386
387 case *ast.Ellipsis:
388 return &ast.Ellipsis{
389 Ellipsis: expr.Ellipsis,
390 Elt: qualifyTypeExpr(expr.Elt, qf),
391 }
392
393 case *ast.FuncType:
394 return &ast.FuncType{
395 Func: expr.Func,
396 Params: qualifyFieldList(expr.Params, qf),
397 Results: qualifyFieldList(expr.Results, qf),
398 }
399
400 case *ast.Ident:
401 // Unqualified type (builtin, package local, or dot-imported).
402
403 // Don't qualify names that look like builtins.
404 //
405 // Without type-checking this may be inaccurate. It could be made accurate
406 // by doing syntactic object resolution for the entire package, but that
407 // does not seem worthwhile and we generally want to avoid using
408 // ast.Object, which may be inaccurate.
409 if obj := types.Universe.Lookup(expr.Name); obj != nil {
410 return expr
411 }
412
413 newName := qf("")
414 if newName != "" {
415 return &ast.SelectorExpr{
416 X: &ast.Ident{
417 NamePos: expr.Pos(),
418 Name: newName,
419 },
420 Sel: expr,
421 }
422 }
423 return expr
424
425 case *ast.IndexExpr:
426 return &ast.IndexExpr{
427 X: qualifyTypeExpr(expr.X, qf),
428 Lbrack: expr.Lbrack,
429 Index: qualifyTypeExpr(expr.Index, qf),
430 Rbrack: expr.Rbrack,
431 }
432
433 case *ast.IndexListExpr:
434 indices := make([]ast.Expr, len(expr.Indices))
435 for i, idx := range expr.Indices {
436 indices[i] = qualifyTypeExpr(idx, qf)
437 }
438 return &ast.IndexListExpr{
439 X: qualifyTypeExpr(expr.X, qf),
440 Lbrack: expr.Lbrack,
441 Indices: indices,
442 Rbrack: expr.Rbrack,
443 }
444
445 case *ast.InterfaceType:
446 return &ast.InterfaceType{
447 Interface: expr.Interface,
448 Methods: qualifyFieldList(expr.Methods, qf),
449 Incomplete: expr.Incomplete,
450 }
451
452 case *ast.MapType:
453 return &ast.MapType{
454 Map: expr.Map,
455 Key: qualifyTypeExpr(expr.Key, qf),
456 Value: qualifyTypeExpr(expr.Value, qf),
457 }
458
459 case *ast.ParenExpr:
460 return &ast.ParenExpr{
461 Lparen: expr.Lparen,
462 Rparen: expr.Rparen,
463 X: qualifyTypeExpr(expr.X, qf),
464 }
465
466 case *ast.SelectorExpr:
467 if id, ok := expr.X.(*ast.Ident); ok {
468 // qualified type
469 newName := qf(id.Name)
470 if newName == "" {
471 return expr.Sel
472 }
473 return &ast.SelectorExpr{
474 X: &ast.Ident{
475 NamePos: id.NamePos,
476 Name: newName,
477 },
478 Sel: expr.Sel,
479 }
480 }
481 return expr
482
483 case *ast.StarExpr:
484 return &ast.StarExpr{
485 Star: expr.Star,
486 X: qualifyTypeExpr(expr.X, qf),
487 }
488
489 case *ast.StructType:
490 return &ast.StructType{
491 Struct: expr.Struct,
492 Fields: qualifyFieldList(expr.Fields, qf),
493 Incomplete: expr.Incomplete,
494 }
495
496 default:
497 return expr
498 }
499 }
500
501 func qualifyFieldList(fl *ast.FieldList, qf func(string) string) *ast.FieldList {
502 if fl == nil {
503 return nil
504 }
505 if fl.List == nil {
506 return &ast.FieldList{
507 Closing: fl.Closing,
508 Opening: fl.Opening,
509 }
510 }
511 list := make([]*ast.Field, 0, len(fl.List))
512 for _, f := range fl.List {
513 list = append(list, &ast.Field{
514 Comment: f.Comment,
515 Doc: f.Doc,
516 Names: f.Names,
517 Tag: f.Tag,
518 Type: qualifyTypeExpr(f.Type, qf),
519 })
520 }
521 return &ast.FieldList{
522 Closing: fl.Closing,
523 Opening: fl.Opening,
524 List: list,
525 }
526 }