-
Notifications
You must be signed in to change notification settings - Fork 43
/
ruleguard_error_test.go
376 lines (337 loc) · 8.2 KB
/
ruleguard_error_test.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
package ruleguard
import (
"errors"
"fmt"
"go/token"
"regexp"
"strings"
"testing"
)
func TestImportError(t *testing.T) {
src := `
package gorules
import "github.com/quasilyte/go-ruleguard/dsl"
func badLock(m dsl.Matcher) {
m.Import("foo/nonexisting")
m.Match("$x").Where(m["x"].Type.Implements("nonexisting.Iface")).Report("ok")
}
`
e := NewEngine()
ctx := &LoadContext{
Fset: token.NewFileSet(),
}
err := e.Load(ctx, "rules.go", strings.NewReader(src))
if err == nil {
t.Fatal("expected an error, got none")
}
var importError *ImportError
if !errors.As(err, &importError) {
t.Fatal("got import that is not ImportError")
}
}
func TestParseFilterFuncError(t *testing.T) {
type testCase struct {
src string
err string
}
simpleTests := []testCase{
// Unsupported features.
// Some of them might be implemented later, but for now
// we want to ensure that the user gets understandable error messages.
{
`b := true; switch true {}; return b`,
`can't compile *ast.SwitchStmt yet`,
},
{
`b := 0; return &b != nil`,
`can't compile unary & yet`,
},
{
`b := 0; return (b << 1) != 0`,
`can't compile binary << yet`,
},
{
`return g(ctx)`,
`can't compile a call to gorules.g func`,
},
{
`return new(int) != nil`,
`can't compile new() builtin function call yet`,
},
{
`x := 5.6; return x != 0`,
`can't compile float constants yet`,
},
{
`s := ""; return s >= "a"`,
`>= is not implemented for string operands`,
},
{
`s := "foo"; b := s[0]; return b == 0`,
`can't compile *ast.IndexExpr yet`,
},
{
`s := Foo{}; return s.X == 0`,
`can't compile *ast.CompositeLit yet`,
},
// Assignment errors.
{
`x, y := 1, 2; return x == y`,
`only single left operand is allowed in assignments`,
},
{
`x := 0; { x := 1; return x == 1 }; return x == 0`,
`x variable shadowing is not allowed`,
},
{
`ctx = ctx; return true`,
`can't assign to ctx, params are readonly`,
},
{
`ctx.Type = nil; return true`,
`can assign only to simple variables`,
},
{
`i++; return true`,
`can't assign to i, params are readonly`,
},
// Unsupported type errors.
{
`x := int32(0); return x == 0`,
`x local variable type: int32 is not supported, try something simpler`,
},
// Implementation limits.
{
`x1:=1; x2:=x1; x3:=x2; x4:=x3; x5:=x4; x6:=x5; x7:=x6; x8:=x7; x9:=x8; return x9 == 1`,
`can't define x9: too many locals`,
},
}
tests := []testCase{
{
`func f() int32 { return 0 }`,
`function result type: int32 is not supported, try something simpler`,
},
{
`func f() []int { return nil }`,
`function result type: []int is not supported, try something simpler`,
},
{
`func f(s *string) int { return 0 }`,
`s param type: *string is not supported, try something simpler`,
},
{
`func f(foo *Foo) int { return foo.X }`,
`can't compile X field access`,
},
{
`func f(foo *Foo) string { return foo.String() }`,
`can't compile a call to *gorules.Foo.String func`,
},
{
`func f() {}`,
`only functions with a single non-void results are supported`,
},
{
`func f() (int, int) { return 0, 0 }`,
`only functions with a single non-void results are supported`,
},
{
`func f() (b bool) { return }`,
`'naked' return statements are not allowed`,
},
}
for _, test := range simpleTests {
test.src = `func f(ctx *dsl.VarFilterContext, i int) bool { ` + test.src + ` }`
tests = append(tests, test)
}
for _, test := range tests {
file := fmt.Sprintf(`
package gorules
import "github.com/quasilyte/go-ruleguard/dsl"
type Foo struct { X int }
func (foo *Foo) String() string { return "" }
func g(ctx *dsl.VarFilterContext) bool { return false }
` + test.src)
e := NewEngine()
ctx := &LoadContext{
Fset: token.NewFileSet(),
}
err := e.Load(ctx, "rules.go", strings.NewReader(file))
if err == nil {
t.Errorf("parse %s: expected %s error, got none", test.src, test.err)
continue
}
have := err.Error()
want := test.err
if !strings.Contains(have, want) {
t.Errorf("parse %s: errors mismatch:\nhave: %s\nwant: %s", test.src, have, want)
continue
}
}
}
func TestParseRuleError(t *testing.T) {
tests := []struct {
expr string
err string
}{
{
`m.Match("$x").Where(m["x"].Object.Is("abc")).Report("")`,
`\Qabc is not a valid go/types object name`,
},
{
`m.Match("$x").MatchComment("").Report("")`,
`\QMatch() and MatchComment() can't be combined`,
},
{
`m.MatchComment("").Match("$x").Report("")`,
`\QMatch() and MatchComment() can't be combined`,
},
{
`m.Where(m.File().Imports("strings")).Report("no match call")`,
`\Qmissing Match() or MatchComment() call`,
},
{
`m.Match("$x").Where(m["x"].Pure)`,
`\Qmissing Report() or Suggest() call`,
},
{
`m.Match("$x").Match("$x")`,
`\QMatch() can't be repeated`,
},
{
`m.MatchComment("").MatchComment("")`,
`\QMatchComment() can't be repeated`,
},
{
`m.Match().Report("$$")`,
`(?:too few|not enough) arguments in call to m\.Match`,
},
{
`m.MatchComment().Report("$$")`,
`(?:too few|not enough) arguments in call to m\.MatchComment`,
},
{
`m.MatchComment("(").Report("")`,
`\Qerror parsing regexp: missing closing )`,
},
{
`m.Match("func[]").Report("$$")`,
`\Qparse match pattern: cannot parse expr: 1:5: expected '(', found '['`,
},
}
for _, test := range tests {
file := fmt.Sprintf(`
package gorules
import "github.com/quasilyte/go-ruleguard/dsl"
func testrule(m dsl.Matcher) {
%s
}`,
test.expr)
e := NewEngine()
ctx := &LoadContext{
Fset: token.NewFileSet(),
}
err := e.Load(ctx, "rules.go", strings.NewReader(file))
if err == nil {
t.Errorf("parse %s: expected %s error, got none", test.expr, test.err)
continue
}
have := err.Error()
wantRE := regexp.MustCompile(test.err)
if !wantRE.MatchString(have) {
t.Errorf("parse %s: errors mismatch:\nhave: %s\nwant: %s", test.expr, have, test.err)
continue
}
}
}
func TestParseFilterError(t *testing.T) {
tests := []struct {
expr string
err string
}{
{
`true`,
`unsupported expr: true`,
},
{
`m["x"].Text == 5`,
`cannot convert 5 (untyped int constant) to string`,
},
{
`m["x"].Text.Matches("(12")`,
`error parsing regexp: missing closing )`,
},
{
`m["x"].Type.Is("%illegal")`,
`parse type expr: 1:1: expected operand, found '%'`,
},
{
`m["x"].Type.Is("interface{String() string}")`,
`parse type expr: can't convert interface{String() string} type expression`,
},
{
`m["x"].Type.ConvertibleTo("interface{String() string}")`,
`can't convert interface{String() string} into a type constraint yet`,
},
{
`m["x"].Type.AssignableTo("interface{String() string}")`,
`can't convert interface{String() string} into a type constraint yet`,
},
{
`m["x"].Type.Implements("foo")`,
`can't resolve foo type; try a fully-qualified name`,
},
{
`m["x"].Type.Implements("func()")`,
`can't resolve func() type; try a fully-qualified name`,
},
{
`m["x"].Type.Implements("bytes.Buffer")`,
`bytes.Buffer is not an interface type`,
},
{
`m["x"].Type.Implements("foo.Bar")`,
`package foo is not imported`,
},
{
`m["x"].Type.Implements("strings.Replacer3")`,
`Replacer3 is not found in strings`,
},
{
`m["x"].Node.Is("abc")`,
`abc is not a valid go/ast type name`,
},
{
`m["x"].Node.Parent().Is("ExprStmt")`,
`only $$ parent nodes are implemented`,
},
{
`m["$$"].Node.Parent().Is("foo")`,
`foo is not a valid go/ast type name`,
},
}
for _, test := range tests {
file := fmt.Sprintf(`
package gorules
import "github.com/quasilyte/go-ruleguard/dsl"
func testrule(m dsl.Matcher) {
m.Match("$x + $y[$key]").Where(%s).Report("$$")
}`,
test.expr)
e := NewEngine()
ctx := &LoadContext{
Fset: token.NewFileSet(),
}
err := e.Load(ctx, "rules.go", strings.NewReader(file))
if err == nil {
t.Errorf("parse %s: expected %s error, got none", test.expr, test.err)
continue
}
have := err.Error()
want := test.err
if !strings.Contains(have, want) {
t.Errorf("parse %s: errors mismatch:\nhave: %s\nwant: %s", test.expr, have, want)
continue
}
}
}