/
structinit.go
304 lines (225 loc) · 6.32 KB
/
structinit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package structinit
import (
"go/ast"
"go/token"
"go/types"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
var Analyzer = &analysis.Analyzer{
Name: "structinit",
Doc: "Checks that structs with tagged declarations have all their values initialized in a struct literal.",
Run: run,
Requires: []*analysis.Analyzer{inspect.Analyzer},
}
type visitor struct {
Report func(analysis.Diagnostic)
TypeOf func(ast.Expr) types.Type
PackagePath string
}
type Set map[string]struct{}
func run(pass *analysis.Pass) (interface{}, error) {
inspector := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
filter := []ast.Node{
(*ast.CompositeLit)(nil),
}
v := visitor{
Report: pass.Report,
TypeOf: pass.TypesInfo.TypeOf,
PackagePath: pass.Pkg.Path(),
}
inspector.WithStack(filter, v.visit)
return nil, nil
}
func (v visitor) visit(n ast.Node, push bool, stack []ast.Node) bool {
if !push {
return false
}
lit, ok := n.(*ast.CompositeLit)
if !ok {
return true
}
typ := v.TypeOf(lit.Type)
if typ == nil {
return true
}
sTyp, ok := typ.Underlying().(*types.Struct)
if !ok {
return true
}
tag := findTag(stack)
if tag == nil {
return true
}
isExhaustive, omitMap := parseTag(tag.Text)
if !isExhaustive {
return true
}
// qualified name for the type, including package name
typName := typ.String()
// if the type is local to the package being scanned
// if the type is not local, we should ignore private fields in the struct type
var validatePrivate bool
if strings.HasPrefix(typName, v.PackagePath) {
typeSuffix := strings.TrimPrefix(typName, v.PackagePath)
// if there is a slash in the type suffix, means that it's imported from a subpackage
// rather than local to the current package
validatePrivate = !strings.HasPrefix(typeSuffix, "/")
}
typeFields := getTypeFields(sTyp, validatePrivate)
// slice of fields that the tag omits
// but that are not valid fields re: the type of struct being analyzed
var invalidOmittedFields []string
for field := range omitMap {
if _, ok := typeFields[field]; !ok {
invalidOmittedFields = append(invalidOmittedFields, field)
}
}
if len(invalidOmittedFields) > 0 {
diagnostic := buildInvalidOmitDiagnostic(n, typName, invalidOmittedFields)
v.Report(diagnostic)
}
litFields := getLiteralFields(lit)
var missing []string
for field := range typeFields {
if _, omit := omitMap[field]; omit {
continue
}
_, present := litFields[field]
if !present {
missing = append(missing, field)
}
}
if len(missing) == 0 {
return true
}
diagnostic := buildDiagnostic(n, typName, missing)
v.Report(diagnostic)
return true
}
func findTag(stack []ast.Node) *ast.Comment {
var genDecl *ast.GenDecl
// traverse from end of list backwards until first GenDecl is found
for i := len(stack) - 1; i >= 0; i-- {
n := stack[i]
decl, ok := n.(*ast.GenDecl)
if !ok {
continue
}
// must be a var declaration, not a const/import/type
if decl.Tok != token.VAR {
continue
}
genDecl = decl
break
}
// if no GenDecl encountered, is probably an error
// but we can't detect if its exhaustive without this node
// since it has the ast.Comment with the exhaustive tag attached to it
// so return false, i.e. is not exhaustive
if genDecl == nil {
return nil
}
if genDecl.Doc == nil {
return nil
}
// last comment in the general decl should have the exhaustive tag
numDocs := len(genDecl.Doc.List)
return genDecl.Doc.List[numDocs-1]
}
const tag = "//structinit:exhaustive"
// from the text in ast.Comment, returns if the struct should be validated for exhaustiveness
// and if there are any fields that should be omitted from the exhaustiveness checks
// text passed in has two leading slashes from the inline comment
func parseTag(text string) (bool, Set) {
if !strings.HasPrefix(text, tag) {
return false, nil
}
// with no suffix
if text == tag {
return true, nil
}
// if tag has the suffix like `,omit=ID,Name`
// omit the ID and Name fields from exhaustiveness checks
// will always work, since HasPrefix check done above
omit := strings.TrimPrefix(text, tag)
if !strings.HasPrefix(omit, ",omit=") {
return true, nil
}
omitList := strings.TrimPrefix(omit, ",omit=")
omitFields := strings.Split(omitList, ",")
omitMap := make(Set)
for _, field := range omitFields {
omitMap[field] = struct{}{}
}
return true, omitMap
}
// returns the list of fields that are initialized in the composite literal being analyzed
func getLiteralFields(lit *ast.CompositeLit) Set {
fields := make(Set)
for _, el := range lit.Elts {
kve, ok := el.(*ast.KeyValueExpr)
if !ok {
continue
}
ident, ok := kve.Key.(*ast.Ident)
if !ok {
continue
}
fields[ident.Name] = struct{}{}
}
return fields
}
// returns the list of Exported/Private+Exported fields in the struct type for the composite literal
func getTypeFields(sTyp *types.Struct, validatePrivate bool) Set {
fields := make(Set)
for i := 0; i < sTyp.NumFields(); i++ {
field := sTyp.Field(i)
if !validatePrivate && !field.Exported() {
continue
}
fieldName := field.Name()
fields[fieldName] = struct{}{}
}
return fields
}
func buildDiagnostic(n ast.Node, name string, missing []string) analysis.Diagnostic {
var builder strings.Builder
builder.WriteString("exhaustive struct literal ")
builder.WriteString(name)
if len(missing) == 1 {
builder.WriteString(" not initialized with field ")
builder.WriteString(missing[0])
} else {
builder.WriteString(" not initialized with fields ")
builder.WriteString(strings.Join(missing, ", "))
}
return analysis.Diagnostic{
Pos: n.Pos(),
Message: builder.String(),
}
}
func buildInvalidOmitDiagnostic(
n ast.Node,
name string,
invalidOmittedFields []string,
) analysis.Diagnostic {
var builder strings.Builder
if len(invalidOmittedFields) == 1 {
builder.WriteString("omitted field ")
builder.WriteString(invalidOmittedFields[0])
builder.WriteString(" is not a field")
} else {
builder.WriteString("omitted fields ")
builder.WriteString(strings.Join(invalidOmittedFields, ", "))
builder.WriteString(" are not fields ")
}
builder.WriteString(" of ")
builder.WriteString(name)
return analysis.Diagnostic{
Pos: n.Pos(),
Message: builder.String(),
}
}