-
Notifications
You must be signed in to change notification settings - Fork 9
/
musttag.go
274 lines (232 loc) Β· 6.26 KB
/
musttag.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
// Package musttag implements the musttag analyzer.
package musttag
import (
"flag"
"fmt"
"go/ast"
"go/types"
"reflect"
"strconv"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/go/types/typeutil"
)
// Func describes a function call to look for, e.g. [json.Marshal].
type Func struct {
Name string // The full name of the function, including the package.
Tag string // The struct tag whose presence should be ensured.
ArgPos int // The position of the argument to check.
// a list of interface names (including the package);
// if at least one is implemented by the argument, no check is performed.
ifaceWhitelist []string
}
// New creates a new musttag analyzer.
// To report a custom function, provide its description as [Func].
func New(funcs ...Func) *analysis.Analyzer {
var flagFuncs []Func
return &analysis.Analyzer{
Name: "musttag",
Doc: "enforce field tags in (un)marshaled structs",
Flags: flags(&flagFuncs),
Requires: []*analysis.Analyzer{inspect.Analyzer},
Run: func(pass *analysis.Pass) (any, error) {
l := len(builtins) + len(funcs) + len(flagFuncs)
allFuncs := make(map[string]Func, l)
merge := func(slice []Func) {
for _, fn := range slice {
allFuncs[fn.Name] = fn
}
}
merge(builtins)
merge(funcs)
merge(flagFuncs)
mainModule, err := getMainModule()
if err != nil {
return nil, err
}
return run(pass, mainModule, allFuncs)
},
}
}
func flags(funcs *[]Func) flag.FlagSet {
fs := flag.NewFlagSet("musttag", flag.ContinueOnError)
fs.Func("fn", "report a custom function (name:tag:arg-pos)", func(s string) error {
parts := strings.Split(s, ":")
if len(parts) != 3 || parts[0] == "" || parts[1] == "" {
return strconv.ErrSyntax
}
pos, err := strconv.Atoi(parts[2])
if err != nil {
return err
}
*funcs = append(*funcs, Func{
Name: parts[0],
Tag: parts[1],
ArgPos: pos,
})
return nil
})
return *fs
}
func run(pass *analysis.Pass, mainModule string, funcs map[string]Func) (_ any, err error) {
visit := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
filter := []ast.Node{(*ast.CallExpr)(nil)}
visit.Preorder(filter, func(node ast.Node) {
if err != nil {
return // there is already an error.
}
call, ok := node.(*ast.CallExpr)
if !ok {
return
}
callee := typeutil.StaticCallee(pass.TypesInfo, call)
if callee == nil {
return
}
fn, ok := funcs[cutVendor(callee.FullName())]
if !ok {
return
}
if len(call.Args) <= fn.ArgPos {
err = fmt.Errorf("musttag: Func.ArgPos cannot be %d: %s accepts only %d argument(s)", fn.ArgPos, fn.Name, len(call.Args))
return
}
arg := call.Args[fn.ArgPos]
if ident, ok := arg.(*ast.Ident); ok && ident.Obj == nil {
return // e.g. json.Marshal(nil)
}
typ := pass.TypesInfo.TypeOf(arg)
if typ == nil {
return
}
checker := checker{
mainModule: mainModule,
seenTypes: make(map[string]struct{}),
ifaceWhitelist: fn.ifaceWhitelist,
imports: pass.Pkg.Imports(),
}
if checker.isValidType(typ, fn.Tag) {
return
}
pass.Reportf(arg.Pos(), "the given struct should be annotated with the `%s` tag", fn.Tag)
})
return nil, err
}
type checker struct {
mainModule string
seenTypes map[string]struct{}
ifaceWhitelist []string
imports []*types.Package
}
func (c *checker) isValidType(typ types.Type, tag string) bool {
if _, ok := c.seenTypes[typ.String()]; ok {
return true
}
c.seenTypes[typ.String()] = struct{}{}
styp, ok := c.parseStruct(typ)
if !ok {
return true
}
return c.isValidStruct(styp, tag)
}
func (c *checker) parseStruct(typ types.Type) (*types.Struct, bool) {
if implementsInterface(typ, c.ifaceWhitelist, c.imports) {
return nil, false
}
switch typ := typ.(type) {
case *types.Pointer:
return c.parseStruct(typ.Elem())
case *types.Array:
return c.parseStruct(typ.Elem())
case *types.Slice:
return c.parseStruct(typ.Elem())
case *types.Map:
return c.parseStruct(typ.Elem())
case *types.Named: // a struct of the named type.
pkg := typ.Obj().Pkg()
if pkg == nil {
return nil, false
}
if !strings.HasPrefix(pkg.Path(), c.mainModule) {
return nil, false
}
styp, ok := typ.Underlying().(*types.Struct)
if !ok {
return nil, false
}
return styp, true
case *types.Struct: // an anonymous struct.
return typ, true
default:
return nil, false
}
}
func (c *checker) isValidStruct(styp *types.Struct, tag string) bool {
for i := 0; i < styp.NumFields(); i++ {
field := styp.Field(i)
if !field.Exported() {
continue
}
tagValue, ok := reflect.StructTag(styp.Tag(i)).Lookup(tag)
if !ok {
// tag is not required for embedded types.
if !field.Embedded() {
return false
}
}
// the field is explicitly ignored.
if tagValue == "-" {
continue
}
if !c.isValidType(field.Type(), tag) {
return false
}
}
return true
}
func implementsInterface(typ types.Type, ifaces []string, imports []*types.Package) bool {
findScope := func(pkgName string) (*types.Scope, bool) {
// fast path: check direct imports (e.g. looking for "encoding/json.Marshaler").
for _, direct := range imports {
if pkgName == cutVendor(direct.Path()) {
return direct.Scope(), true
}
}
// slow path: check indirect imports (e.g. looking for "encoding.TextMarshaler").
// TODO: only check indirect imports from the package (e.g. "encoding/json") of the analyzed function (e.g. "encoding/json.Marshal").
for _, direct := range imports {
for _, indirect := range direct.Imports() {
if pkgName == cutVendor(indirect.Path()) {
return indirect.Scope(), true
}
}
}
return nil, false
}
for _, ifacePath := range ifaces {
// e.g. "encoding/json.Marshaler" -> "encoding/json" + "Marshaler".
idx := strings.LastIndex(ifacePath, ".")
if idx == -1 {
continue
}
pkgName, ifaceName := ifacePath[:idx], ifacePath[idx+1:]
scope, ok := findScope(pkgName)
if !ok {
continue
}
obj := scope.Lookup(ifaceName)
if obj == nil {
continue
}
iface, ok := obj.Type().Underlying().(*types.Interface)
if !ok {
continue
}
if types.Implements(typ, iface) || types.Implements(types.NewPointer(typ), iface) {
return true
}
}
return false
}