-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbrenda_test.go
638 lines (571 loc) · 11.7 KB
/
brenda_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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
package brenda_test
import (
"bytes"
"go/ast"
"go/format"
"go/importer"
"go/parser"
"go/token"
"go/types"
"io"
"github.com/dave/brenda"
"fmt"
"sort"
"strings"
"github.com/pkg/errors"
"regexp"
"os"
)
func ExampleNewSolver_bool_lit_3() {
printExample(`
var a bool
if a && false {} else {}
`)
// Output:
// if a && false {
// // IMPOSSIBLE
// } else {
// // a UNKNOWN
// }
}
func ExampleNewSolver_bool_lit_2() {
printExample(`
var a bool
if a || true {} else {}
`)
// Output:
// if a || true {
// // a UNKNOWN
// } else {
// // IMPOSSIBLE
// }
}
func ExampleNewSolver_bool_lit_1() {
printExample(`
if false {} else {}
`)
// Output:
// if false {
// // IMPOSSIBLE
// } else {
//
// }
}
func ExampleNewSolver_simple() {
printExample(`
var a bool
if a { }
`)
// Output:
// if a {
// // a TRUE
// }
}
func ExampleNewSolver_else() {
printExample(`
var a bool
if a {} else {}
`)
// Output:
// if a {
// // a TRUE
// } else {
// // a FALSE
// }
}
func ExampleNewSolver_and() {
printExample(`
var a, b bool
if a && b {} else {}
`)
// Output:
// if a && b {
// // a TRUE
// // b TRUE
// } else {
// // a UNKNOWN
// // b UNKNOWN
// }
}
func ExampleNewSolver_unknown() {
printExample(`
var a, b, c bool
if a && (b || c) {} else if b {}
`)
// Output:
// if a && (b || c) {
// // a TRUE
// // b UNKNOWN
// // c UNKNOWN
// } else if b {
// // a FALSE
// // b TRUE
// // c UNKNOWN
// }
}
func ExampleNewSolver_impossible() {
printExample(`
var a bool
if a {} else if !a {} else {}
`)
// Output:
// if a {
// // a TRUE
// } else if !a {
// // a FALSE
// } else {
// // IMPOSSIBLE
// }
}
func ExampleNewSolver_or() {
printExample(`
var a, b bool
if a || b {} else {}
`)
// Output:
// if a || b {
// // a UNKNOWN
// // b UNKNOWN
// } else {
// // a FALSE
// // b FALSE
// }
}
func ExampleNewSolver_unary() {
printExample(`
var a, b bool
if !(a || b) {} else {}
`)
// Output:
// if !(a || b) {
// // a FALSE
// // b FALSE
// } else {
// // a UNKNOWN
// // b UNKNOWN
// }
}
func ExampleNewSolver_else_if() {
printExample(`
var a, b bool
if a {} else if b {} else {}
`)
// Output:
// if a {
// // a TRUE
// } else if b {
// // a FALSE
// // b TRUE
// } else {
// // a FALSE
// // b FALSE
// }
}
func ExampleNewSolver_invert() {
printExample(`
// should correctly detect that b == nil is the inverse of b != nil
var a, b error
if a == nil && b == nil {} else if b != nil {} else {}
`)
// Output:
// if a == nil && b == nil {
// // a == nil TRUE
// // b == nil TRUE
// } else if b != nil {
// // a == nil UNKNOWN
// // b != nil TRUE
// } else {
// // a == nil FALSE
// // b == nil TRUE
// }
}
func ExampleNewSolver_invert2() {
printExample(`
// should correctly detect that a == nil is the inverse of a != nil
var a error
var b bool
if a == nil && b || a != nil {} else if b {} else {}
`)
// Output:
// if a == nil && b || a != nil {
// // a == nil UNKNOWN
// // b UNKNOWN
// } else if b {
// // IMPOSSIBLE
// } else {
// // a == nil TRUE
// // b FALSE
// }
}
func ExampleNewSolver_invert_gt() {
printExample(`
var a int
if a > 0 {} else if a <= 0 {} else {}
`)
// Output:
// if a > 0 {
// // a > 0 TRUE
// } else if a <= 0 {
// // a <= 0 TRUE
// } else {
// // IMPOSSIBLE
// }
}
func ExampleNewSolver_invert_lt() {
printExample(`
var a int
if a < 0 {} else if a >= 0 {} else {}
`)
// Output:
// if a < 0 {
// // a < 0 TRUE
// } else if a >= 0 {
// // a >= 0 TRUE
// } else {
// // IMPOSSIBLE
// }
}
func ExampleNewSolver_brackets1() {
printExample(`
var a, b, c bool
if a || (b && c) {} else if a {} else {}
`)
// Output:
// if a || (b && c) {
// // a UNKNOWN
// // b UNKNOWN
// // c UNKNOWN
// } else if a {
// // IMPOSSIBLE
// } else {
// // a FALSE
// // b UNKNOWN
// // c UNKNOWN
// }
}
func ExampleNewSolver_brackets2() {
printExample(`
var a, b, c bool
if a || (b && c) {} else if b {} else {}
`)
// Output:
// if a || (b && c) {
// // a UNKNOWN
// // b UNKNOWN
// // c UNKNOWN
// } else if b {
// // a FALSE
// // b TRUE
// // c FALSE
// } else {
// // a FALSE
// // b FALSE
// // c UNKNOWN
// }
}
func ExampleNewSolver_brackets3() {
printExample(`
var a, b, c bool
if a && (b || c) {} else if a {} else {}
`)
// Output:
// if a && (b || c) {
// // a TRUE
// // b UNKNOWN
// // c UNKNOWN
// } else if a {
// // a TRUE
// // b FALSE
// // c FALSE
// } else {
// // a FALSE
// // b UNKNOWN
// // c UNKNOWN
// }
}
func ExampleNewSolver_brackets4() {
printExample(`
var a, b, c bool
if a && (b || c) {} else if b {} else {}
`)
// Output:
// if a && (b || c) {
// // a TRUE
// // b UNKNOWN
// // c UNKNOWN
// } else if b {
// // a FALSE
// // b TRUE
// // c UNKNOWN
// } else {
// // a UNKNOWN
// // b FALSE
// // c UNKNOWN
// }
}
func ExampleNewSolver_errors() {
printExample(`
var a error
if a == nil {} else {}
`)
// Output:
// if a == nil {
// // a == nil TRUE
// } else {
// // a != nil TRUE
// }
}
func ExampleNewSolver_mixed() {
printExample(`
var a error
var b, c bool
var d int
if a == nil && (b && d > 0) || c {} else if d <= 0 || c {} else if b {}
`)
// Output:
// if a == nil && (b && d > 0) || c {
// // a == nil UNKNOWN
// // b UNKNOWN
// // c UNKNOWN
// // d > 0 UNKNOWN
// } else if d <= 0 || c {
// // a == nil UNKNOWN
// // b UNKNOWN
// // c FALSE
// // d <= 0 TRUE
// } else if b {
// // a == nil FALSE
// // b TRUE
// // c FALSE
// // d > 0 TRUE
// }
}
func printExample(src string) {
err := printOutput(os.Stdout, src)
if err != nil {
fmt.Printf("%+v", err)
}
}
func printOutput(writer io.Writer, src string) error {
fpath := "/foo.go"
ppath := "a.b/c"
src = fmt.Sprintf("package a\n\nfunc a() {\n%s\n}", src)
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, fpath, src, parser.ParseComments)
if err != nil {
return errors.Wrap(err, "Error parsing file")
}
info := types.Info{
Uses: make(map[*ast.Ident]types.Object),
Defs: make(map[*ast.Ident]types.Object),
}
conf := types.Config{
Importer: importer.Default(),
}
if _, err = conf.Check(ppath, fset, []*ast.File{f}, &info); err != nil {
return errors.Wrap(err, "Error checking conf")
}
var ifs *ast.IfStmt
ast.Inspect(f, func(node ast.Node) bool {
if ifs != nil {
// once if statement is found, skip all further code
return false
}
if n, ok := node.(*ast.IfStmt); ok && n != nil {
ifs = n
return false
}
return true
})
if ifs == nil {
return errors.New("No *ast.IfStmt found")
}
err = printIf(writer, fset, info, ifs)
if err != nil {
return err
}
return nil
}
func printIf(writer io.Writer, fset *token.FileSet, info types.Info, expr *ast.IfStmt, falseExpr ...ast.Expr) error {
s := brenda.NewSolver(fset, info.Uses, info.Defs, expr.Cond, falseExpr...)
err := s.SolveTrue()
if err != nil {
return err
}
fmt.Fprintln(writer, "if", printNode(fset, expr.Cond), "{")
printMatches(writer, fset, s)
switch e := expr.Else.(type) {
case nil:
// No else block
fmt.Fprintln(writer, "}")
case *ast.BlockStmt:
// Else block
s := brenda.NewSolver(fset, info.Uses, info.Defs, expr.Cond, falseExpr...)
s.SolveFalse()
fmt.Fprintln(writer, "} else {")
printMatches(writer, fset, s)
fmt.Fprintln(writer, "}")
case *ast.IfStmt:
// Else if statement
fmt.Fprint(writer, "} else ")
falseExpr = append(falseExpr, expr.Cond)
printIf(writer, fset, info, e, falseExpr...)
}
return nil
}
func printMatches(writer io.Writer, fset *token.FileSet, s *brenda.Solver) {
if s.Impossible {
fmt.Fprintln(writer, "\t// IMPOSSIBLE")
return
}
var lines []string
for ex, m := range s.Components {
switch {
case m.Match:
lines = append(lines, fmt.Sprint("\t// ", printNode(fset, ex), " TRUE"))
case m.Inverse:
lines = append(lines, fmt.Sprint("\t// ", printNode(fset, ex), " FALSE"))
default:
lines = append(lines, fmt.Sprint("\t// ", printNode(fset, ex), " UNKNOWN"))
}
}
sort.Strings(lines)
fmt.Fprintln(writer, strings.Join(lines, "\n"))
}
func printNode(fset *token.FileSet, node ast.Node) string {
buf := &bytes.Buffer{}
err := format.Node(buf, fset, node)
if err != nil {
return err.Error()
}
return buf.String()
}
func unindent(s string) string {
// first trim any \n
s = strings.Trim(s, "\n")
// then work out how the first line is indented
loc := regexp.MustCompile("[^\t ]").FindStringIndex(s)
if loc == nil {
// string is empty?
return s
}
indent := s[:loc[0]]
if indent == "" {
// string is not indented
return s
}
return strings.Replace("\n"+s, "\n"+indent, "\n", -1)[1:]
}
func ExampleNewSolver_usage() {
// A simple source file
src := `package foo
func foo(a, b bool) {
if a { } else if b { } else { }
}`
// We parse the AST
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "foo.go", src, 0)
if err != nil {
fmt.Println(err)
return
}
// We extract type info
info := types.Info{
Uses: make(map[*ast.Ident]types.Object),
Defs: make(map[*ast.Ident]types.Object),
}
conf := types.Config{Importer: importer.Default()}
if _, err = conf.Check("foo", fset, []*ast.File{f}, &info); err != nil {
fmt.Println(err)
return
}
// Walk the AST until we find the first *ast.IfStmt
var ifs *ast.IfStmt
ast.Inspect(f, func(node ast.Node) bool {
if ifs != nil {
return false
}
if n, ok := node.(*ast.IfStmt); ok && n != nil {
ifs = n
return false
}
return true
})
if ifs == nil {
fmt.Println("No *ast.IfStmt found")
return
}
var printIf func(*ast.IfStmt, ...ast.Expr) error
var sprintResults func(*brenda.Solver) string
var sprintNode func(ast.Node) string
// This is called recursively for the if and all else-if statements. falseExpr
// is a slice of all the conditions that came before an else-if statement,
// which must all be false for the else-if to be reached.
printIf = func(ifStmt *ast.IfStmt, falseExpr ...ast.Expr) error {
s := brenda.NewSolver(fset, info.Uses, info.Defs, ifStmt.Cond, falseExpr...)
err := s.SolveTrue()
if err != nil {
return err
}
fmt.Printf("if %s {\n%s\n}", sprintNode(ifStmt.Cond), sprintResults(s))
switch e := ifStmt.Else.(type) {
case *ast.BlockStmt:
// Else block
s := brenda.NewSolver(fset, info.Uses, info.Defs, ifStmt.Cond, falseExpr...)
s.SolveFalse()
fmt.Printf(" else {\n%s\n}", sprintResults(s))
case *ast.IfStmt:
// Else if statement
fmt.Print(" else ")
// Add the condition from the current if statement to the list of
// false expressions for the else-if solver
falseExpr = append(falseExpr, ifStmt.Cond)
printIf(e, falseExpr...)
}
return nil
}
// Helper function to print results
sprintResults = func(s *brenda.Solver) string {
if s.Impossible {
// If the expression is impossible
return "\t// IMPOSSIBLE"
}
// The results must be sorted to ensure repeatable output
var lines []string
for expr, result := range s.Components {
switch {
case result.Match:
lines = append(lines, fmt.Sprint("\t// ", printNode(fset, expr), " TRUE"))
case result.Inverse:
lines = append(lines, fmt.Sprint("\t// ", printNode(fset, expr), " FALSE"))
default:
lines = append(lines, fmt.Sprint("\t// ", printNode(fset, expr), " UNKNOWN"))
}
}
sort.Strings(lines)
return strings.Join(lines, "\n")
}
// Helper function to print AST nodes
sprintNode = func(n ast.Node) string {
buf := &bytes.Buffer{}
err := format.Node(buf, fset, n)
if err != nil {
return err.Error()
}
return buf.String()
}
if err := printIf(ifs); err != nil {
fmt.Println(err)
return
}
// Output:
// if a {
// // a TRUE
// } else if b {
// // a FALSE
// // b TRUE
// } else {
// // a FALSE
// // b FALSE
// }
}