forked from mvdan/sh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimplify_test.go
97 lines (88 loc) · 2.35 KB
/
simplify_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
// Copyright (c) 2017, Daniel Martí <[email protected]>
// See LICENSE for licensing information
package syntax
import (
"bytes"
"strings"
"testing"
)
type simplifyTest struct {
in, want string
}
func noSimple(in string) simplifyTest {
return simplifyTest{in: in, want: in}
}
var simplifyTests = [...]simplifyTest{
// arithmetic exprs
{"$((a + ((b - c))))", "$((a + (b - c)))"},
{"$((a + (((b - c)))))", "$((a + (b - c)))"},
{"$(((b - c)))", "$((b - c))"},
{"(((b - c)))", "((b - c))"},
{"${foo[(1)]}", "${foo[1]}"},
{"${foo:(1):(2)}", "${foo:1:2}"},
{"a[(1)]=2", "a[1]=2"},
{"$(($a + ${b}))", "$((a + b))"},
noSimple("$((${!a} + ${#b}))"),
noSimple("a[$b]=2"),
noSimple("${a[$b]}"),
noSimple("${a[@]}"),
noSimple("((${a[@]}))"),
noSimple("((${a[*]}))"),
noSimple("((${a[0]}))"),
noSimple("(($3 == $#))"),
// test exprs
{`[[ "$foo" == "bar" ]]`, `[[ $foo == "bar" ]]`},
{`[[ (-z "$foo") ]]`, `[[ -z $foo ]]`},
{`[[ "a b" > "$c" ]]`, `[[ "a b" > $c ]]`},
{`[[ ! -n $foo ]]`, `[[ -z $foo ]]`},
{`[[ ! ! -e a && ! -z $b ]]`, `[[ -e a && -n $b ]]`},
{`[[ (! a == b) || (! c != d) ]]`, `[[ (a != b) || (c == d) ]]`},
noSimple(`[[ -n a$b && -n $c ]]`),
noSimple(`[[ ! -e foo ]]`),
noSimple(`[[ foo == bar ]]`),
{`[[ foo = bar ]]`, `[[ foo == bar ]]`},
// stmts
{"$( (sts))", "$(sts)"},
{"( ( (sts)))", "(sts)"},
noSimple("( (sts) >f)"),
noSimple("(\n\tx\n\t(sts)\n)"),
// strings
noSimple(`"foo"`),
noSimple(`"foo$bar"`),
noSimple(`"$bar"`),
noSimple(`"f'o\\o"`),
noSimple(`"fo\'o"`),
noSimple(`"fo\\'o"`),
noSimple(`"fo\no"`),
{`"fo\$o"`, `'fo$o'`},
{`"fo\"o"`, `'fo"o'`},
{"\"fo\\`o\"", "'fo`o'"},
noSimple(`fo"o"bar`),
noSimple(`foo""bar`),
}
func TestSimplify(t *testing.T) {
t.Parallel()
parser := NewParser()
printer := NewPrinter()
for _, tc := range simplifyTests {
t.Run("", func(t *testing.T) {
prog, err := parser.Parse(strings.NewReader(tc.in), "")
if err != nil {
t.Fatal(err)
}
simplified := Simplify(prog)
var buf bytes.Buffer
printer.Print(&buf, prog)
want := tc.want + "\n"
if got := buf.String(); got != want {
t.Fatalf("Simplify mismatch of %q\nwant: %q\ngot: %q",
tc.in, want, got)
}
if simplified && tc.in == tc.want {
t.Fatalf("returned true but did not simplify")
} else if !simplified && tc.in != tc.want {
t.Fatalf("returned false but did simplify")
}
})
}
}