Debian Codegraph @

gopls/internal/analysis/fillstruct/fillstruct.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 fillstruct defines an Analyzer that automatically
6 // fills in a struct declaration with zero value elements for each field.
7 //
8 // The analyzer's diagnostic is merely a prompt.
9 // The actual fix is created by a separate direct call from gopls to
10 // the SuggestedFixes function.
11 // Tests of Analyzer.Run can be found in ./testdata/src.
12 // Tests of the SuggestedFixes logic live in ../../testdata/fillstruct.
13 package fillstruct
14
15 import (
16 "bytes"
17 "fmt"
18 "go/ast"
19 "go/format"
20 "go/printer"
21 "go/token"
22 "go/types"
23 "slices"
24 "strings"
25 "unicode"
26
27 "golang.org/x/tools/go/analysis"
28 "golang.org/x/tools/go/ast/inspector"
29 "golang.org/x/tools/gopls/internal/analysis/fillreturns"
30 "golang.org/x/tools/gopls/internal/cache"
31 "golang.org/x/tools/gopls/internal/cache/parsego"
32 "golang.org/x/tools/gopls/internal/fuzzy"
33 "golang.org/x/tools/gopls/internal/util/cursorutil"
34 "golang.org/x/tools/gopls/internal/util/safetoken"
35 "golang.org/x/tools/internal/astutil"
36 "golang.org/x/tools/internal/typeparams"
37 "golang.org/x/tools/internal/typesinternal"
38 "golang.org/x/tools/internal/versions"
39 )
40
41 // Diagnose computes a diagnostic for the enclosing struct literal enclosing
42 // the provided start and end position of curFile.
43 //
44 // If the target struct is already fully populated, no diagnostic is reported.
45 //
46 // The diagnostic contains a lazy fix; the actual patch is computed
47 // (via the ApplyFix command) by a call to [SuggestedFix].
48 func Diagnose(curFile inspector.Cursor, start, end token.Pos, pkg *types.Package, info *types.Info) (diags []analysis.Diagnostic) {
49 cur, _, _, _ := astutil.Select(curFile, start, end)
50
51 // Direct reference to embedded fields in struct literals requires Go 1.27+.
52 var supportsEmbedFields bool
53 if v := info.FileVersions[curFile.Node().(*ast.File)]; v != "" {
54 supportsEmbedFields = versions.AtLeast(v, versions.Go1_27)
55 }
56
57 var lits []*ast.CompositeLit
58 for c := range cur.Enclosing((*ast.CompositeLit)(nil)) {
59 lits = append(lits, c.Node().(*ast.CompositeLit))
60 }
61 for c := range cur.Preorder((*ast.CompositeLit)(nil)) {
62 expr := c.Node().(*ast.CompositeLit)
63 // Avoid double-counting when cur.Node() is itself a [ast.CompositeLit].
64 if expr == cur.Node() {
65 continue
66 }
67 if expr.Pos() <= end && expr.End() >= start {
68 lits = append(lits, expr)
69 }
70 }
71
72 nextComp:
73 for _, expr := range lits {
74 typ := info.TypeOf(expr)
75 if typ == nil {
76 continue
77 }
78
79 // Find reference to the type declaration of the struct being initialized.
80 typ = typeparams.Deref(typ)
81 tStruct, ok := typeparams.CoreType(typ).(*types.Struct)
82 if !ok {
83 continue
84 }
85
86 // Inv: typ is the possibly-named struct type.
87
88 // fillableFields returns the number of fields in the struct that are
89 // accessible and thus can be filled in the current package.
90 fillableFields := func(t *types.Struct) (count int) {
91 for field := range t.Fields() {
92 if field.Pkg() == pkg || field.Exported() {
93 count++
94 }
95 }
96 return count
97 }
98
99 // fieldCount tracks the maximum number of fillable fields under the minimum
100 // required expansion of embedded structs.
101 //
102 // It starts as the number of direct fields of the struct.
103 //
104 // Example structure:
105 // A
106 // ├── A1
107 // ├── A2
108 // └── B (embedded)
109 // ├── B1 (promoted to A)
110 // ├── B2
111 // └── C (embedded)
112 // ├── C1
113 // └── C2
114 //
115 // When a promoted field is filled (e.g., B1 in A{B1: 1}), we expand
116 // fieldCount to include the fields of that embedded struct (B1, B2, C),
117 // while removing the embedded struct B itself from the count.
118 //
119 // This means we need to fill all fields at B's level (B1, B2, C) and
120 // its parent levels (A1, A2), but we don't need to fill B anymore. C
121 // will be filled as C: C{} unless its own fields are accessed.
122 fieldCount := fillableFields(tStruct)
123
124 var seen map[*types.Var]bool
125
126 nextElem:
127 for _, el := range expr.Elts {
128 kv, ok := el.(*ast.KeyValueExpr)
129 if !ok {
130 continue nextComp
131 }
132
133 key, ok := kv.Key.(*ast.Ident)
134 if !ok {
135 continue
136 }
137
138 seln, ok := types.LookupSelection(typ, true, pkg, key.Name)
139 if !ok {
140 continue
141 }
142
143 if len(seln.Index()) > 1 && !supportsEmbedFields {
144 continue
145 }
146
147 length := len(seln.Index())
148 if length == 0 {
149 continue
150 }
151
152 var (
153 fields = make([]*types.Var, length-1)
154 typs = make([]*types.Struct, length-1)
155 )
156
157 i := 0
158 for field := range typesinternal.ImplicitFieldSelections(seln) {
159 t := field.Type()
160 ptr, isPtr := t.Underlying().(*types.Pointer)
161 if isPtr {
162 t = ptr.Elem()
163 }
164 structType, ok := t.Underlying().(*types.Struct)
165 if !ok {
166 continue nextElem
167 }
168
169 fields[i] = field
170 typs[i] = structType
171 i++
172 }
173
174 for i, field := range fields {
175 if !seen[field] {
176 if seen == nil {
177 seen = make(map[*types.Var]bool)
178 }
179 seen[field] = true
180 fieldCount += fillableFields(typs[i]) - 1
181 }
182 }
183 }
184
185 // Skip any struct that is already populated or that has no fillable fields.
186 if fieldCount == 0 || fieldCount == len(expr.Elts) {
187 continue
188 }
189
190 // Derive a name for the struct type.
191 var name string
192 if typ != tStruct {
193 // named struct type (e.g. pkg.S[T])
194 name = types.TypeString(typ, typesinternal.NameRelativeTo(pkg))
195 } else {
196 // anonymous struct type
197 var buf strings.Builder
198 buf.WriteString("anonymous struct{ ")
199
200 var printedCount int
201
202 for field := range tStruct.Fields() {
203 if field.Pkg() == pkg || field.Exported() {
204 if buf.Len() > 38 || printedCount > 3 {
205 buf.WriteString("...")
206 break
207 }
208 fmt.Fprintf(&buf, "%s: %s; ", field.Name(), field.Type().String())
209 printedCount++
210 }
211 }
212
213 buf.WriteString(" }")
214 name = buf.String()
215 }
216
217 diags = append(diags, analysis.Diagnostic{
218 Message: fmt.Sprintf("%s literal has missing fields", name),
219 Pos: expr.Pos(),
220 End: expr.End(),
221 Category: FixCategory,
222 SuggestedFixes: []analysis.SuggestedFix{{
223 Message: fmt.Sprintf("Fill %s", name),
224 // No TextEdits => computed later by gopls.
225 }},
226 })
227 }
228
229 return diags
230 }
231
232 const FixCategory = "fillstruct" // recognized by gopls ApplyFix
233
234 // SuggestedFix computes the suggested fix for the kinds of
235 // diagnostics produced by the Analyzer above.
236 func SuggestedFix(cpkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) {
237 var (
238 file = pgf.File
239 fset = cpkg.FileSet()
240 pkg = cpkg.Types()
241 info = cpkg.TypesInfo()
242 pos = start // don't use end
243 )
244 cur, ok := pgf.Cursor().FindByPos(pos, pos)
245 if !ok {
246 return nil, nil, fmt.Errorf("no enclosing ast.Node")
247 }
248 expr, _ := cursorutil.FirstEnclosing[*ast.CompositeLit](cur)
249
250 // newElts accumulates the newly generated field element AST nodes.
251 newElts, err := populateMissingFields(info, pkg, file, expr, pos)
252 if err != nil {
253 return nil, nil, err
254 }
255
256 // If we failed to generate any new fields to fill, we have nothing to do.
257 if len(newElts) == 0 {
258 return nil, nil, fmt.Errorf("no elements to fill")
259 }
260
261 // Find the line on which the composite literal is declared.
262 split := bytes.Split(pgf.Src, []byte("\n"))
263 lineNumber := safetoken.StartPosition(fset, expr.Lbrace).Line
264 firstLine := split[lineNumber-1] // lines are 1-indexed
265
266 // Trim the whitespace from the left of the line, and use the index
267 // to get the amount of whitespace on the left.
268 trimmed := bytes.TrimLeftFunc(firstLine, unicode.IsSpace)
269 index := bytes.Index(firstLine, trimmed)
270 whitespace := firstLine[:index]
271
272 var buf bytes.Buffer
273 buf.WriteString("_{\n")
274 fcmap := ast.NewCommentMap(fset, file, file.Comments)
275 comments := fcmap.Filter(expr).Comments() // comments inside the expr, in source order
276 for _, elt := range slices.Concat(expr.Elts, newElts) {
277 // Print comments before the current elt
278 for len(comments) > 0 && comments[0].Pos() < elt.Pos() {
279 for _, co := range comments[0].List {
280 fmt.Fprintln(&buf, co.Text)
281 }
282 comments = comments[1:]
283 }
284
285 // Print the current elt with comments
286 eltcomments := fcmap.Filter(elt).Comments()
287 if err := format.Node(&buf, fset, &printer.CommentedNode{Node: elt, Comments: eltcomments}); err != nil {
288 return nil, nil, err
289 }
290 buf.WriteString(",")
291
292 // Prune comments up to the end of the elt
293 for len(comments) > 0 && comments[0].Pos() < elt.End() {
294 comments = comments[1:]
295 }
296
297 // Write comments associated with the current elt that appear after it
298 // printer.CommentedNode only prints comments inside the elt.
299 for _, cg := range eltcomments {
300 for _, co := range cg.List {
301 if co.Pos() >= elt.End() {
302 fmt.Fprintln(&buf, co.Text)
303 if len(comments) > 0 {
304 comments = comments[1:]
305 }
306 }
307 }
308 }
309 buf.WriteString("\n")
310 }
311 buf.WriteString("}")
312 formatted, err := format.Source(buf.Bytes())
313 if err != nil {
314 return nil, nil, err
315 }
316
317 sug := indent(formatted, whitespace)
318 // Remove _
319 idx := bytes.IndexByte(sug, '{') // cannot fail
320 sug = sug[idx:]
321
322 return fset, &analysis.SuggestedFix{
323 TextEdits: []analysis.TextEdit{
324 {
325 Pos: expr.Lbrace,
326 End: expr.Rbrace + token.Pos(len("}")),
327 NewText: sug,
328 },
329 },
330 }, nil
331 }
332
333 // populateMissingFields returns a slice of ast.Expr (specifically *ast.KeyValueExpr)
334 // representing the populated missing fields of tStruct that can be filled.
335 //
336 // It traverses the struct fields in depth-first order (DFS), flattening embedded
337 // structs where the user has partially initialized their sub-fields, and attempts
338 // to generate a matching local variable or zero-value for each missing field.
339 // Fields that cannot be populated are skipped, returning only the ones that can
340 // be successfully populated.
341 func populateMissingFields(info *types.Info, pkg *types.Package, file *ast.File, expr *ast.CompositeLit, pos token.Pos) ([]ast.Expr, error) {
342 typ := info.TypeOf(expr)
343 if typ == nil {
344 return nil, fmt.Errorf("no composite literal")
345 }
346
347 // Find reference to the type declaration of the struct being initialized.
348 typ = typeparams.Deref(typ)
349 tStruct, ok := typ.Underlying().(*types.Struct)
350 if !ok {
351 return nil, fmt.Errorf("%s is not a (pointer to) struct type",
352 types.TypeString(typ, typesinternal.NameRelativeTo(pkg)))
353 }
354
355 // Inv: typ is the possibly-named struct type.
356
357 // Direct reference to embedded fields in struct literals requires Go 1.27+.
358 var supportsEmbedFields bool
359 if v := info.FileVersions[file]; v != "" {
360 supportsEmbedFields = versions.AtLeast(v, versions.Go1_27)
361 }
362
363 // explicit records whether each encountered field is explicitly initialized.
364 // Each non-last field in a selection path is accessed implicitly (false),
365 // and the last field is accessed explicitly (true).
366 // Fields not present in this map are completely missing and need to be populated.
367 explicit := make(map[*types.Var]bool)
368 for _, elem := range expr.Elts {
369 kv, ok := elem.(*ast.KeyValueExpr)
370 if !ok {
371 return nil, fmt.Errorf("cannot fill struct literal containing unkeyed elements")
372 }
373
374 key, ok := kv.Key.(*ast.Ident)
375 if !ok {
376 continue
377 }
378
379 seln, ok := types.LookupSelection(tStruct, true, pkg, key.Name)
380 if !ok {
381 continue
382 }
383
384 if len(seln.Index()) > 1 && !supportsEmbedFields {
385 continue
386 }
387
388 field, ok := seln.Obj().(*types.Var)
389 if !ok {
390 continue
391 }
392
393 isExplicit, ok := explicit[field]
394 if ok && !isExplicit {
395 return nil, fmt.Errorf("cannot fill both %q and its subfields", field.Name())
396 }
397 explicit[field] = true // last field is explicit
398
399 for field := range typesinternal.ImplicitFieldSelections(seln) {
400 if explicit[field] {
401 return nil, fmt.Errorf("cannot fill both %q and its subfields", field.Name())
402 }
403 explicit[field] = false // all the others are implicit
404 }
405 }
406
407 // Collect the final list of fields to be filled. Traverse the struct fields
408 // in depth-first order, flattening embedded fields that are marked for
409 // expansion because the user has partially initialized their sub-fields.
410 var fields []*types.Var
411 {
412 var addFields func(*types.Struct)
413 addFields = func(tStruct *types.Struct) {
414 for field := range tStruct.Fields() {
415 if field.Pkg() != pkg && !field.Exported() {
416 continue
417 }
418
419 isExplicit, ok := explicit[field]
420 if !ok {
421 fields = append(fields, field)
422 continue
423 }
424
425 if !isExplicit {
426 tInner, ok := typeparams.Deref(field.Type()).Underlying().(*types.Struct)
427 if !ok {
428 continue // can't happen
429 }
430 addFields(tInner)
431 }
432 }
433 }
434 addFields(tStruct)
435 }
436
437 typs := make([]types.Type, len(fields))
438 for i, f := range fields {
439 typs[i] = f.Type()
440 }
441
442 var newElts []ast.Expr
443 matches := fillreturns.MatchingIdents(typs, file, pos, info, pkg)
444 qual := typesinternal.FileQualifier(file, pkg)
445
446 // Iterate in the order fields were discovered to ensure deterministic
447 // output and match the struct definition order.
448 for _, field := range fields {
449 // TODO(hxjiang): Provide a separate quick-fix option to fill the
450 // struct using nested composite literals, ensuring we always have a
451 // valid suggestion even if shadowing prevents flattening.
452 if obj, _, _ := types.LookupFieldOrMethod(tStruct, true, pkg, field.Name()); obj != field {
453 return nil, fmt.Errorf("field %s shadowed", field.Name())
454 }
455
456 kv := &ast.KeyValueExpr{
457 Key: ast.NewIdent(field.Name()),
458 }
459
460 names, ok := matches[field.Type()]
461 if !ok {
462 return nil, fmt.Errorf("invalid struct field type: %v", field.Type())
463 }
464
465 // Find the name most similar to the field name.
466 // If no name matches the pattern, generate a zero value.
467 // NOTE: We currently match on the name of the field key rather than the field type.
468 if best := fuzzy.BestMatch(field.Name(), names); best != "" {
469 kv.Value = ast.NewIdent(best)
470 } else if expr, isValid := populateValue(field.Type(), qual); isValid {
471 kv.Value = expr
472 } else {
473 continue
474 }
475
476 newElts = append(newElts, kv)
477 }
478 return newElts, nil
479 }
480
481 // indent works line by line through str, indenting (prefixing) each line with
482 // ind.
483 func indent(str, ind []byte) []byte {
484 split := bytes.Split(str, []byte("\n"))
485 newText := bytes.NewBuffer(nil)
486 for i, s := range split {
487 if len(s) == 0 {
488 continue
489 }
490 // Don't add the extra indentation to the first line.
491 if i != 0 {
492 newText.Write(ind)
493 }
494 newText.Write(s)
495 if i < len(split)-1 {
496 newText.WriteByte('\n')
497 }
498 }
499 return newText.Bytes()
500 }
501
502 // populateValue constructs an expression to fill the value of a struct field.
503 //
504 // When the type of a struct field is a basic literal or interface, we return
505 // default values. For other types, such as maps, slices, and channels, we create
506 // empty expressions such as []T{} or make(chan T) rather than using default values.
507 //
508 // The reasoning here is that users will call fillstruct with the intention of
509 // initializing the struct, in which case setting these fields to nil has no effect.
510 //
511 // If the input contains an invalid type, populateValue may panic or return
512 // expression that may not compile.
513 func populateValue(typ types.Type, qual types.Qualifier) (_ ast.Expr, isValid bool) {
514 switch t := typ.(type) {
515 case *types.TypeParam, *types.Interface, *types.Struct, *types.Basic:
516 return typesinternal.ZeroExpr(t, qual)
517
518 case *types.Alias, *types.Named:
519 switch t.Underlying().(type) {
520 // Avoid typesinternal.ZeroExpr here as we don't want to return nil.
521 case *types.Map, *types.Slice:
522 return &ast.CompositeLit{
523 Type: typesinternal.TypeExpr(t, qual),
524 }, true
525 default:
526 return typesinternal.ZeroExpr(t, qual)
527 }
528
529 // Avoid typesinternal.ZeroExpr here as we don't want to return nil.
530 case *types.Map, *types.Slice:
531 return &ast.CompositeLit{
532 Type: typesinternal.TypeExpr(t, qual),
533 }, true
534
535 case *types.Array:
536 return &ast.CompositeLit{
537 Type: &ast.ArrayType{
538 Elt: typesinternal.TypeExpr(t.Elem(), qual),
539 Len: &ast.BasicLit{
540 Kind: token.INT, Value: fmt.Sprintf("%v", t.Len()),
541 },
542 },
543 }, true
544
545 case *types.Chan:
546 dir := ast.ChanDir(t.Dir())
547 if t.Dir() == types.SendRecv {
548 dir = ast.SEND | ast.RECV
549 }
550 return &ast.CallExpr{
551 Fun: ast.NewIdent("make"),
552 Args: []ast.Expr{
553 &ast.ChanType{
554 Dir: dir,
555 Value: typesinternal.TypeExpr(t.Elem(), qual),
556 },
557 },
558 }, true
559
560 case *types.Signature:
561 return &ast.FuncLit{
562 Type: typesinternal.TypeExpr(t, qual).(*ast.FuncType),
563 // The body of the function literal contains a panic statement to
564 // avoid type errors.
565 Body: &ast.BlockStmt{
566 List: []ast.Stmt{
567 &ast.ExprStmt{
568 X: &ast.CallExpr{
569 Fun: ast.NewIdent("panic"),
570 Args: []ast.Expr{
571 &ast.BasicLit{
572 Kind: token.STRING,
573 Value: `"TODO"`,
574 },
575 },
576 },
577 },
578 },
579 },
580 }, true
581
582 case *types.Pointer:
583 switch tt := types.Unalias(t.Elem()).(type) {
584 case *types.Basic:
585 return &ast.CallExpr{
586 Fun: &ast.Ident{
587 Name: "new",
588 },
589 Args: []ast.Expr{
590 &ast.Ident{
591 Name: t.Elem().String(),
592 },
593 },
594 }, true
595 // Pointer to type parameter should return new(T) instead of &*new(T).
596 case *types.TypeParam:
597 return &ast.CallExpr{
598 Fun: &ast.Ident{
599 Name: "new",
600 },
601 Args: []ast.Expr{
602 &ast.Ident{
603 Name: tt.Obj().Name(),
604 },
605 },
606 }, true
607 default:
608 // TODO(hxjiang): & prefix only works if populateValue returns a
609 // composite literal T{} or the expression new(T).
610 expr, isValid := populateValue(t.Elem(), qual)
611 return &ast.UnaryExpr{
612 Op: token.AND,
613 X: expr,
614 }, isValid
615 }
616 }
617 return nil, false
618 }