Debian Codegraph @

syntax/typedjson/json_test.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package typedjson_test
5
6 import (
7 "bytes"
8 "encoding/json"
9 "flag"
10 "maps"
11 "os"
12 "path/filepath"
13 "slices"
14 "strings"
15 "testing"
16
17 "github.com/go-quicktest/qt"
18
19 "mvdan.cc/sh/v3/syntax"
20 "mvdan.cc/sh/v3/syntax/typedjson"
21 )
22
23 var update = flag.Bool("u", false, "update output files")
24
25 func TestRoundtripZsh(t *testing.T) {
26 t.Parallel()
27
28 // ${a[(r)foo]} produces a FlagsArithm node, which only appears with zsh.
29 src := "echo ${a[(r)foo]}\n"
30 parser := syntax.NewParser(syntax.Variant(syntax.LangZsh))
31 node, err := parser.Parse(strings.NewReader(src), "")
32 qt.Assert(t, qt.IsNil(err))
33
34 var buf bytes.Buffer
35 qt.Assert(t, qt.IsNil(typedjson.Encode(&buf, node)))
36
37 node2, err := typedjson.Decode(&buf)
38 qt.Assert(t, qt.IsNil(err))
39
40 sb := new(strings.Builder)
41 qt.Assert(t, qt.IsNil(syntax.NewPrinter().Print(sb, node2)))
42 qt.Assert(t, qt.Equals(sb.String(), src))
43 }
44
45 // allNodeNames lists the name of every [syntax.Node] type,
46 // all of which must be encodable and decodable as a root node.
47 var allNodeNames = []string{
48 "ArithmCmd", "ArithmExp", "ArrayElem", "ArrayExpr", "Assign",
49 "BinaryArithm", "BinaryCmd", "BinaryTest", "Block", "BraceExp",
50 "CStyleLoop", "CallExpr", "CaseClause", "CaseItem", "CmdSubst", "Comment",
51 "CoprocClause", "DblQuoted", "DeclClause", "ExtGlob", "File", "FlagsArithm",
52 "ForClause", "FuncDecl", "IfClause", "LetClause", "Lit", "ParamExp",
53 "ParenArithm", "ParenTest", "ProcSubst", "Redirect", "SglQuoted", "Stmt",
54 "Subshell", "TestClause", "TestDecl", "TimeClause", "UnaryArithm",
55 "UnaryTest", "WhileClause", "Word", "WordIter",
56 }
57
58 // TestRoundtripAnyNode checks that any node can be encoded and decoded,
59 // not just [syntax.File], and that every node type is covered.
60 func TestRoundtripAnyNode(t *testing.T) {
61 t.Parallel()
62
63 tests := []struct {
64 lang syntax.LangVariant
65 src string
66 }{
67 {syntax.LangBash, `
68 foo=bar qux >redir <<EOF
69 hdoc
70 EOF
71 baz=(one [two]=three)
72 ! foo | bar || baz & 'sgl' "dbl" ${foo:-x} $(cmd) $((1 + -2)) $(( ($x) )) @(glob) <(proc) {a,b}
73 if foo; then bar; else baz; fi
74 for i in x; do foo; done
75 for ((i = 0; i < 3; i++)); do foo; done
76 while foo; do bar; done
77 case i in foo) bar ;; esac
78 { foo; }
79 (foo)
80 foo() { bar; }
81 declare -A foo
82 let x=1
83 time foo
84 coproc foo
85 ((2))
86 [[ ! (foo && -n bar) ]]
87 # comment
88 `},
89 // ${a[(r)foo]} produces a FlagsArithm node, which only appears with zsh.
90 {syntax.LangZsh, "echo ${a[(r)foo]}\n"},
91 // TestDecl only appears with bats.
92 {syntax.LangBats, "@test \"name\" {\n\tfoo\n}\n"},
93 }
94
95 seen := make(map[string]bool)
96 roundtrip := func(node syntax.Node) {
97 var buf bytes.Buffer
98 qt.Assert(t, qt.IsNil(typedjson.Encode(&buf, node)))
99 encoded := buf.String()
100
101 var typed struct{ Type string }
102 qt.Assert(t, qt.IsNil(json.Unmarshal(buf.Bytes(), &typed)))
103 qt.Assert(t, qt.Not(qt.Equals(typed.Type, "")))
104 seen[typed.Type] = true
105
106 // Decoding and encoding again must give the same JSON,
107 // as no information is lost along the way.
108 node2, err := typedjson.Decode(strings.NewReader(encoded))
109 qt.Assert(t, qt.IsNil(err), qt.Commentf("node: %s", encoded))
110 buf.Reset()
111 qt.Assert(t, qt.IsNil(typedjson.Encode(&buf, node2)))
112 qt.Assert(t, qt.Equals(buf.String(), encoded))
113 }
114 for _, test := range tests {
115 parser := syntax.NewParser(syntax.Variant(test.lang), syntax.KeepComments(true))
116 file, err := parser.Parse(strings.NewReader(test.src), "")
117 qt.Assert(t, qt.IsNil(err))
118 syntax.Walk(file, func(node syntax.Node) bool {
119 if node == nil {
120 return false
121 }
122 roundtrip(node)
123 return true
124 })
125 }
126
127 // The parser never produces a BraceExp, and [syntax.Walk] does not know
128 // how to walk one either, so cover it on its own.
129 file, err := syntax.NewParser().Parse(strings.NewReader("{a,b}"), "")
130 qt.Assert(t, qt.IsNil(err))
131 word := file.Stmts[0].Cmd.(*syntax.CallExpr).Args[0]
132 qt.Assert(t, qt.IsTrue(syntax.SplitBraces(word)))
133 roundtrip(word.Parts[0].(*syntax.BraceExp))
134
135 qt.Assert(t, qt.ContentEquals(slices.Sorted(maps.Keys(seen)), allNodeNames))
136 }
137
138 // TestDecodeErrors checks that malformed input results in errors
139 // rather than panics from unchecked reflection operations.
140 func TestDecodeErrors(t *testing.T) {
141 t.Parallel()
142
143 tests := []struct {
144 name string
145 input string
146 want string
147 }{
148 {"Empty", ``, "EOF"},
149 {"BadJSON", `{`, "unexpected EOF"},
150 {"Null", `null`, "cannot decode JSON null into a syntax node"},
151 {"RootString", `"x"`, "cannot decode JSON string into syntax.Node"},
152 {"RootNumber", `3`, "cannot decode JSON number into syntax.Node"},
153 {"RootBool", `true`, "cannot decode JSON boolean into syntax.Node"},
154 {"RootArray", `[]`, "cannot decode JSON array into syntax.Node"},
155 {"RootNoType", `{}`, `missing "Type" to decode a JSON object into syntax.Node`},
156 {"UnknownType", `{"Type":"Foo"}`, `unknown type: "Foo"`},
157 {"UnknownField", `{"Type":"File","Foo":3}`, `unknown field for syntax.File: "Foo"`},
158
159 {"StringIntoSlice", `{"Type":"File","Stmts":"x"}`, "cannot decode JSON string into []*syntax.Stmt"},
160 {"NumberIntoSlice", `{"Type":"File","Stmts":3}`, "cannot decode JSON number into []*syntax.Stmt"},
161 {"ObjectIntoSlice", `{"Type":"File","Stmts":{}}`, "cannot decode JSON object into []*syntax.Stmt"},
162 {"NumberIntoString", `{"Type":"File","Name":3}`, "cannot decode JSON number into string"},
163 {"ArrayIntoString", `{"Type":"File","Name":[]}`, "cannot decode JSON array into string"},
164 {"BoolIntoString", `{"Type":"File","Name":true}`, "cannot decode JSON boolean into string"},
165 {"StringIntoBool", `{"Type":"Word","Parts":[{"Type":"ParamExp","Short":"x"}]}`, "cannot decode JSON string into bool"},
166 {"ArrayIntoStruct", `{"Type":"File","Stmts":[[]]}`, "cannot decode JSON array into *syntax.Stmt"},
167 {"MismatchedType", `{"Type":"File","Stmts":[{"Cmd":{"Type":"Word"}}]}`, "cannot decode Word into syntax.Command"},
168 {"NoTypeForInterface", `{"Type":"File","Stmts":[{"Cmd":{}}]}`, `missing "Type" to decode a JSON object into syntax.Command`},
169
170 {"StringIntoPos", `{"Type":"Lit","ValuePos":"x"}`, `cannot decode JSON string into a position`},
171 {"ArrayIntoPos", `{"Type":"Lit","ValuePos":[]}`, `cannot decode JSON array into a position`},
172 {"PosMissingField", `{"Type":"Lit","ValuePos":{"Offset":0,"Line":1}}`, `a position must contain exactly the fields [Offset Line Col]`},
173 {"PosWrongField", `{"Type":"Lit","ValuePos":{"Offset":0,"Line":1,"Column":1}}`, `a position must contain the field "Col"`},
174 {"PosStringField", `{"Type":"Lit","ValuePos":{"Offset":0,"Line":1,"Col":"x"}}`, `cannot decode JSON string into the position field "Col"`},
175 {"PosNegativeField", `{"Type":"Lit","ValuePos":{"Offset":-1,"Line":1,"Col":1}}`, `the position field "Offset" is out of range: -1`},
176 {"PosHugeField", `{"Type":"Lit","ValuePos":{"Offset":1e30,"Line":1,"Col":1}}`, `the position field "Offset" is out of range: 1e+30`},
177 {"PosFractionField", `{"Type":"Lit","ValuePos":{"Offset":1.5,"Line":1,"Col":1}}`, `the position field "Offset" is out of range: 1.5`},
178
179 {"UnknownOperator", `{"Type":"ExtGlob","Op":"x"}`, `invalid GlobOperator: "x"`},
180 {"NumberIntoOperator", `{"Type":"ExtGlob","Op":3}`, "cannot decode JSON number into syntax.GlobOperator; a string is required"},
181 {"OptStateOverflow", `{"Type":"ParamExp","Split":300}`, "cannot decode the JSON number 300 into syntax.OptState"},
182 {"OptStateNegative", `{"Type":"ParamExp","Split":-1}`, "cannot decode the JSON number -1 into syntax.OptState"},
183 }
184 for _, test := range tests {
185 t.Run(test.name, func(t *testing.T) {
186 t.Parallel()
187
188 node, err := typedjson.Decode(strings.NewReader(test.input))
189 qt.Assert(t, qt.IsNil(node))
190 qt.Assert(t, qt.IsNotNil(err))
191 qt.Assert(t, qt.StringContains(err.Error(), test.want))
192 })
193 }
194 }
195
196 // FuzzDecode checks that no input can cause the decoder to panic.
197 // Note that a decoded tree may still be incomplete, such as a binary command
198 // missing its operands, which the printer and interpreter do not support.
199 func FuzzDecode(f *testing.F) {
200 jsonInput, err := os.ReadFile(filepath.Join("testdata", "roundtrip", "file.json"))
201 qt.Assert(f, qt.IsNil(err))
202 f.Add(string(jsonInput))
203 f.Add(`{"Type":"File","Stmts":"x"}`)
204 f.Add(`{"Type":"Lit","ValuePos":{"Offset":0,"Line":1,"Col":1},"Value":"x"}`)
205 f.Add(`{"Type":"Word","Parts":[{"Type":"ParamExp","Excl":true,"Names":"@"}]}`)
206
207 f.Fuzz(func(t *testing.T, src string) {
208 typedjson.Decode(strings.NewReader(src))
209 })
210 }
211
212 func TestRoundtrip(t *testing.T) {
213 t.Parallel()
214
215 dir := filepath.Join("testdata", "roundtrip")
216 shellPaths, err := filepath.Glob(filepath.Join(dir, "*.sh"))
217 qt.Assert(t, qt.IsNil(err))
218 for _, shellPath := range shellPaths {
219 name := strings.TrimSuffix(filepath.Base(shellPath), ".sh")
220 jsonPath := filepath.Join(dir, name+".json")
221 t.Run(name, func(t *testing.T) {
222 t.Parallel()
223
224 shellInput, err := os.ReadFile(shellPath)
225 qt.Assert(t, qt.IsNil(err))
226 jsonInput, err := os.ReadFile(jsonPath)
227 if !*update { // allow it to not exist
228 qt.Assert(t, qt.IsNil(err))
229 }
230 sb := new(strings.Builder)
231
232 // Parse the shell source and check that it is well formatted.
233 parser := syntax.NewParser(syntax.KeepComments(true))
234 node, err := parser.Parse(bytes.NewReader(shellInput), "")
235 qt.Assert(t, qt.IsNil(err))
236
237 printer := syntax.NewPrinter()
238 sb.Reset()
239 err = printer.Print(sb, node)
240 qt.Assert(t, qt.IsNil(err))
241 qt.Assert(t, qt.Equals(sb.String(), string(shellInput)))
242
243 // Validate writing the pretty JSON.
244 sb.Reset()
245 encOpts := typedjson.EncodeOptions{Indent: "\t"}
246 err = encOpts.Encode(sb, node)
247 qt.Assert(t, qt.IsNil(err))
248 got := sb.String()
249 if *update {
250 err := os.WriteFile(jsonPath, []byte(got), 0o666)
251 qt.Assert(t, qt.IsNil(err))
252 } else {
253 qt.Assert(t, qt.Equals(got, string(jsonInput)))
254 }
255
256 // Ensure we don't use the originally parsed node again.
257 node = nil
258
259 // Validate reading the pretty JSON and check that it formats the same.
260 node2, err := typedjson.Decode(bytes.NewReader(jsonInput))
261 qt.Assert(t, qt.IsNil(err))
262
263 sb.Reset()
264 err = printer.Print(sb, node2)
265 qt.Assert(t, qt.IsNil(err))
266 qt.Assert(t, qt.Equals(sb.String(), string(shellInput)))
267
268 // Validate that emitting the JSON again produces the same result.
269 sb.Reset()
270 err = encOpts.Encode(sb, node2)
271 qt.Assert(t, qt.IsNil(err))
272 got = sb.String()
273 qt.Assert(t, qt.Equals(got, string(jsonInput)))
274 })
275 }
276 }