/
pairedbrackets.go
386 lines (348 loc) · 9.83 KB
/
pairedbrackets.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package pairedbrackets
import (
"flag"
"go/ast"
"go/token"
"go/types"
"regexp"
"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"
)
type Name string
const (
Parenthesis Name = "parenthesis" // ()
Bracket Name = "bracket" // []
Brace Name = "brace" // {}
)
type Element string
const (
Unknown Element = "element"
Argument Element = "argument"
CompositeElement Element = "composite element"
Constant Element = "constant"
Expression Element = "expression"
Field Element = "field"
Import Element = "import"
Index Element = "index"
Method Element = "method"
Parameter Element = "parameter"
Receiver Element = "receiver"
Result Element = "result"
Statement Element = "statement"
Type Element = "type"
TypeParameter Element = "type parameter"
Variable Element = "variable"
)
// Fully qualified function examples:
// - github.com/stretchr/testify/require.Equal
// - (*github.com/stretchr/testify/assert.Assertions).Equal
const (
IgnoreFuncCallsFlagName = "ignore-func-calls"
IgnoreFuncCallsFlagUsage = "comma separated list of regexp patterns of fully qualified function calls to ignore"
IgnoreFuncCallsFlagDefault = "github.com/stretchr/testify/assert,github.com/stretchr/testify/require"
)
// NewAnalyzer returns Analyzer that checks formatting of paired brackets.
func NewAnalyzer() *analysis.Analyzer {
var (
ignoreFuncCalls commaListRegexpFlag
fs flag.FlagSet
)
_ = ignoreFuncCalls.Set(IgnoreFuncCallsFlagDefault)
fs.Var(&ignoreFuncCalls, IgnoreFuncCallsFlagName, IgnoreFuncCallsFlagUsage)
return &analysis.Analyzer{
Name: "pairedbrackets",
Doc: "linter checks formatting of paired brackets",
Requires: []*analysis.Analyzer{inspect.Analyzer},
Flags: fs,
Run: func(pass *analysis.Pass) (interface{}, error) {
return run(runner{
ignoreFuncCalls: &ignoreFuncCalls,
pass: pass,
})
},
}
}
type runner struct {
ignoreFuncCalls *commaListRegexpFlag
pass *analysis.Pass
}
// Run runs the analyzer.
//
// Nodes without brackets (alphabet order):
// - [*ast.AssignStmt]
// - [*ast.BadDecl]
// - [*ast.BadExpr]
// - [*ast.BadStmt]
// - [*ast.BasicLit]
// - [*ast.BinaryExpr]
// - [*ast.BranchStmt]
// - [*ast.CaseClause]
// - [*ast.ChanType]
// - [*ast.CommClause]
// - [*ast.CommentGroup]
// - [*ast.Comment]
// - [*ast.DeclStmt]
// - [*ast.DeferStmt]
// - [*ast.Ellipsis]
// - [*ast.EmptyStmt]
// - [*ast.ExprStmt]
// - [*ast.Field]
// - [*ast.File]
// - [*ast.GoStmt]
// - [*ast.Ident]
// - [*ast.ImportSpec]
// - [*ast.IncDecStmt]
// - [*ast.KeyValueExpr]
// - [*ast.LabeledStmt]
// - [*ast.Package]
// - [*ast.ReturnStmt]
// - [*ast.SelectorExpr]
// - [*ast.SendStmt]
// - [*ast.StarExpr]
// - [*ast.UnaryExpr]
// - [*ast.ValueSpec]
//
// Ignored because go syntax doesn't allow to start line with right bracket:
// - [*ast.ArrayType]
// - [*ast.MapType]
//
// [*ast.BlockStmt] ignored because is checked in other cases:
// - [*ast.ForStmt]
// - [*ast.FuncLit]
// - [*ast.IfStmt]
// - [*ast.RangeStmt]
// - [*ast.SelectStmt]
// - [*ast.SwitchStmt]
// - [*ast.TypeSwitchStmt]
//
// [*ast.FieldList] ignored because is checked in other cases:
// - [*ast.FuncDecl]
// - [*ast.FuncType]
// - [*ast.InterfaceType]
// - [*ast.StructType]
// - [*ast.TypeSpec]
func run(r runner) (interface{}, error) {
filter := []ast.Node{ // alphabet order
&ast.CallExpr{},
&ast.CompositeLit{},
&ast.ForStmt{},
&ast.FuncDecl{},
&ast.FuncLit{},
&ast.FuncType{},
&ast.GenDecl{},
&ast.IfStmt{},
&ast.IndexExpr{},
&ast.IndexListExpr{},
&ast.InterfaceType{},
&ast.ParenExpr{},
&ast.RangeStmt{},
&ast.SelectStmt{},
&ast.SliceExpr{},
&ast.StructType{},
&ast.SwitchStmt{},
&ast.TypeAssertExpr{},
&ast.TypeSpec{},
&ast.TypeSwitchStmt{},
}
astInspector := r.pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) //nolint:errcheck // let's panic
astInspector.Preorder(filter, func(node ast.Node) {
switch n := node.(type) {
case *ast.CallExpr:
validateCall(r, n)
case *ast.CompositeLit:
validate(r, Brace, n.Lbrace, n.Rbrace, n.Elts, CompositeElement)
case *ast.ForStmt:
validateBlock(r, n.Body)
case *ast.FuncDecl:
// n.Type is checked separately in [*ast.FuncType]
validateFieldList(r, Parenthesis, n.Recv, Receiver)
validateBlock(r, n.Body)
case *ast.FuncLit:
// n.Type is checked separately in [*ast.FuncType]
validateBlock(r, n.Body)
case *ast.FuncType:
validateFieldList(r, Bracket, n.TypeParams, TypeParameter)
validateFieldList(r, Parenthesis, n.Params, Parameter)
validateFieldList(r, Parenthesis, n.Results, Result)
case *ast.GenDecl:
validate(r, Parenthesis, n.Lparen, n.Rparen, n.Specs, genDeclElement(n))
case *ast.IfStmt:
validateBlock(r, n.Body)
if block, ok := n.Else.(*ast.BlockStmt); ok {
validateBlock(r, block)
}
case *ast.IndexExpr:
validate(r, Bracket, n.Lbrack, n.Rbrack, []ast.Expr{n.Index}, Unknown) // unknown because it may be several types
case *ast.IndexListExpr:
validate(r, Bracket, n.Lbrack, n.Rbrack, n.Indices, Unknown) // unknown because it may be several types
case *ast.InterfaceType:
validateFieldList(r, Brace, n.Methods, Method)
case *ast.ParenExpr:
validate(r, Parenthesis, n.Lparen, n.Rparen, []ast.Expr{n.X}, Expression)
case *ast.RangeStmt:
validateBlock(r, n.Body)
case *ast.SelectStmt:
validateBlock(r, n.Body)
case *ast.SliceExpr:
validate(r, Bracket, n.Lbrack, n.Rbrack, []ast.Expr{n.Low, n.High, n.Max}, Index)
case *ast.StructType:
validateFieldList(r, Brace, n.Fields, Field)
case *ast.SwitchStmt:
validateBlock(r, n.Body)
case *ast.TypeAssertExpr:
validate(r, Parenthesis, n.Lparen, n.Rparen, []ast.Expr{n.Type}, Type)
case *ast.TypeSpec:
validateFieldList(r, Bracket, n.TypeParams, TypeParameter)
case *ast.TypeSwitchStmt:
validateBlock(r, n.Body)
}
})
return nil, nil //nolint:nilnil // the linter has no result, it should return nil
}
func validateCall(r runner, node *ast.CallExpr) {
if callee := typeutil.Callee(r.pass.TypesInfo, node); callee != nil {
if fn, ok := callee.(*types.Func); ok {
if r.ignoreFuncCalls.Match(fn.FullName()) {
return
}
}
}
validate(r, Parenthesis, node.Lparen, node.Rparen, node.Args, Argument)
}
func validateFieldList(r runner, name Name, node *ast.FieldList, element Element) {
if node == nil {
return
}
validate(r, name, node.Opening, node.Closing, node.List, element)
}
func validateBlock(r runner, node *ast.BlockStmt) {
if node == nil {
return
}
validate(r, Brace, node.Lbrace, node.Rbrace, node.List, Statement)
}
func genDeclElement(node *ast.GenDecl) Element {
switch node.Tok { //nolint:exhaustive // only 4 options are possible, see doc for [*ast.GenDecl]
case token.IMPORT:
return Import
case token.CONST:
return Constant
case token.TYPE:
return Type
case token.VAR:
return Variable
default:
return Unknown
}
}
func validate[N ast.Node](r runner, bracket Name, left, right token.Pos, list []N, element Element) {
if left == token.NoPos || right == token.NoPos {
return // no brackets - nothing to check
}
leftLine := r.pass.Fset.Position(left).Line
rightLine := r.pass.Fset.Position(right).Line
if leftLine == rightLine {
return
}
// aaa, bbb, ccccccccc
// ^ ^ ^
firstPos, lastPos, lastEnd, ok := boundaries(list)
if !ok {
return // list is empty
}
firstPosLine := r.pass.Fset.Position(firstPos).Line
lastPosLine := firstPosLine // optimisation
if lastPos != firstPos {
lastPosLine = r.pass.Fset.Position(lastPos).Line
}
lastEndLine := r.pass.Fset.Position(lastEnd).Line
switch {
case leftLine == lastPosLine: // left bracket is ok
if lastEndLine != rightLine {
r.pass.Reportf(right, "right %s should be on the previous line", bracket)
}
case leftLine != firstPosLine: // left bracket is ok
if lastEndLine == rightLine {
r.pass.Reportf(right, "right %s should be on the next line", bracket)
}
default:
r.pass.Reportf(
left,
"left %s should either be the last character on a line or be on the same line with the last %s",
bracket,
element,
)
}
}
// boundaries returns:
// - position of the first character of the first node
// - position of the first character of the last node
// - position of the last character of the last node
// - false, if list doesn't contain non-nil nodes
//
// Example:
//
// aaaaaa, bbbbbb, cccccc
// ^ ^ ^
func boundaries[N ast.Node](list []N) (token.Pos, token.Pos, token.Pos, bool) {
ok := false
firstPos, lastPos, lastEnd := token.NoPos, token.NoPos, token.NoPos
var last N
for _, n := range list {
if any(n) == nil {
continue
}
p := n.Pos()
if !ok {
ok = true
firstPos, lastPos = p, p
last = n
continue
}
if p < firstPos { // seems like impossible, but let's be conservative
firstPos = p
}
if p > lastPos {
lastPos = p
last = n
}
}
if ok {
lastEnd = last.End() - 1 // -1 because we need position of node's last character
}
return firstPos, lastPos, lastEnd, ok
}
type commaListRegexpFlag struct {
original string
regs []*regexp.Regexp
}
func (f *commaListRegexpFlag) String() string {
if f == nil {
return ""
}
return f.original
}
func (f *commaListRegexpFlag) Set(value string) error {
regs := make([]*regexp.Regexp, 0, len(value))
for _, pattern := range strings.Split(value, ",") {
re, err := regexp.Compile(pattern)
if err != nil {
return err
}
regs = append(regs, re)
}
f.original = value
f.regs = regs
return nil
}
func (f *commaListRegexpFlag) Match(s string) bool {
for _, r := range f.regs {
if r.MatchString(s) {
return true
}
}
return false
}