github.com/kovansky/hugo@v0.92.3-0.20220224232819-63076e4ff19f/tpl/internal/go_templates/texttemplate/parse/parse_test.go (about)

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