Debian Codegraph @

gopls/internal/golang/inlay_hint.go

raw symbols SCIP
1 // Copyright 2022 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 "cmp"
9 "context"
10 "fmt"
11 "go/ast"
12 "go/constant"
13 "go/token"
14 "go/types"
15 "slices"
16 "strings"
17
18 "golang.org/x/tools/go/ast/inspector"
19 "golang.org/x/tools/go/types/typeutil"
20 "golang.org/x/tools/gopls/internal/cache"
21 "golang.org/x/tools/gopls/internal/cache/parsego"
22 "golang.org/x/tools/gopls/internal/file"
23 "golang.org/x/tools/gopls/internal/protocol"
24 "golang.org/x/tools/gopls/internal/settings"
25 "golang.org/x/tools/gopls/internal/util/safetoken"
26 "golang.org/x/tools/internal/event"
27 "golang.org/x/tools/internal/typeparams"
28 "golang.org/x/tools/internal/typesinternal"
29 )
30
31 func InlayHint(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, pRng protocol.Range) ([]protocol.InlayHint, error) {
32 ctx, done := event.Start(ctx, "golang.InlayHint")
33 defer done()
34
35 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
36 if err != nil {
37 return nil, fmt.Errorf("getting file for InlayHint: %w", err)
38 }
39
40 // Collect a list of the inlay hints that are enabled.
41 inlayHintOptions := snapshot.Options().InlayHintOptions
42 var enabledHints []inlayHintFunc
43 for hint, enabled := range inlayHintOptions.Hints {
44 if !enabled {
45 continue
46 }
47 if fn, ok := allInlayHints[hint]; ok {
48 enabledHints = append(enabledHints, fn)
49 }
50 }
51 if len(enabledHints) == 0 {
52 return nil, nil
53 }
54
55 info := pkg.TypesInfo()
56 qual := typesinternal.FileQualifier(pgf.File, pkg.Types())
57
58 // Set the range to the full file if the range is not valid.
59 start, end := pgf.File.FileStart, pgf.File.FileEnd
60
61 // TODO(adonovan): this condition looks completely wrong!
62 if pRng.Start.Line < pRng.End.Line || pRng.Start.Character < pRng.End.Character {
63 // Adjust start and end for the specified range.
64 var err error
65 start, end, err = pgf.RangePos(pRng)
66 if err != nil {
67 return nil, err
68 }
69 }
70
71 var hints []protocol.InlayHint
72 if curSubrange, ok := pgf.Cursor().FindByPos(start, end); ok {
73 add := func(hint protocol.InlayHint) { hints = append(hints, hint) }
74 for _, fn := range enabledHints {
75 fn(info, pgf, qual, curSubrange, add)
76 }
77 }
78 return hints, nil
79 }
80
81 type inlayHintFunc func(info *types.Info, pgf *parsego.File, qual types.Qualifier, cur inspector.Cursor, add func(protocol.InlayHint))
82
83 var allInlayHints = map[settings.InlayHint]inlayHintFunc{
84 settings.AssignVariableTypes: assignVariableTypes,
85 settings.ConstantValues: constantValues,
86 settings.ParameterNames: parameterNames,
87 settings.RangeVariableTypes: rangeVariableTypes,
88 settings.CompositeLiteralTypes: compositeLiteralTypes,
89 settings.CompositeLiteralFieldNames: compositeLiteralFields,
90 settings.FunctionTypeParameters: funcTypeParams,
91 settings.IgnoredError: ignoredError,
92 }
93
94 func parameterNames(info *types.Info, pgf *parsego.File, qual types.Qualifier, cur inspector.Cursor, add func(protocol.InlayHint)) {
95 for curCall := range cur.Preorder((*ast.CallExpr)(nil)) {
96 callExpr := curCall.Node().(*ast.CallExpr)
97 t := info.TypeOf(callExpr.Fun)
98 if t == nil {
99 continue
100 }
101 signature, ok := typeparams.CoreType(t).(*types.Signature)
102 if !ok {
103 continue
104 }
105
106 for i, v := range callExpr.Args {
107 start, err := pgf.PosPosition(v.Pos())
108 if err != nil {
109 continue
110 }
111 params := signature.Params()
112 // When a function has variadic params, we skip args after
113 // params.Len().
114 if i > params.Len()-1 {
115 break
116 }
117 param := params.At(i)
118 // param.Name is empty for built-ins like append
119 if param.Name() == "" {
120 continue
121 }
122 // Skip the parameter name hint if the arg matches
123 // the parameter name.
124 if i, ok := v.(*ast.Ident); ok && i.Name == param.Name() {
125 continue
126 }
127
128 label := param.Name()
129 if signature.Variadic() && i == params.Len()-1 {
130 label = label + "..."
131 }
132 add(protocol.InlayHint{
133 Position: start,
134 Label: labelPart(label + ":"),
135 Kind: protocol.Parameter,
136 PaddingRight: true,
137 })
138 }
139 }
140 }
141
142 func ignoredError(info *types.Info, pgf *parsego.File, qual types.Qualifier, cur inspector.Cursor, add func(protocol.InlayHint)) {
143 outer:
144 for curCall := range cur.Preorder((*ast.ExprStmt)(nil)) {
145 stmt := curCall.Node().(*ast.ExprStmt)
146 call, ok := stmt.X.(*ast.CallExpr)
147 if !ok {
148 continue // not a call stmt
149 }
150
151 // Check that type of result (or last component) is error.
152 tv, ok := info.Types[call]
153 if !ok {
154 continue // no type info
155 }
156 t := tv.Type
157 if res, ok := t.(*types.Tuple); ok && res.Len() > 1 {
158 t = res.At(res.Len() - 1).Type()
159 }
160 if !types.Identical(t, errorType) {
161 continue
162 }
163
164 // Suppress some common false positives.
165 obj := typeutil.Callee(info, call)
166 if typesinternal.IsFunctionNamed(obj, "fmt", "Print", "Printf", "Println", "Fprint", "Fprintf", "Fprintln") ||
167 typesinternal.IsMethodNamed(obj, "bytes", "Buffer", "Write", "WriteByte", "WriteRune", "WriteString") ||
168 typesinternal.IsMethodNamed(obj, "strings", "Builder", "Write", "WriteByte", "WriteRune", "WriteString") ||
169 typesinternal.IsFunctionNamed(obj, "io", "WriteString") {
170 continue
171 }
172
173 // Suppress if comment on same line contains "// ignore error".
174 line := func(pos token.Pos) int { return safetoken.Line(pgf.Tok, pos) }
175 comments := pgf.File.Comments
176 compare := func(cg *ast.CommentGroup, pos token.Pos) int {
177 return cmp.Compare(cg.Pos(), pos)
178 }
179 i, _ := slices.BinarySearchFunc(comments, stmt.End(), compare)
180 if i >= 0 && i < len(comments) {
181 cg := comments[i]
182 if line(cg.Pos()) == line(stmt.End()) && strings.Contains(cg.Text(), "ignore error") {
183 continue outer // suppress
184 }
185 }
186
187 // Provide a hint.
188 pos, err := pgf.PosPosition(stmt.End())
189 if err != nil {
190 continue
191 }
192 add(protocol.InlayHint{
193 Position: pos,
194 Label: labelPart(" // ignore error"),
195 })
196 }
197 }
198
199 func funcTypeParams(info *types.Info, pgf *parsego.File, qual types.Qualifier, cur inspector.Cursor, add func(protocol.InlayHint)) {
200 for curCall := range cur.Preorder((*ast.CallExpr)(nil)) {
201 call := curCall.Node().(*ast.CallExpr)
202 id, ok := call.Fun.(*ast.Ident)
203 if !ok {
204 continue
205 }
206 inst := info.Instances[id]
207 if inst.TypeArgs == nil {
208 continue
209 }
210 start, err := pgf.PosPosition(id.End())
211 if err != nil {
212 continue
213 }
214 var args []string
215 for t := range inst.TypeArgs.Types() {
216 args = append(args, t.String())
217 }
218 if len(args) == 0 {
219 continue
220 }
221 add(protocol.InlayHint{
222 Position: start,
223 Label: labelPart("[" + strings.Join(args, ", ") + "]"),
224 Kind: protocol.Type,
225 })
226 }
227 }
228
229 func assignVariableTypes(info *types.Info, pgf *parsego.File, qual types.Qualifier, cur inspector.Cursor, add func(protocol.InlayHint)) {
230 for cur := range cur.Preorder((*ast.AssignStmt)(nil), (*ast.ValueSpec)(nil)) {
231 switch node := cur.Node().(type) {
232 case *ast.AssignStmt:
233 if node.Tok == token.DEFINE {
234 for _, lhs := range node.Lhs {
235 variableType(info, pgf, qual, lhs, add)
236 }
237 }
238 case *ast.ValueSpec:
239 if cur.Parent().Node().(*ast.GenDecl).Tok == token.VAR && node.Type == nil { // type not already explicit
240 for _, id := range node.Names {
241 variableType(info, pgf, qual, id, add)
242 }
243 }
244 }
245 }
246 }
247
248 func rangeVariableTypes(info *types.Info, pgf *parsego.File, qual types.Qualifier, cur inspector.Cursor, add func(protocol.InlayHint)) {
249 for curRange := range cur.Preorder((*ast.RangeStmt)(nil)) {
250 rStmt := curRange.Node().(*ast.RangeStmt)
251 variableType(info, pgf, qual, rStmt.Key, add)
252 variableType(info, pgf, qual, rStmt.Value, add)
253 }
254 }
255
256 func variableType(info *types.Info, pgf *parsego.File, qual types.Qualifier, e ast.Expr, add func(protocol.InlayHint)) {
257 typ := info.TypeOf(e)
258 if typ == nil {
259 return
260 }
261 end, err := pgf.PosPosition(e.End())
262 if err != nil {
263 return
264 }
265 add(protocol.InlayHint{
266 Position: end,
267 Label: labelPart(types.TypeString(typ, qual)),
268 Kind: protocol.Type,
269 PaddingLeft: true,
270 })
271 }
272
273 func constantValues(info *types.Info, pgf *parsego.File, qual types.Qualifier, cur inspector.Cursor, add func(protocol.InlayHint)) {
274 for curDecl := range cur.Preorder((*ast.GenDecl)(nil)) {
275 genDecl := curDecl.Node().(*ast.GenDecl)
276 if genDecl.Tok != token.CONST {
277 continue
278 }
279
280 for _, v := range genDecl.Specs {
281 spec, ok := v.(*ast.ValueSpec)
282 if !ok {
283 continue
284 }
285 end, err := pgf.PosPosition(v.End())
286 if err != nil {
287 continue
288 }
289 // Show hints when values are missing or at least one value is not
290 // a basic literal.
291 showHints := len(spec.Values) == 0
292 checkValues := len(spec.Names) == len(spec.Values)
293 var values []string
294 for i, w := range spec.Names {
295 obj, ok := info.ObjectOf(w).(*types.Const)
296 if !ok || obj.Val().Kind() == constant.Unknown {
297 continue
298 }
299 if checkValues {
300 switch spec.Values[i].(type) {
301 case *ast.BadExpr:
302 continue
303 case *ast.BasicLit:
304 default:
305 if obj.Val().Kind() != constant.Bool {
306 showHints = true
307 }
308 }
309 }
310 values = append(values, fmt.Sprintf("%v", obj.Val()))
311 }
312 if !showHints || len(values) == 0 {
313 continue
314 }
315 add(protocol.InlayHint{
316 Position: end,
317 Label: labelPart("= " + strings.Join(values, ", ")),
318 PaddingLeft: true,
319 })
320 }
321 }
322 }
323
324 func compositeLiteralFields(info *types.Info, pgf *parsego.File, qual types.Qualifier, cur inspector.Cursor, add func(protocol.InlayHint)) {
325 for curCompLit := range cur.Preorder((*ast.CompositeLit)(nil)) {
326 compLit := curCompLit.Node().(*ast.CompositeLit)
327 typ := info.TypeOf(compLit)
328 if typ == nil {
329 continue
330 }
331 strct, ok := typeparams.CoreType(typesinternal.Unpointer(typ)).(*types.Struct)
332 if !ok {
333 continue
334 }
335
336 var (
337 hints []protocol.InlayHint
338 allEdits []protocol.TextEdit
339 label strings.Builder
340 )
341 for i, v := range compLit.Elts {
342 label.Reset()
343 pad := false
344 if kv, ok := v.(*ast.KeyValueExpr); ok {
345 // keyed field: show implicit field selections
346 if id, ok := kv.Key.(*ast.Ident); ok {
347 // For some reason an inlayHintFunc
348 // doesn't get the current types.Package.
349 // Use the package of the explicit field.
350 var pkg *types.Package
351 if obj, ok := info.Uses[id]; ok {
352 pkg = obj.Pkg()
353 }
354
355 if seln, ok := types.LookupSelection(strct, true, pkg, id.Name); ok {
356 for field := range typesinternal.ImplicitFieldSelections(seln) {
357 label.WriteString(field.Name())
358 label.WriteByte('.')
359 }
360 }
361 }
362 } else {
363 // unkeyed field: show key based on index
364 if i < strct.NumFields() {
365 label.WriteString(strct.Field(i).Name())
366 label.WriteByte(':')
367 pad = true
368 }
369 }
370 if label.Len() == 0 {
371 continue
372 }
373 labelStr := label.String()
374
375 start, err := pgf.PosPosition(v.Pos())
376 if err != nil {
377 continue
378 }
379 hints = append(hints, protocol.InlayHint{
380 Position: start,
381 Label: labelPart(labelStr),
382 Kind: protocol.Parameter,
383 PaddingRight: pad,
384 })
385 allEdits = append(allEdits, protocol.TextEdit{
386 Range: protocol.Range{Start: start, End: start},
387 NewText: labelStr,
388 })
389 }
390
391 // It is not allowed to have a mix of keyed and unkeyed fields, so
392 // have the text edits add keys to all fields.
393 for i := range hints {
394 hints[i].TextEdits = allEdits
395 add(hints[i])
396 }
397 }
398 }
399
400 func compositeLiteralTypes(info *types.Info, pgf *parsego.File, qual types.Qualifier, cur inspector.Cursor, add func(protocol.InlayHint)) {
401 for curCompLit := range cur.Preorder((*ast.CompositeLit)(nil)) {
402 compLit := curCompLit.Node().(*ast.CompositeLit)
403 typ := info.TypeOf(compLit)
404 if typ == nil {
405 continue
406 }
407 if compLit.Type != nil {
408 continue
409 }
410 prefix := ""
411 if t, ok := typeparams.CoreType(typ).(*types.Pointer); ok {
412 typ = t.Elem()
413 prefix = "&"
414 }
415 // The type for this composite literal is implicit, add an inlay hint.
416 start, err := pgf.PosPosition(compLit.Lbrace)
417 if err != nil {
418 continue
419 }
420 add(protocol.InlayHint{
421 Position: start,
422 Label: labelPart(fmt.Sprintf("%s%s", prefix, types.TypeString(typ, qual))),
423 Kind: protocol.Type,
424 })
425 }
426 }
427
428 func labelPart(s string) []protocol.InlayHintLabelPart {
429 const maxLabelLength = 28
430 if len(s) > maxLabelLength+len("...") {
431 s = s[:maxLabelLength] + "..."
432 }
433 return []protocol.InlayHintLabelPart{{Value: s}}
434 }