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.
5 // Package fillstruct defines an Analyzer that automatically
6 // fills in a struct declaration with zero value elements for each field.
18 "golang.org/x/tools/go/analysis"
19 "golang.org/x/tools/go/analysis/passes/inspect"
20 "golang.org/x/tools/go/ast/astutil"
21 "golang.org/x/tools/go/ast/inspector"
22 "golang.org/x/tools/internal/analysisinternal"
23 "golang.org/x/tools/internal/span"
26 const Doc = `note incomplete struct initializations
28 This analyzer provides diagnostics for any struct literals that do not have
29 any fields initialized. Because the suggested fix for this analysis is
30 expensive to compute, callers should compute it separately, using the
31 SuggestedFix function below.
34 var Analyzer = &analysis.Analyzer{
37 Requires: []*analysis.Analyzer{inspect.Analyzer},
39 RunDespiteErrors: true,
42 func run(pass *analysis.Pass) (interface{}, error) {
43 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
44 nodeFilter := []ast.Node{(*ast.CompositeLit)(nil)}
45 inspect.Preorder(nodeFilter, func(n ast.Node) {
46 info := pass.TypesInfo
50 expr := n.(*ast.CompositeLit)
52 // TODO: Handle partially-filled structs as well.
53 if len(expr.Elts) != 0 {
58 for _, f := range pass.Files {
59 if f.Pos() <= expr.Pos() && expr.Pos() <= f.End() {
68 typ := info.TypeOf(expr)
73 // Find reference to the type declaration of the struct being initialized.
75 p, ok := typ.Underlying().(*types.Pointer)
81 typ = typ.Underlying()
83 obj, ok := typ.(*types.Struct)
87 fieldCount := obj.NumFields()
89 // Skip any struct that is already populated or that has no fields.
90 if fieldCount == 0 || fieldCount == len(expr.Elts) {
94 for i := 0; i < fieldCount; i++ {
97 // Ignore fields that are not accessible in the current package.
98 if field.Pkg() != nil && field.Pkg() != pass.Pkg && !field.Exported() {
107 switch typ := expr.Type.(type) {
110 case *ast.SelectorExpr:
111 name = fmt.Sprintf("%s.%s", typ.X, typ.Sel.Name)
113 name = "anonymous struct"
115 pass.Report(analysis.Diagnostic{
116 Message: fmt.Sprintf("Fill %s", name),
124 func SuggestedFix(fset *token.FileSet, rng span.Range, content []byte, file *ast.File, pkg *types.Package, info *types.Info) (*analysis.SuggestedFix, error) {
125 pos := rng.Start // don't use the end
127 // TODO(rstambler): Using ast.Inspect would probably be more efficient than
128 // calling PathEnclosingInterval. Switch this approach.
129 path, _ := astutil.PathEnclosingInterval(file, pos, pos)
131 return nil, fmt.Errorf("no enclosing ast.Node")
133 var expr *ast.CompositeLit
134 for _, n := range path {
135 if node, ok := n.(*ast.CompositeLit); ok {
141 return nil, fmt.Errorf("nil types.Info")
143 typ := info.TypeOf(expr)
145 return nil, fmt.Errorf("no composite literal")
148 // Find reference to the type declaration of the struct being initialized.
150 p, ok := typ.Underlying().(*types.Pointer)
156 typ = typ.Underlying()
158 obj, ok := typ.(*types.Struct)
160 return nil, fmt.Errorf("unexpected type %v (%T), expected *types.Struct", typ, typ)
162 fieldCount := obj.NumFields()
164 // Use a new fileset to build up a token.File for the new composite
165 // literal. We need one line for foo{, one line for }, and one line for
166 // each field we're going to set. format.Node only cares about line
167 // numbers, so we don't need to set columns, and each line can be
169 fakeFset := token.NewFileSet()
170 tok := fakeFset.AddFile("", -1, fieldCount+2)
172 line := 2 // account for 1-based lines and the left brace
174 var fieldTyps []types.Type
175 for i := 0; i < fieldCount; i++ {
176 field := obj.Field(i)
177 // Ignore fields that are not accessible in the current package.
178 if field.Pkg() != nil && field.Pkg() != pkg && !field.Exported() {
179 fieldTyps = append(fieldTyps, nil)
182 fieldTyps = append(fieldTyps, field.Type())
184 matches := analysisinternal.FindMatchingIdents(fieldTyps, file, rng.Start, info, pkg)
185 for i, fieldTyp := range fieldTyps {
189 idents, ok := matches[fieldTyp]
191 return nil, fmt.Errorf("invalid struct field type: %v", fieldTyp)
194 // Find the identifer whose name is most similar to the name of the field's key.
195 // If we do not find any identifer that matches the pattern, generate a new value.
196 // NOTE: We currently match on the name of the field key rather than the field type.
197 value := analysisinternal.FindBestMatch(obj.Field(i).Name(), idents)
199 value = populateValue(fset, file, pkg, fieldTyp)
205 tok.AddLine(line - 1) // add 1 byte per line
206 if line > tok.LineCount() {
207 panic(fmt.Sprintf("invalid line number %v (of %v) for fillstruct", line, tok.LineCount()))
209 pos := tok.LineStart(line)
211 kv := &ast.KeyValueExpr{
214 Name: obj.Field(i).Name(),
219 elts = append(elts, kv)
223 // If all of the struct's fields are unexported, we have nothing to do.
225 return nil, fmt.Errorf("no elements to fill")
228 // Add the final line for the right brace. Offset is the number of
229 // bytes already added plus 1.
230 tok.AddLine(len(elts) + 1)
232 if line > tok.LineCount() {
233 panic(fmt.Sprintf("invalid line number %v (of %v) for fillstruct", line, tok.LineCount()))
236 cl := &ast.CompositeLit{
238 Lbrace: tok.LineStart(1),
240 Rbrace: tok.LineStart(line),
243 // Find the line on which the composite literal is declared.
244 split := bytes.Split(content, []byte("\n"))
245 lineNumber := fset.Position(expr.Lbrace).Line
246 firstLine := split[lineNumber-1] // lines are 1-indexed
248 // Trim the whitespace from the left of the line, and use the index
249 // to get the amount of whitespace on the left.
250 trimmed := bytes.TrimLeftFunc(firstLine, unicode.IsSpace)
251 index := bytes.Index(firstLine, trimmed)
252 whitespace := firstLine[:index]
254 var newExpr bytes.Buffer
255 if err := format.Node(&newExpr, fakeFset, cl); err != nil {
256 return nil, fmt.Errorf("failed to format %s: %v", cl.Type, err)
258 split = bytes.Split(newExpr.Bytes(), []byte("\n"))
259 newText := bytes.NewBuffer(nil)
260 for i, s := range split {
261 // Don't add the extra indentation to the first line.
263 newText.Write(whitespace)
266 if i < len(split)-1 {
267 newText.WriteByte('\n')
270 return &analysis.SuggestedFix{
271 TextEdits: []analysis.TextEdit{
275 NewText: newText.Bytes(),
281 // populateValue constructs an expression to fill the value of a struct field.
283 // When the type of a struct field is a basic literal or interface, we return
284 // default values. For other types, such as maps, slices, and channels, we create
285 // expressions rather than using default values.
287 // The reasoning here is that users will call fillstruct with the intention of
288 // initializing the struct, in which case setting these fields to nil has no effect.
289 func populateValue(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Type) ast.Expr {
291 if n, ok := typ.(*types.Named); ok {
292 under = n.Underlying()
294 switch u := under.(type) {
297 case u.Info()&types.IsNumeric != 0:
298 return &ast.BasicLit{Kind: token.INT, Value: "0"}
299 case u.Info()&types.IsBoolean != 0:
300 return &ast.Ident{Name: "false"}
301 case u.Info()&types.IsString != 0:
302 return &ast.BasicLit{Kind: token.STRING, Value: `""`}
304 panic("unknown basic type")
307 k := analysisinternal.TypeExpr(fset, f, pkg, u.Key())
308 v := analysisinternal.TypeExpr(fset, f, pkg, u.Elem())
309 if k == nil || v == nil {
312 return &ast.CompositeLit{
319 s := analysisinternal.TypeExpr(fset, f, pkg, u.Elem())
323 return &ast.CompositeLit{
324 Type: &ast.ArrayType{
329 a := analysisinternal.TypeExpr(fset, f, pkg, u.Elem())
333 return &ast.CompositeLit{
334 Type: &ast.ArrayType{
337 Kind: token.INT, Value: fmt.Sprintf("%v", u.Len()),
342 v := analysisinternal.TypeExpr(fset, f, pkg, u.Elem())
346 dir := ast.ChanDir(u.Dir())
347 if u.Dir() == types.SendRecv {
348 dir = ast.SEND | ast.RECV
350 return &ast.CallExpr{
351 Fun: ast.NewIdent("make"),
360 s := analysisinternal.TypeExpr(fset, f, pkg, typ)
364 return &ast.CompositeLit{
367 case *types.Signature:
368 var params []*ast.Field
369 for i := 0; i < u.Params().Len(); i++ {
370 p := analysisinternal.TypeExpr(fset, f, pkg, u.Params().At(i).Type())
374 params = append(params, &ast.Field{
378 Name: u.Params().At(i).Name(),
383 var returns []*ast.Field
384 for i := 0; i < u.Results().Len(); i++ {
385 r := analysisinternal.TypeExpr(fset, f, pkg, u.Results().At(i).Type())
389 returns = append(returns, &ast.Field{
395 Params: &ast.FieldList{
398 Results: &ast.FieldList{
402 Body: &ast.BlockStmt{},
405 switch u.Elem().(type) {
407 return &ast.CallExpr{
413 Name: u.Elem().String(),
418 return &ast.UnaryExpr{
420 X: populateValue(fset, f, pkg, u.Elem()),
423 case *types.Interface:
424 return ast.NewIdent("nil")