parse_test.go (23286B)
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build go1.13
6 // +build go1.13
7
8 package parse
9
10 import (
11 "flag"
12 "fmt"
13 "strings"
14 "testing"
15 )
16
17 var debug = flag.Bool("debug", false, "show the errors produced by the main tests")
18
19 type numberTest struct {
20 text string
21 isInt bool
22 isUint bool
23 isFloat bool
24 isComplex bool
25 int64
26 uint64
27 float64
28 complex128
29 }
30
31 var numberTests = []numberTest{
32 // basics
33 {"0", true, true, true, false, 0, 0, 0, 0},
34 {"-0", true, true, true, false, 0, 0, 0, 0}, // check that -0 is a uint.
35 {"73", true, true, true, false, 73, 73, 73, 0},
36 {"7_3", true, true, true, false, 73, 73, 73, 0},
37 {"0b10_010_01", true, true, true, false, 73, 73, 73, 0},
38 {"0B10_010_01", true, true, true, false, 73, 73, 73, 0},
39 {"073", true, true, true, false, 073, 073, 073, 0},
40 {"0o73", true, true, true, false, 073, 073, 073, 0},
41 {"0O73", true, true, true, false, 073, 073, 073, 0},
42 {"0x73", true, true, true, false, 0x73, 0x73, 0x73, 0},
43 {"0X73", true, true, true, false, 0x73, 0x73, 0x73, 0},
44 {"0x7_3", true, true, true, false, 0x73, 0x73, 0x73, 0},
45 {"-73", true, false, true, false, -73, 0, -73, 0},
46 {"+73", true, false, true, false, 73, 0, 73, 0},
47 {"100", true, true, true, false, 100, 100, 100, 0},
48 {"1e9", true, true, true, false, 1e9, 1e9, 1e9, 0},
49 {"-1e9", true, false, true, false, -1e9, 0, -1e9, 0},
50 {"-1.2", false, false, true, false, 0, 0, -1.2, 0},
51 {"1e19", false, true, true, false, 0, 1e19, 1e19, 0},
52 {"1e1_9", false, true, true, false, 0, 1e19, 1e19, 0},
53 {"1E19", false, true, true, false, 0, 1e19, 1e19, 0},
54 {"-1e19", false, false, true, false, 0, 0, -1e19, 0},
55 {"0x_1p4", true, true, true, false, 16, 16, 16, 0},
56 {"0X_1P4", true, true, true, false, 16, 16, 16, 0},
57 {"0x_1p-4", false, false, true, false, 0, 0, 1 / 16., 0},
58 {"4i", false, false, false, true, 0, 0, 0, 4i},
59 {"-1.2+4.2i", false, false, false, true, 0, 0, 0, -1.2 + 4.2i},
60 {"073i", false, false, false, true, 0, 0, 0, 73i}, // not octal!
61 // complex with 0 imaginary are float (and maybe integer)
62 {"0i", true, true, true, true, 0, 0, 0, 0},
63 {"-1.2+0i", false, false, true, true, 0, 0, -1.2, -1.2},
64 {"-12+0i", true, false, true, true, -12, 0, -12, -12},
65 {"13+0i", true, true, true, true, 13, 13, 13, 13},
66 // funny bases
67 {"0123", true, true, true, false, 0123, 0123, 0123, 0},
68 {"-0x0", true, true, true, false, 0, 0, 0, 0},
69 {"0xdeadbeef", true, true, true, false, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0},
70 // character constants
71 {`'a'`, true, true, true, false, 'a', 'a', 'a', 0},
72 {`'\n'`, true, true, true, false, '\n', '\n', '\n', 0},
73 {`'\\'`, true, true, true, false, '\\', '\\', '\\', 0},
74 {`'\''`, true, true, true, false, '\'', '\'', '\'', 0},
75 {`'\xFF'`, true, true, true, false, 0xFF, 0xFF, 0xFF, 0},
76 {`'パ'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0},
77 {`'\u30d1'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0},
78 {`'\U000030d1'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0},
79 // some broken syntax
80 {text: "+-2"},
81 {text: "0x123."},
82 {text: "1e."},
83 {text: "0xi."},
84 {text: "1+2."},
85 {text: "'x"},
86 {text: "'xx'"},
87 {text: "'433937734937734969526500969526500'"}, // Integer too large - issue 10634.
88 // Issue 8622 - 0xe parsed as floating point. Very embarrassing.
89 {"0xef", true, true, true, false, 0xef, 0xef, 0xef, 0},
90 }
91
92 func TestNumberParse(t *testing.T) {
93 for _, test := range numberTests {
94 // If fmt.Sscan thinks it's complex, it's complex. We can't trust the output
95 // because imaginary comes out as a number.
96 var c complex128
97 typ := itemNumber
98 var tree *Tree
99 if test.text[0] == '\'' {
100 typ = itemCharConstant
101 } else {
102 _, err := fmt.Sscan(test.text, &c)
103 if err == nil {
104 typ = itemComplex
105 }
106 }
107 n, err := tree.newNumber(0, test.text, typ)
108 ok := test.isInt || test.isUint || test.isFloat || test.isComplex
109 if ok && err != nil {
110 t.Errorf("unexpected error for %q: %s", test.text, err)
111 continue
112 }
113 if !ok && err == nil {
114 t.Errorf("expected error for %q", test.text)
115 continue
116 }
117 if !ok {
118 if *debug {
119 fmt.Printf("%s\n\t%s\n", test.text, err)
120 }
121 continue
122 }
123 if n.IsComplex != test.isComplex {
124 t.Errorf("complex incorrect for %q; should be %t", test.text, test.isComplex)
125 }
126 if test.isInt {
127 if !n.IsInt {
128 t.Errorf("expected integer for %q", test.text)
129 }
130 if n.Int64 != test.int64 {
131 t.Errorf("int64 for %q should be %d Is %d", test.text, test.int64, n.Int64)
132 }
133 } else if n.IsInt {
134 t.Errorf("did not expect integer for %q", test.text)
135 }
136 if test.isUint {
137 if !n.IsUint {
138 t.Errorf("expected unsigned integer for %q", test.text)
139 }
140 if n.Uint64 != test.uint64 {
141 t.Errorf("uint64 for %q should be %d Is %d", test.text, test.uint64, n.Uint64)
142 }
143 } else if n.IsUint {
144 t.Errorf("did not expect unsigned integer for %q", test.text)
145 }
146 if test.isFloat {
147 if !n.IsFloat {
148 t.Errorf("expected float for %q", test.text)
149 }
150 if n.Float64 != test.float64 {
151 t.Errorf("float64 for %q should be %g Is %g", test.text, test.float64, n.Float64)
152 }
153 } else if n.IsFloat {
154 t.Errorf("did not expect float for %q", test.text)
155 }
156 if test.isComplex {
157 if !n.IsComplex {
158 t.Errorf("expected complex for %q", test.text)
159 }
160 if n.Complex128 != test.complex128 {
161 t.Errorf("complex128 for %q should be %g Is %g", test.text, test.complex128, n.Complex128)
162 }
163 } else if n.IsComplex {
164 t.Errorf("did not expect complex for %q", test.text)
165 }
166 }
167 }
168
169 type parseTest struct {
170 name string
171 input string
172 ok bool
173 result string // what the user would see in an error message.
174 }
175
176 const (
177 noError = true
178 hasError = false
179 )
180
181 var parseTests = []parseTest{
182 {"empty", "", noError,
183 ``},
184 {"comment", "{{/*\n\n\n*/}}", noError,
185 ``},
186 {"spaces", " \t\n", noError,
187 `" \t\n"`},
188 {"text", "some text", noError,
189 `"some text"`},
190 {"emptyAction", "{{}}", hasError,
191 `{{}}`},
192 {"field", "{{.X}}", noError,
193 `{{.X}}`},
194 {"simple command", "{{printf}}", noError,
195 `{{printf}}`},
196 {"$ invocation", "{{$}}", noError,
197 "{{$}}"},
198 {"variable invocation", "{{with $x := 3}}{{$x 23}}{{end}}", noError,
199 "{{with $x := 3}}{{$x 23}}{{end}}"},
200 {"variable with fields", "{{$.I}}", noError,
201 "{{$.I}}"},
202 {"multi-word command", "{{printf `%d` 23}}", noError,
203 "{{printf `%d` 23}}"},
204 {"pipeline", "{{.X|.Y}}", noError,
205 `{{.X | .Y}}`},
206 {"pipeline with decl", "{{$x := .X|.Y}}", noError,
207 `{{$x := .X | .Y}}`},
208 {"nested pipeline", "{{.X (.Y .Z) (.A | .B .C) (.E)}}", noError,
209 `{{.X (.Y .Z) (.A | .B .C) (.E)}}`},
210 {"field applied to parentheses", "{{(.Y .Z).Field}}", noError,
211 `{{(.Y .Z).Field}}`},
212 {"simple if", "{{if .X}}hello{{end}}", noError,
213 `{{if .X}}"hello"{{end}}`},
214 {"if with else", "{{if .X}}true{{else}}false{{end}}", noError,
215 `{{if .X}}"true"{{else}}"false"{{end}}`},
216 {"if with else if", "{{if .X}}true{{else if .Y}}false{{end}}", noError,
217 `{{if .X}}"true"{{else}}{{if .Y}}"false"{{end}}{{end}}`},
218 {"if else chain", "+{{if .X}}X{{else if .Y}}Y{{else if .Z}}Z{{end}}+", noError,
219 `"+"{{if .X}}"X"{{else}}{{if .Y}}"Y"{{else}}{{if .Z}}"Z"{{end}}{{end}}{{end}}"+"`},
220 {"simple range", "{{range .X}}hello{{end}}", noError,
221 `{{range .X}}"hello"{{end}}`},
222 {"chained field range", "{{range .X.Y.Z}}hello{{end}}", noError,
223 `{{range .X.Y.Z}}"hello"{{end}}`},
224 {"nested range", "{{range .X}}hello{{range .Y}}goodbye{{end}}{{end}}", noError,
225 `{{range .X}}"hello"{{range .Y}}"goodbye"{{end}}{{end}}`},
226 {"range with else", "{{range .X}}true{{else}}false{{end}}", noError,
227 `{{range .X}}"true"{{else}}"false"{{end}}`},
228 {"range over pipeline", "{{range .X|.M}}true{{else}}false{{end}}", noError,
229 `{{range .X | .M}}"true"{{else}}"false"{{end}}`},
230 {"range []int", "{{range .SI}}{{.}}{{end}}", noError,
231 `{{range .SI}}{{.}}{{end}}`},
232 {"range 1 var", "{{range $x := .SI}}{{.}}{{end}}", noError,
233 `{{range $x := .SI}}{{.}}{{end}}`},
234 {"range 2 vars", "{{range $x, $y := .SI}}{{.}}{{end}}", noError,
235 `{{range $x, $y := .SI}}{{.}}{{end}}`},
236 {"range with break", "{{range .SI}}{{.}}{{break}}{{end}}", noError,
237 `{{range .SI}}{{.}}{{break}}{{end}}`},
238 {"range with continue", "{{range .SI}}{{.}}{{continue}}{{end}}", noError,
239 `{{range .SI}}{{.}}{{continue}}{{end}}`},
240 {"constants", "{{range .SI 1 -3.2i true false 'a' nil}}{{end}}", noError,
241 `{{range .SI 1 -3.2i true false 'a' nil}}{{end}}`},
242 {"template", "{{template `x`}}", noError,
243 `{{template "x"}}`},
244 {"template with arg", "{{template `x` .Y}}", noError,
245 `{{template "x" .Y}}`},
246 {"with", "{{with .X}}hello{{end}}", noError,
247 `{{with .X}}"hello"{{end}}`},
248 {"with with else", "{{with .X}}hello{{else}}goodbye{{end}}", noError,
249 `{{with .X}}"hello"{{else}}"goodbye"{{end}}`},
250 // Trimming spaces.
251 {"trim left", "x \r\n\t{{- 3}}", noError, `"x"{{3}}`},
252 {"trim right", "{{3 -}}\n\n\ty", noError, `{{3}}"y"`},
253 {"trim left and right", "x \r\n\t{{- 3 -}}\n\n\ty", noError, `"x"{{3}}"y"`},
254 {"trim with extra spaces", "x\n{{- 3 -}}\ny", noError, `"x"{{3}}"y"`},
255 {"comment trim left", "x \r\n\t{{- /* hi */}}", noError, `"x"`},
256 {"comment trim right", "{{/* hi */ -}}\n\n\ty", noError, `"y"`},
257 {"comment trim left and right", "x \r\n\t{{- /* */ -}}\n\n\ty", noError, `"x""y"`},
258 {"block definition", `{{block "foo" .}}hello{{end}}`, noError,
259 `{{template "foo" .}}`},
260
261 {"newline in assignment", "{{ $x \n := \n 1 \n }}", noError, "{{$x := 1}}"},
262 {"newline in empty action", "{{\n}}", hasError, "{{\n}}"},
263 {"newline in pipeline", "{{\n\"x\"\n|\nprintf\n}}", noError, `{{"x" | printf}}`},
264 {"newline in comment", "{{/*\nhello\n*/}}", noError, ""},
265 {"newline in comment", "{{-\n/*\nhello\n*/\n-}}", noError, ""},
266 {"spaces around continue", "{{range .SI}}{{.}}{{ continue }}{{end}}", noError,
267 `{{range .SI}}{{.}}{{continue}}{{end}}`},
268 {"spaces around break", "{{range .SI}}{{.}}{{ break }}{{end}}", noError,
269 `{{range .SI}}{{.}}{{break}}{{end}}`},
270
271 // Errors.
272 {"unclosed action", "hello{{range", hasError, ""},
273 {"unmatched end", "{{end}}", hasError, ""},
274 {"unmatched else", "{{else}}", hasError, ""},
275 {"unmatched else after if", "{{if .X}}hello{{end}}{{else}}", hasError, ""},
276 {"multiple else", "{{if .X}}1{{else}}2{{else}}3{{end}}", hasError, ""},
277 {"missing end", "hello{{range .x}}", hasError, ""},
278 {"missing end after else", "hello{{range .x}}{{else}}", hasError, ""},
279 {"undefined function", "hello{{undefined}}", hasError, ""},
280 {"undefined variable", "{{$x}}", hasError, ""},
281 {"variable undefined after end", "{{with $x := 4}}{{end}}{{$x}}", hasError, ""},
282 {"variable undefined in template", "{{template $v}}", hasError, ""},
283 {"declare with field", "{{with $x.Y := 4}}{{end}}", hasError, ""},
284 {"template with field ref", "{{template .X}}", hasError, ""},
285 {"template with var", "{{template $v}}", hasError, ""},
286 {"invalid punctuation", "{{printf 3, 4}}", hasError, ""},
287 {"multidecl outside range", "{{with $v, $u := 3}}{{end}}", hasError, ""},
288 {"too many decls in range", "{{range $u, $v, $w := 3}}{{end}}", hasError, ""},
289 {"dot applied to parentheses", "{{printf (printf .).}}", hasError, ""},
290 {"adjacent args", "{{printf 3`x`}}", hasError, ""},
291 {"adjacent args with .", "{{printf `x`.}}", hasError, ""},
292 {"extra end after if", "{{if .X}}a{{else if .Y}}b{{end}}{{end}}", hasError, ""},
293 {"break outside range", "{{range .}}{{end}} {{break}}", hasError, ""},
294 {"continue outside range", "{{range .}}{{end}} {{continue}}", hasError, ""},
295 {"break in range else", "{{range .}}{{else}}{{break}}{{end}}", hasError, ""},
296 {"continue in range else", "{{range .}}{{else}}{{continue}}{{end}}", hasError, ""},
297 // Other kinds of assignments and operators aren't available yet.
298 {"bug0a", "{{$x := 0}}{{$x}}", noError, "{{$x := 0}}{{$x}}"},
299 {"bug0b", "{{$x += 1}}{{$x}}", hasError, ""},
300 {"bug0c", "{{$x ! 2}}{{$x}}", hasError, ""},
301 {"bug0d", "{{$x % 3}}{{$x}}", hasError, ""},
302 // Check the parse fails for := rather than comma.
303 {"bug0e", "{{range $x := $y := 3}}{{end}}", hasError, ""},
304 // Another bug: variable read must ignore following punctuation.
305 {"bug1a", "{{$x:=.}}{{$x!2}}", hasError, ""}, // ! is just illegal here.
306 {"bug1b", "{{$x:=.}}{{$x+2}}", hasError, ""}, // $x+2 should not parse as ($x) (+2).
307 {"bug1c", "{{$x:=.}}{{$x +2}}", noError, "{{$x := .}}{{$x +2}}"}, // It's OK with a space.
308 // dot following a literal value
309 {"dot after integer", "{{1.E}}", hasError, ""},
310 {"dot after float", "{{0.1.E}}", hasError, ""},
311 {"dot after boolean", "{{true.E}}", hasError, ""},
312 {"dot after char", "{{'a'.any}}", hasError, ""},
313 {"dot after string", `{{"hello".guys}}`, hasError, ""},
314 {"dot after dot", "{{..E}}", hasError, ""},
315 {"dot after nil", "{{nil.E}}", hasError, ""},
316 // Wrong pipeline
317 {"wrong pipeline dot", "{{12|.}}", hasError, ""},
318 {"wrong pipeline number", "{{.|12|printf}}", hasError, ""},
319 {"wrong pipeline string", "{{.|printf|\"error\"}}", hasError, ""},
320 {"wrong pipeline char", "{{12|printf|'e'}}", hasError, ""},
321 {"wrong pipeline boolean", "{{.|true}}", hasError, ""},
322 {"wrong pipeline nil", "{{'c'|nil}}", hasError, ""},
323 {"empty pipeline", `{{printf "%d" ( ) }}`, hasError, ""},
324 // Missing pipeline in block
325 {"block definition", `{{block "foo"}}hello{{end}}`, hasError, ""},
326 }
327
328 var builtins = map[string]any{
329 "printf": fmt.Sprintf,
330 "contains": strings.Contains,
331 }
332
333 func testParse(doCopy bool, t *testing.T) {
334 textFormat = "%q"
335 defer func() { textFormat = "%s" }()
336 for _, test := range parseTests {
337 tmpl, err := New(test.name).Parse(test.input, "", "", make(map[string]*Tree), builtins)
338 switch {
339 case err == nil && !test.ok:
340 t.Errorf("%q: expected error; got none", test.name)
341 continue
342 case err != nil && test.ok:
343 t.Errorf("%q: unexpected error: %v", test.name, err)
344 continue
345 case err != nil && !test.ok:
346 // expected error, got one
347 if *debug {
348 fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)
349 }
350 continue
351 }
352 var result string
353 if doCopy {
354 result = tmpl.Root.Copy().String()
355 } else {
356 result = tmpl.Root.String()
357 }
358 if result != test.result {
359 t.Errorf("%s=(%q): got\n\t%v\nexpected\n\t%v", test.name, test.input, result, test.result)
360 }
361 }
362 }
363
364 func TestParse(t *testing.T) {
365 testParse(false, t)
366 }
367
368 // Same as TestParse, but we copy the node first
369 func TestParseCopy(t *testing.T) {
370 testParse(true, t)
371 }
372
373 func TestParseWithComments(t *testing.T) {
374 textFormat = "%q"
375 defer func() { textFormat = "%s" }()
376 tests := [...]parseTest{
377 {"comment", "{{/*\n\n\n*/}}", noError, "{{/*\n\n\n*/}}"},
378 {"comment trim left", "x \r\n\t{{- /* hi */}}", noError, `"x"{{/* hi */}}`},
379 {"comment trim right", "{{/* hi */ -}}\n\n\ty", noError, `{{/* hi */}}"y"`},
380 {"comment trim left and right", "x \r\n\t{{- /* */ -}}\n\n\ty", noError, `"x"{{/* */}}"y"`},
381 }
382 for _, test := range tests {
383 t.Run(test.name, func(t *testing.T) {
384 tr := New(test.name)
385 tr.Mode = ParseComments
386 tmpl, err := tr.Parse(test.input, "", "", make(map[string]*Tree))
387 if err != nil {
388 t.Errorf("%q: expected error; got none", test.name)
389 }
390 if result := tmpl.Root.String(); result != test.result {
391 t.Errorf("%s=(%q): got\n\t%v\nexpected\n\t%v", test.name, test.input, result, test.result)
392 }
393 })
394 }
395 }
396
397 func TestSkipFuncCheck(t *testing.T) {
398 oldTextFormat := textFormat
399 textFormat = "%q"
400 defer func() { textFormat = oldTextFormat }()
401 tr := New("skip func check")
402 tr.Mode = SkipFuncCheck
403 tmpl, err := tr.Parse("{{fn 1 2}}", "", "", make(map[string]*Tree))
404 if err != nil {
405 t.Fatalf("unexpected error: %v", err)
406 }
407 expected := "{{fn 1 2}}"
408 if result := tmpl.Root.String(); result != expected {
409 t.Errorf("got\n\t%v\nexpected\n\t%v", result, expected)
410 }
411 }
412
413 type isEmptyTest struct {
414 name string
415 input string
416 empty bool
417 }
418
419 var isEmptyTests = []isEmptyTest{
420 {"empty", ``, true},
421 {"nonempty", `hello`, false},
422 {"spaces only", " \t\n \t\n", true},
423 {"comment only", "{{/* comment */}}", true},
424 {"definition", `{{define "x"}}something{{end}}`, true},
425 {"definitions and space", "{{define `x`}}something{{end}}\n\n{{define `y`}}something{{end}}\n\n", true},
426 {"definitions and text", "{{define `x`}}something{{end}}\nx\n{{define `y`}}something{{end}}\ny\n", false},
427 {"definition and action", "{{define `x`}}something{{end}}{{if 3}}foo{{end}}", false},
428 }
429
430 func TestIsEmpty(t *testing.T) {
431 if !IsEmptyTree(nil) {
432 t.Errorf("nil tree is not empty")
433 }
434 for _, test := range isEmptyTests {
435 tree, err := New("root").Parse(test.input, "", "", make(map[string]*Tree), nil)
436 if err != nil {
437 t.Errorf("%q: unexpected error: %v", test.name, err)
438 continue
439 }
440 if empty := IsEmptyTree(tree.Root); empty != test.empty {
441 t.Errorf("%q: expected %t got %t", test.name, test.empty, empty)
442 }
443 }
444 }
445
446 func TestErrorContextWithTreeCopy(t *testing.T) {
447 tree, err := New("root").Parse("{{if true}}{{end}}", "", "", make(map[string]*Tree), nil)
448 if err != nil {
449 t.Fatalf("unexpected tree parse failure: %v", err)
450 }
451 treeCopy := tree.Copy()
452 wantLocation, wantContext := tree.ErrorContext(tree.Root.Nodes[0])
453 gotLocation, gotContext := treeCopy.ErrorContext(treeCopy.Root.Nodes[0])
454 if wantLocation != gotLocation {
455 t.Errorf("wrong error location want %q got %q", wantLocation, gotLocation)
456 }
457 if wantContext != gotContext {
458 t.Errorf("wrong error location want %q got %q", wantContext, gotContext)
459 }
460 }
461
462 // All failures, and the result is a string that must appear in the error message.
463 var errorTests = []parseTest{
464 // Check line numbers are accurate.
465 {"unclosed1",
466 "line1\n{{",
467 hasError, `unclosed1:2: unclosed action`},
468 {"unclosed2",
469 "line1\n{{define `x`}}line2\n{{",
470 hasError, `unclosed2:3: unclosed action`},
471 {"unclosed3",
472 "line1\n{{\"x\"\n\"y\"\n",
473 hasError, `unclosed3:4: unclosed action started at unclosed3:2`},
474 {"unclosed4",
475 "{{\n\n\n\n\n",
476 hasError, `unclosed4:6: unclosed action started at unclosed4:1`},
477 {"var1",
478 "line1\n{{\nx\n}}",
479 hasError, `var1:3: function "x" not defined`},
480 // Specific errors.
481 {"function",
482 "{{foo}}",
483 hasError, `function "foo" not defined`},
484 {"comment1",
485 "{{/*}}",
486 hasError, `comment1:1: unclosed comment`},
487 {"comment2",
488 "{{/*\nhello\n}}",
489 hasError, `comment2:1: unclosed comment`},
490 {"lparen",
491 "{{.X (1 2 3}}",
492 hasError, `unclosed left paren`},
493 {"rparen",
494 "{{.X 1 2 3 ) }}",
495 hasError, `unexpected ")" in command`},
496 {"rparen2",
497 "{{(.X 1 2 3",
498 hasError, `unclosed action`},
499 {"space",
500 "{{`x`3}}",
501 hasError, `in operand`},
502 {"idchar",
503 "{{a#}}",
504 hasError, `'#'`},
505 {"charconst",
506 "{{'a}}",
507 hasError, `unterminated character constant`},
508 {"stringconst",
509 `{{"a}}`,
510 hasError, `unterminated quoted string`},
511 {"rawstringconst",
512 "{{`a}}",
513 hasError, `unterminated raw quoted string`},
514 {"number",
515 "{{0xi}}",
516 hasError, `number syntax`},
517 {"multidefine",
518 "{{define `a`}}a{{end}}{{define `a`}}b{{end}}",
519 hasError, `multiple definition of template`},
520 {"eof",
521 "{{range .X}}",
522 hasError, `unexpected EOF`},
523 {"variable",
524 // Declare $x so it's defined, to avoid that error, and then check we don't parse a declaration.
525 "{{$x := 23}}{{with $x.y := 3}}{{$x 23}}{{end}}",
526 hasError, `unexpected ":="`},
527 {"multidecl",
528 "{{$a,$b,$c := 23}}",
529 hasError, `too many declarations`},
530 {"undefvar",
531 "{{$a}}",
532 hasError, `undefined variable`},
533 {"wrongdot",
534 "{{true.any}}",
535 hasError, `unexpected . after term`},
536 {"wrongpipeline",
537 "{{12|false}}",
538 hasError, `non executable command in pipeline`},
539 {"emptypipeline",
540 `{{ ( ) }}`,
541 hasError, `missing value for parenthesized pipeline`},
542 {"multilinerawstring",
543 "{{ $v := `\n` }} {{",
544 hasError, `multilinerawstring:2: unclosed action`},
545 {"rangeundefvar",
546 "{{range $k}}{{end}}",
547 hasError, `undefined variable`},
548 {"rangeundefvars",
549 "{{range $k, $v}}{{end}}",
550 hasError, `undefined variable`},
551 {"rangemissingvalue1",
552 "{{range $k,}}{{end}}",
553 hasError, `missing value for range`},
554 {"rangemissingvalue2",
555 "{{range $k, $v := }}{{end}}",
556 hasError, `missing value for range`},
557 {"rangenotvariable1",
558 "{{range $k, .}}{{end}}",
559 hasError, `range can only initialize variables`},
560 {"rangenotvariable2",
561 "{{range $k, 123 := .}}{{end}}",
562 hasError, `range can only initialize variables`},
563 }
564
565 func TestErrors(t *testing.T) {
566 for _, test := range errorTests {
567 t.Run(test.name, func(t *testing.T) {
568 _, err := New(test.name).Parse(test.input, "", "", make(map[string]*Tree))
569 if err == nil {
570 t.Fatalf("expected error %q, got nil", test.result)
571 }
572 if !strings.Contains(err.Error(), test.result) {
573 t.Fatalf("error %q does not contain %q", err, test.result)
574 }
575 })
576 }
577 }
578
579 func TestBlock(t *testing.T) {
580 const (
581 input = `a{{block "inner" .}}bar{{.}}baz{{end}}b`
582 outer = `a{{template "inner" .}}b`
583 inner = `bar{{.}}baz`
584 )
585 treeSet := make(map[string]*Tree)
586 tmpl, err := New("outer").Parse(input, "", "", treeSet, nil)
587 if err != nil {
588 t.Fatal(err)
589 }
590 if g, w := tmpl.Root.String(), outer; g != w {
591 t.Errorf("outer template = %q, want %q", g, w)
592 }
593 inTmpl := treeSet["inner"]
594 if inTmpl == nil {
595 t.Fatal("block did not define template")
596 }
597 if g, w := inTmpl.Root.String(), inner; g != w {
598 t.Errorf("inner template = %q, want %q", g, w)
599 }
600 }
601
602 func TestLineNum(t *testing.T) {
603 const count = 100
604 text := strings.Repeat("{{printf 1234}}\n", count)
605 tree, err := New("bench").Parse(text, "", "", make(map[string]*Tree), builtins)
606 if err != nil {
607 t.Fatal(err)
608 }
609 // Check the line numbers. Each line is an action containing a template, followed by text.
610 // That's two nodes per line.
611 nodes := tree.Root.Nodes
612 for i := 0; i < len(nodes); i += 2 {
613 line := 1 + i/2
614 // Action first.
615 action := nodes[i].(*ActionNode)
616 if action.Line != line {
617 t.Fatalf("line %d: action is line %d", line, action.Line)
618 }
619 pipe := action.Pipe
620 if pipe.Line != line {
621 t.Fatalf("line %d: pipe is line %d", line, pipe.Line)
622 }
623 }
624 }
625
626 func BenchmarkParseLarge(b *testing.B) {
627 text := strings.Repeat("{{1234}}\n", 10000)
628 for i := 0; i < b.N; i++ {
629 _, err := New("bench").Parse(text, "", "", make(map[string]*Tree), builtins)
630 if err != nil {
631 b.Fatal(err)
632 }
633 }
634 }
635
636 var sinkv, sinkl string
637
638 func BenchmarkVariableString(b *testing.B) {
639 v := &VariableNode{
640 Ident: []string{"$", "A", "BB", "CCC", "THIS_IS_THE_VARIABLE_BEING_PROCESSED"},
641 }
642 b.ResetTimer()
643 b.ReportAllocs()
644 for i := 0; i < b.N; i++ {
645 sinkv = v.String()
646 }
647 if sinkv == "" {
648 b.Fatal("Benchmark was not run")
649 }
650 }
651
652 func BenchmarkListString(b *testing.B) {
653 text := `
654 {{(printf .Field1.Field2.Field3).Value}}
655 {{$x := (printf .Field1.Field2.Field3).Value}}
656 {{$y := (printf $x.Field1.Field2.Field3).Value}}
657 {{$z := $y.Field1.Field2.Field3}}
658 {{if contains $y $z}}
659 {{printf "%q" $y}}
660 {{else}}
661 {{printf "%q" $x}}
662 {{end}}
663 {{with $z.Field1 | contains "boring"}}
664 {{printf "%q" . | printf "%s"}}
665 {{else}}
666 {{printf "%d %d %d" 11 11 11}}
667 {{printf "%d %d %s" 22 22 $x.Field1.Field2.Field3 | printf "%s"}}
668 {{printf "%v" (contains $z.Field1.Field2 $y)}}
669 {{end}}
670 `
671 tree, err := New("bench").Parse(text, "", "", make(map[string]*Tree), builtins)
672 if err != nil {
673 b.Fatal(err)
674 }
675 b.ResetTimer()
676 b.ReportAllocs()
677 for i := 0; i < b.N; i++ {
678 sinkl = tree.Root.String()
679 }
680 if sinkl == "" {
681 b.Fatal("Benchmark was not run")
682 }
683 }