Home | History | Annotate | Download | only in parse
      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 package parse
      6 
      7 import (
      8 	"flag"
      9 	"fmt"
     10 	"strings"
     11 	"testing"
     12 )
     13 
     14 var debug = flag.Bool("debug", false, "show the errors produced by the main tests")
     15 
     16 type numberTest struct {
     17 	text      string
     18 	isInt     bool
     19 	isUint    bool
     20 	isFloat   bool
     21 	isComplex bool
     22 	int64
     23 	uint64
     24 	float64
     25 	complex128
     26 }
     27 
     28 var numberTests = []numberTest{
     29 	// basics
     30 	{"0", true, true, true, false, 0, 0, 0, 0},
     31 	{"-0", true, true, true, false, 0, 0, 0, 0}, // check that -0 is a uint.
     32 	{"73", true, true, true, false, 73, 73, 73, 0},
     33 	{"073", true, true, true, false, 073, 073, 073, 0},
     34 	{"0x73", true, true, true, false, 0x73, 0x73, 0x73, 0},
     35 	{"-73", true, false, true, false, -73, 0, -73, 0},
     36 	{"+73", true, false, true, false, 73, 0, 73, 0},
     37 	{"100", true, true, true, false, 100, 100, 100, 0},
     38 	{"1e9", true, true, true, false, 1e9, 1e9, 1e9, 0},
     39 	{"-1e9", true, false, true, false, -1e9, 0, -1e9, 0},
     40 	{"-1.2", false, false, true, false, 0, 0, -1.2, 0},
     41 	{"1e19", false, true, true, false, 0, 1e19, 1e19, 0},
     42 	{"-1e19", false, false, true, false, 0, 0, -1e19, 0},
     43 	{"4i", false, false, false, true, 0, 0, 0, 4i},
     44 	{"-1.2+4.2i", false, false, false, true, 0, 0, 0, -1.2 + 4.2i},
     45 	{"073i", false, false, false, true, 0, 0, 0, 73i}, // not octal!
     46 	// complex with 0 imaginary are float (and maybe integer)
     47 	{"0i", true, true, true, true, 0, 0, 0, 0},
     48 	{"-1.2+0i", false, false, true, true, 0, 0, -1.2, -1.2},
     49 	{"-12+0i", true, false, true, true, -12, 0, -12, -12},
     50 	{"13+0i", true, true, true, true, 13, 13, 13, 13},
     51 	// funny bases
     52 	{"0123", true, true, true, false, 0123, 0123, 0123, 0},
     53 	{"-0x0", true, true, true, false, 0, 0, 0, 0},
     54 	{"0xdeadbeef", true, true, true, false, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0},
     55 	// character constants
     56 	{`'a'`, true, true, true, false, 'a', 'a', 'a', 0},
     57 	{`'\n'`, true, true, true, false, '\n', '\n', '\n', 0},
     58 	{`'\\'`, true, true, true, false, '\\', '\\', '\\', 0},
     59 	{`'\''`, true, true, true, false, '\'', '\'', '\'', 0},
     60 	{`'\xFF'`, true, true, true, false, 0xFF, 0xFF, 0xFF, 0},
     61 	{`''`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0},
     62 	{`'\u30d1'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0},
     63 	{`'\U000030d1'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0},
     64 	// some broken syntax
     65 	{text: "+-2"},
     66 	{text: "0x123."},
     67 	{text: "1e."},
     68 	{text: "0xi."},
     69 	{text: "1+2."},
     70 	{text: "'x"},
     71 	{text: "'xx'"},
     72 	{text: "'433937734937734969526500969526500'"}, // Integer too large - issue 10634.
     73 	// Issue 8622 - 0xe parsed as floating point. Very embarrassing.
     74 	{"0xef", true, true, true, false, 0xef, 0xef, 0xef, 0},
     75 }
     76 
     77 func TestNumberParse(t *testing.T) {
     78 	for _, test := range numberTests {
     79 		// If fmt.Sscan thinks it's complex, it's complex.  We can't trust the output
     80 		// because imaginary comes out as a number.
     81 		var c complex128
     82 		typ := itemNumber
     83 		var tree *Tree
     84 		if test.text[0] == '\'' {
     85 			typ = itemCharConstant
     86 		} else {
     87 			_, err := fmt.Sscan(test.text, &c)
     88 			if err == nil {
     89 				typ = itemComplex
     90 			}
     91 		}
     92 		n, err := tree.newNumber(0, test.text, typ)
     93 		ok := test.isInt || test.isUint || test.isFloat || test.isComplex
     94 		if ok && err != nil {
     95 			t.Errorf("unexpected error for %q: %s", test.text, err)
     96 			continue
     97 		}
     98 		if !ok && err == nil {
     99 			t.Errorf("expected error for %q", test.text)
    100 			continue
    101 		}
    102 		if !ok {
    103 			if *debug {
    104 				fmt.Printf("%s\n\t%s\n", test.text, err)
    105 			}
    106 			continue
    107 		}
    108 		if n.IsComplex != test.isComplex {
    109 			t.Errorf("complex incorrect for %q; should be %t", test.text, test.isComplex)
    110 		}
    111 		if test.isInt {
    112 			if !n.IsInt {
    113 				t.Errorf("expected integer for %q", test.text)
    114 			}
    115 			if n.Int64 != test.int64 {
    116 				t.Errorf("int64 for %q should be %d Is %d", test.text, test.int64, n.Int64)
    117 			}
    118 		} else if n.IsInt {
    119 			t.Errorf("did not expect integer for %q", test.text)
    120 		}
    121 		if test.isUint {
    122 			if !n.IsUint {
    123 				t.Errorf("expected unsigned integer for %q", test.text)
    124 			}
    125 			if n.Uint64 != test.uint64 {
    126 				t.Errorf("uint64 for %q should be %d Is %d", test.text, test.uint64, n.Uint64)
    127 			}
    128 		} else if n.IsUint {
    129 			t.Errorf("did not expect unsigned integer for %q", test.text)
    130 		}
    131 		if test.isFloat {
    132 			if !n.IsFloat {
    133 				t.Errorf("expected float for %q", test.text)
    134 			}
    135 			if n.Float64 != test.float64 {
    136 				t.Errorf("float64 for %q should be %g Is %g", test.text, test.float64, n.Float64)
    137 			}
    138 		} else if n.IsFloat {
    139 			t.Errorf("did not expect float for %q", test.text)
    140 		}
    141 		if test.isComplex {
    142 			if !n.IsComplex {
    143 				t.Errorf("expected complex for %q", test.text)
    144 			}
    145 			if n.Complex128 != test.complex128 {
    146 				t.Errorf("complex128 for %q should be %g Is %g", test.text, test.complex128, n.Complex128)
    147 			}
    148 		} else if n.IsComplex {
    149 			t.Errorf("did not expect complex for %q", test.text)
    150 		}
    151 	}
    152 }
    153 
    154 type parseTest struct {
    155 	name   string
    156 	input  string
    157 	ok     bool
    158 	result string // what the user would see in an error message.
    159 }
    160 
    161 const (
    162 	noError  = true
    163 	hasError = false
    164 )
    165 
    166 var parseTests = []parseTest{
    167 	{"empty", "", noError,
    168 		``},
    169 	{"comment", "{{/*\n\n\n*/}}", noError,
    170 		``},
    171 	{"spaces", " \t\n", noError,
    172 		`" \t\n"`},
    173 	{"text", "some text", noError,
    174 		`"some text"`},
    175 	{"emptyAction", "{{}}", hasError,
    176 		`{{}}`},
    177 	{"field", "{{.X}}", noError,
    178 		`{{.X}}`},
    179 	{"simple command", "{{printf}}", noError,
    180 		`{{printf}}`},
    181 	{"$ invocation", "{{$}}", noError,
    182 		"{{$}}"},
    183 	{"variable invocation", "{{with $x := 3}}{{$x 23}}{{end}}", noError,
    184 		"{{with $x := 3}}{{$x 23}}{{end}}"},
    185 	{"variable with fields", "{{$.I}}", noError,
    186 		"{{$.I}}"},
    187 	{"multi-word command", "{{printf `%d` 23}}", noError,
    188 		"{{printf `%d` 23}}"},
    189 	{"pipeline", "{{.X|.Y}}", noError,
    190 		`{{.X | .Y}}`},
    191 	{"pipeline with decl", "{{$x := .X|.Y}}", noError,
    192 		`{{$x := .X | .Y}}`},
    193 	{"nested pipeline", "{{.X (.Y .Z) (.A | .B .C) (.E)}}", noError,
    194 		`{{.X (.Y .Z) (.A | .B .C) (.E)}}`},
    195 	{"field applied to parentheses", "{{(.Y .Z).Field}}", noError,
    196 		`{{(.Y .Z).Field}}`},
    197 	{"simple if", "{{if .X}}hello{{end}}", noError,
    198 		`{{if .X}}"hello"{{end}}`},
    199 	{"if with else", "{{if .X}}true{{else}}false{{end}}", noError,
    200 		`{{if .X}}"true"{{else}}"false"{{end}}`},
    201 	{"if with else if", "{{if .X}}true{{else if .Y}}false{{end}}", noError,
    202 		`{{if .X}}"true"{{else}}{{if .Y}}"false"{{end}}{{end}}`},
    203 	{"if else chain", "+{{if .X}}X{{else if .Y}}Y{{else if .Z}}Z{{end}}+", noError,
    204 		`"+"{{if .X}}"X"{{else}}{{if .Y}}"Y"{{else}}{{if .Z}}"Z"{{end}}{{end}}{{end}}"+"`},
    205 	{"simple range", "{{range .X}}hello{{end}}", noError,
    206 		`{{range .X}}"hello"{{end}}`},
    207 	{"chained field range", "{{range .X.Y.Z}}hello{{end}}", noError,
    208 		`{{range .X.Y.Z}}"hello"{{end}}`},
    209 	{"nested range", "{{range .X}}hello{{range .Y}}goodbye{{end}}{{end}}", noError,
    210 		`{{range .X}}"hello"{{range .Y}}"goodbye"{{end}}{{end}}`},
    211 	{"range with else", "{{range .X}}true{{else}}false{{end}}", noError,
    212 		`{{range .X}}"true"{{else}}"false"{{end}}`},
    213 	{"range over pipeline", "{{range .X|.M}}true{{else}}false{{end}}", noError,
    214 		`{{range .X | .M}}"true"{{else}}"false"{{end}}`},
    215 	{"range []int", "{{range .SI}}{{.}}{{end}}", noError,
    216 		`{{range .SI}}{{.}}{{end}}`},
    217 	{"range 1 var", "{{range $x := .SI}}{{.}}{{end}}", noError,
    218 		`{{range $x := .SI}}{{.}}{{end}}`},
    219 	{"range 2 vars", "{{range $x, $y := .SI}}{{.}}{{end}}", noError,
    220 		`{{range $x, $y := .SI}}{{.}}{{end}}`},
    221 	{"constants", "{{range .SI 1 -3.2i true false 'a' nil}}{{end}}", noError,
    222 		`{{range .SI 1 -3.2i true false 'a' nil}}{{end}}`},
    223 	{"template", "{{template `x`}}", noError,
    224 		`{{template "x"}}`},
    225 	{"template with arg", "{{template `x` .Y}}", noError,
    226 		`{{template "x" .Y}}`},
    227 	{"with", "{{with .X}}hello{{end}}", noError,
    228 		`{{with .X}}"hello"{{end}}`},
    229 	{"with with else", "{{with .X}}hello{{else}}goodbye{{end}}", noError,
    230 		`{{with .X}}"hello"{{else}}"goodbye"{{end}}`},
    231 	// Errors.
    232 	{"unclosed action", "hello{{range", hasError, ""},
    233 	{"unmatched end", "{{end}}", hasError, ""},
    234 	{"unmatched else", "{{else}}", hasError, ""},
    235 	{"unmatched else after if", "{{if .X}}hello{{end}}{{else}}", hasError, ""},
    236 	{"multiple else", "{{if .X}}1{{else}}2{{else}}3{{end}}", hasError, ""},
    237 	{"missing end", "hello{{range .x}}", hasError, ""},
    238 	{"missing end after else", "hello{{range .x}}{{else}}", hasError, ""},
    239 	{"undefined function", "hello{{undefined}}", hasError, ""},
    240 	{"undefined variable", "{{$x}}", hasError, ""},
    241 	{"variable undefined after end", "{{with $x := 4}}{{end}}{{$x}}", hasError, ""},
    242 	{"variable undefined in template", "{{template $v}}", hasError, ""},
    243 	{"declare with field", "{{with $x.Y := 4}}{{end}}", hasError, ""},
    244 	{"template with field ref", "{{template .X}}", hasError, ""},
    245 	{"template with var", "{{template $v}}", hasError, ""},
    246 	{"invalid punctuation", "{{printf 3, 4}}", hasError, ""},
    247 	{"multidecl outside range", "{{with $v, $u := 3}}{{end}}", hasError, ""},
    248 	{"too many decls in range", "{{range $u, $v, $w := 3}}{{end}}", hasError, ""},
    249 	{"dot applied to parentheses", "{{printf (printf .).}}", hasError, ""},
    250 	{"adjacent args", "{{printf 3`x`}}", hasError, ""},
    251 	{"adjacent args with .", "{{printf `x`.}}", hasError, ""},
    252 	{"extra end after if", "{{if .X}}a{{else if .Y}}b{{end}}{{end}}", hasError, ""},
    253 	// Equals (and other chars) do not assignments make (yet).
    254 	{"bug0a", "{{$x := 0}}{{$x}}", noError, "{{$x := 0}}{{$x}}"},
    255 	{"bug0b", "{{$x = 1}}{{$x}}", hasError, ""},
    256 	{"bug0c", "{{$x ! 2}}{{$x}}", hasError, ""},
    257 	{"bug0d", "{{$x % 3}}{{$x}}", hasError, ""},
    258 	// Check the parse fails for := rather than comma.
    259 	{"bug0e", "{{range $x := $y := 3}}{{end}}", hasError, ""},
    260 	// Another bug: variable read must ignore following punctuation.
    261 	{"bug1a", "{{$x:=.}}{{$x!2}}", hasError, ""},                     // ! is just illegal here.
    262 	{"bug1b", "{{$x:=.}}{{$x+2}}", hasError, ""},                     // $x+2 should not parse as ($x) (+2).
    263 	{"bug1c", "{{$x:=.}}{{$x +2}}", noError, "{{$x := .}}{{$x +2}}"}, // It's OK with a space.
    264 	// dot following a literal value
    265 	{"dot after integer", "{{1.E}}", hasError, ""},
    266 	{"dot after float", "{{0.1.E}}", hasError, ""},
    267 	{"dot after boolean", "{{true.E}}", hasError, ""},
    268 	{"dot after char", "{{'a'.any}}", hasError, ""},
    269 	{"dot after string", `{{"hello".guys}}`, hasError, ""},
    270 	{"dot after dot", "{{..E}}", hasError, ""},
    271 	{"dot after nil", "{{nil.E}}", hasError, ""},
    272 	// Wrong pipeline
    273 	{"wrong pipeline dot", "{{12|.}}", hasError, ""},
    274 	{"wrong pipeline number", "{{.|12|printf}}", hasError, ""},
    275 	{"wrong pipeline string", "{{.|printf|\"error\"}}", hasError, ""},
    276 	{"wrong pipeline char", "{{12|printf|'e'}}", hasError, ""},
    277 	{"wrong pipeline boolean", "{{.|true}}", hasError, ""},
    278 	{"wrong pipeline nil", "{{'c'|nil}}", hasError, ""},
    279 	{"empty pipeline", `{{printf "%d" ( ) }}`, hasError, ""},
    280 }
    281 
    282 var builtins = map[string]interface{}{
    283 	"printf": fmt.Sprintf,
    284 }
    285 
    286 func testParse(doCopy bool, t *testing.T) {
    287 	textFormat = "%q"
    288 	defer func() { textFormat = "%s" }()
    289 	for _, test := range parseTests {
    290 		tmpl, err := New(test.name).Parse(test.input, "", "", make(map[string]*Tree), builtins)
    291 		switch {
    292 		case err == nil && !test.ok:
    293 			t.Errorf("%q: expected error; got none", test.name)
    294 			continue
    295 		case err != nil && test.ok:
    296 			t.Errorf("%q: unexpected error: %v", test.name, err)
    297 			continue
    298 		case err != nil && !test.ok:
    299 			// expected error, got one
    300 			if *debug {
    301 				fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)
    302 			}
    303 			continue
    304 		}
    305 		var result string
    306 		if doCopy {
    307 			result = tmpl.Root.Copy().String()
    308 		} else {
    309 			result = tmpl.Root.String()
    310 		}
    311 		if result != test.result {
    312 			t.Errorf("%s=(%q): got\n\t%v\nexpected\n\t%v", test.name, test.input, result, test.result)
    313 		}
    314 	}
    315 }
    316 
    317 func TestParse(t *testing.T) {
    318 	testParse(false, t)
    319 }
    320 
    321 // Same as TestParse, but we copy the node first
    322 func TestParseCopy(t *testing.T) {
    323 	testParse(true, t)
    324 }
    325 
    326 type isEmptyTest struct {
    327 	name  string
    328 	input string
    329 	empty bool
    330 }
    331 
    332 var isEmptyTests = []isEmptyTest{
    333 	{"empty", ``, true},
    334 	{"nonempty", `hello`, false},
    335 	{"spaces only", " \t\n \t\n", true},
    336 	{"definition", `{{define "x"}}something{{end}}`, true},
    337 	{"definitions and space", "{{define `x`}}something{{end}}\n\n{{define `y`}}something{{end}}\n\n", true},
    338 	{"definitions and text", "{{define `x`}}something{{end}}\nx\n{{define `y`}}something{{end}}\ny\n", false},
    339 	{"definition and action", "{{define `x`}}something{{end}}{{if 3}}foo{{end}}", false},
    340 }
    341 
    342 func TestIsEmpty(t *testing.T) {
    343 	if !IsEmptyTree(nil) {
    344 		t.Errorf("nil tree is not empty")
    345 	}
    346 	for _, test := range isEmptyTests {
    347 		tree, err := New("root").Parse(test.input, "", "", make(map[string]*Tree), nil)
    348 		if err != nil {
    349 			t.Errorf("%q: unexpected error: %v", test.name, err)
    350 			continue
    351 		}
    352 		if empty := IsEmptyTree(tree.Root); empty != test.empty {
    353 			t.Errorf("%q: expected %t got %t", test.name, test.empty, empty)
    354 		}
    355 	}
    356 }
    357 
    358 func TestErrorContextWithTreeCopy(t *testing.T) {
    359 	tree, err := New("root").Parse("{{if true}}{{end}}", "", "", make(map[string]*Tree), nil)
    360 	if err != nil {
    361 		t.Fatalf("unexpected tree parse failure: %v", err)
    362 	}
    363 	treeCopy := tree.Copy()
    364 	wantLocation, wantContext := tree.ErrorContext(tree.Root.Nodes[0])
    365 	gotLocation, gotContext := treeCopy.ErrorContext(treeCopy.Root.Nodes[0])
    366 	if wantLocation != gotLocation {
    367 		t.Errorf("wrong error location want %q got %q", wantLocation, gotLocation)
    368 	}
    369 	if wantContext != gotContext {
    370 		t.Errorf("wrong error location want %q got %q", wantContext, gotContext)
    371 	}
    372 }
    373 
    374 // All failures, and the result is a string that must appear in the error message.
    375 var errorTests = []parseTest{
    376 	// Check line numbers are accurate.
    377 	{"unclosed1",
    378 		"line1\n{{",
    379 		hasError, `unclosed1:2: unexpected unclosed action in command`},
    380 	{"unclosed2",
    381 		"line1\n{{define `x`}}line2\n{{",
    382 		hasError, `unclosed2:3: unexpected unclosed action in command`},
    383 	// Specific errors.
    384 	{"function",
    385 		"{{foo}}",
    386 		hasError, `function "foo" not defined`},
    387 	{"comment",
    388 		"{{/*}}",
    389 		hasError, `unclosed comment`},
    390 	{"lparen",
    391 		"{{.X (1 2 3}}",
    392 		hasError, `unclosed left paren`},
    393 	{"rparen",
    394 		"{{.X 1 2 3)}}",
    395 		hasError, `unexpected ")"`},
    396 	{"space",
    397 		"{{`x`3}}",
    398 		hasError, `in operand`},
    399 	{"idchar",
    400 		"{{a#}}",
    401 		hasError, `'#'`},
    402 	{"charconst",
    403 		"{{'a}}",
    404 		hasError, `unterminated character constant`},
    405 	{"stringconst",
    406 		`{{"a}}`,
    407 		hasError, `unterminated quoted string`},
    408 	{"rawstringconst",
    409 		"{{`a}}",
    410 		hasError, `unterminated raw quoted string`},
    411 	{"number",
    412 		"{{0xi}}",
    413 		hasError, `number syntax`},
    414 	{"multidefine",
    415 		"{{define `a`}}a{{end}}{{define `a`}}b{{end}}",
    416 		hasError, `multiple definition of template`},
    417 	{"eof",
    418 		"{{range .X}}",
    419 		hasError, `unexpected EOF`},
    420 	{"variable",
    421 		// Declare $x so it's defined, to avoid that error, and then check we don't parse a declaration.
    422 		"{{$x := 23}}{{with $x.y := 3}}{{$x 23}}{{end}}",
    423 		hasError, `unexpected ":="`},
    424 	{"multidecl",
    425 		"{{$a,$b,$c := 23}}",
    426 		hasError, `too many declarations`},
    427 	{"undefvar",
    428 		"{{$a}}",
    429 		hasError, `undefined variable`},
    430 	{"wrongdot",
    431 		"{{true.any}}",
    432 		hasError, `unexpected . after term`},
    433 	{"wrongpipeline",
    434 		"{{12|false}}",
    435 		hasError, `non executable command in pipeline`},
    436 	{"emptypipeline",
    437 		`{{ ( ) }}`,
    438 		hasError, `missing value for parenthesized pipeline`},
    439 }
    440 
    441 func TestErrors(t *testing.T) {
    442 	for _, test := range errorTests {
    443 		_, err := New(test.name).Parse(test.input, "", "", make(map[string]*Tree))
    444 		if err == nil {
    445 			t.Errorf("%q: expected error", test.name)
    446 			continue
    447 		}
    448 		if !strings.Contains(err.Error(), test.result) {
    449 			t.Errorf("%q: error %q does not contain %q", test.name, err, test.result)
    450 		}
    451 	}
    452 }
    453