Source file src/text/template/exec_test.go

     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 template
     6  
     7  import (
     8  	"bytes"
     9  	"errors"
    10  	"flag"
    11  	"fmt"
    12  	"io"
    13  	"iter"
    14  	"reflect"
    15  	"strings"
    16  	"sync"
    17  	"testing"
    18  )
    19  
    20  var debug = flag.Bool("debug", false, "show the errors produced by the tests")
    21  
    22  // T has lots of interesting pieces to use to test execution.
    23  type T struct {
    24  	// Basics
    25  	True        bool
    26  	I           int
    27  	U16         uint16
    28  	X, S        string
    29  	FloatZero   float64
    30  	ComplexZero complex128
    31  	// Nested structs.
    32  	U *U
    33  	// Struct with String method.
    34  	V0     V
    35  	V1, V2 *V
    36  	// Struct with Error method.
    37  	W0     W
    38  	W1, W2 *W
    39  	// Slices
    40  	SI      []int
    41  	SICap   []int
    42  	SIEmpty []int
    43  	SB      []bool
    44  	// Arrays
    45  	AI [3]int
    46  	// Maps
    47  	MSI      map[string]int
    48  	MSIone   map[string]int // one element, for deterministic output
    49  	MSIEmpty map[string]int
    50  	MXI      map[any]int
    51  	MII      map[int]int
    52  	MI32S    map[int32]string
    53  	MI64S    map[int64]string
    54  	MUI32S   map[uint32]string
    55  	MUI64S   map[uint64]string
    56  	MI8S     map[int8]string
    57  	MUI8S    map[uint8]string
    58  	SMSI     []map[string]int
    59  	// Empty interfaces; used to see if we can dig inside one.
    60  	Empty0 any // nil
    61  	Empty1 any
    62  	Empty2 any
    63  	Empty3 any
    64  	Empty4 any
    65  	// Non-empty interfaces.
    66  	NonEmptyInterface         I
    67  	NonEmptyInterfacePtS      *I
    68  	NonEmptyInterfaceNil      I
    69  	NonEmptyInterfaceTypedNil I
    70  	// Stringer.
    71  	Str fmt.Stringer
    72  	Err error
    73  	// Pointers
    74  	PI  *int
    75  	PS  *string
    76  	PSI *[]int
    77  	NIL *int
    78  	// Function (not method)
    79  	BinaryFunc             func(string, string) string
    80  	VariadicFunc           func(...string) string
    81  	VariadicFuncInt        func(int, ...string) string
    82  	NilOKFunc              func(*int) bool
    83  	ErrFunc                func() (string, error)
    84  	PanicFunc              func() string
    85  	TooFewReturnCountFunc  func()
    86  	TooManyReturnCountFunc func() (string, error, int)
    87  	InvalidReturnTypeFunc  func() (string, bool)
    88  	// Template to test evaluation of templates.
    89  	Tmpl *Template
    90  	// Unexported field; cannot be accessed by template.
    91  	unexported int
    92  }
    93  
    94  type S []string
    95  
    96  func (S) Method0() string {
    97  	return "M0"
    98  }
    99  
   100  type U struct {
   101  	V string
   102  }
   103  
   104  type V struct {
   105  	j int
   106  }
   107  
   108  func (v *V) String() string {
   109  	if v == nil {
   110  		return "nilV"
   111  	}
   112  	return fmt.Sprintf("<%d>", v.j)
   113  }
   114  
   115  type W struct {
   116  	k int
   117  }
   118  
   119  func (w *W) Error() string {
   120  	if w == nil {
   121  		return "nilW"
   122  	}
   123  	return fmt.Sprintf("[%d]", w.k)
   124  }
   125  
   126  var siVal = I(S{"a", "b"})
   127  
   128  var tVal = &T{
   129  	True:   true,
   130  	I:      17,
   131  	U16:    16,
   132  	X:      "x",
   133  	S:      "xyz",
   134  	U:      &U{"v"},
   135  	V0:     V{6666},
   136  	V1:     &V{7777}, // leave V2 as nil
   137  	W0:     W{888},
   138  	W1:     &W{999}, // leave W2 as nil
   139  	SI:     []int{3, 4, 5},
   140  	SICap:  make([]int, 5, 10),
   141  	AI:     [3]int{3, 4, 5},
   142  	SB:     []bool{true, false},
   143  	MSI:    map[string]int{"one": 1, "two": 2, "three": 3},
   144  	MSIone: map[string]int{"one": 1},
   145  	MXI:    map[any]int{"one": 1},
   146  	MII:    map[int]int{1: 1},
   147  	MI32S:  map[int32]string{1: "one", 2: "two"},
   148  	MI64S:  map[int64]string{2: "i642", 3: "i643"},
   149  	MUI32S: map[uint32]string{2: "u322", 3: "u323"},
   150  	MUI64S: map[uint64]string{2: "ui642", 3: "ui643"},
   151  	MI8S:   map[int8]string{2: "i82", 3: "i83"},
   152  	MUI8S:  map[uint8]string{2: "u82", 3: "u83"},
   153  	SMSI: []map[string]int{
   154  		{"one": 1, "two": 2},
   155  		{"eleven": 11, "twelve": 12},
   156  	},
   157  	Empty1:                    3,
   158  	Empty2:                    "empty2",
   159  	Empty3:                    []int{7, 8},
   160  	Empty4:                    &U{"UinEmpty"},
   161  	NonEmptyInterface:         &T{X: "x"},
   162  	NonEmptyInterfacePtS:      &siVal,
   163  	NonEmptyInterfaceTypedNil: (*T)(nil),
   164  	Str:                       bytes.NewBuffer([]byte("foozle")),
   165  	Err:                       errors.New("erroozle"),
   166  	PI:                        newInt(23),
   167  	PS:                        newString("a string"),
   168  	PSI:                       newIntSlice(21, 22, 23),
   169  	BinaryFunc:                func(a, b string) string { return fmt.Sprintf("[%s=%s]", a, b) },
   170  	VariadicFunc:              func(s ...string) string { return fmt.Sprint("<", strings.Join(s, "+"), ">") },
   171  	VariadicFuncInt:           func(a int, s ...string) string { return fmt.Sprint(a, "=<", strings.Join(s, "+"), ">") },
   172  	NilOKFunc:                 func(s *int) bool { return s == nil },
   173  	ErrFunc:                   func() (string, error) { return "bla", nil },
   174  	PanicFunc:                 func() string { panic("test panic") },
   175  	TooFewReturnCountFunc:     func() {},
   176  	TooManyReturnCountFunc:    func() (string, error, int) { return "", nil, 0 },
   177  	InvalidReturnTypeFunc:     func() (string, bool) { return "", false },
   178  	Tmpl:                      Must(New("x").Parse("test template")), // "x" is the value of .X
   179  }
   180  
   181  var tSliceOfNil = []*T{nil}
   182  
   183  // A non-empty interface.
   184  type I interface {
   185  	Method0() string
   186  }
   187  
   188  var iVal I = tVal
   189  
   190  // Helpers for creation.
   191  func newInt(n int) *int {
   192  	return &n
   193  }
   194  
   195  func newString(s string) *string {
   196  	return &s
   197  }
   198  
   199  func newIntSlice(n ...int) *[]int {
   200  	p := new([]int)
   201  	*p = make([]int, len(n))
   202  	copy(*p, n)
   203  	return p
   204  }
   205  
   206  // Simple methods with and without arguments.
   207  func (t *T) Method0() string {
   208  	return "M0"
   209  }
   210  
   211  func (t *T) Method1(a int) int {
   212  	return a
   213  }
   214  
   215  func (t *T) Method2(a uint16, b string) string {
   216  	return fmt.Sprintf("Method2: %d %s", a, b)
   217  }
   218  
   219  func (t *T) Method3(v any) string {
   220  	return fmt.Sprintf("Method3: %v", v)
   221  }
   222  
   223  func (t *T) Copy() *T {
   224  	n := new(T)
   225  	*n = *t
   226  	return n
   227  }
   228  
   229  func (t *T) MAdd(a int, b []int) []int {
   230  	v := make([]int, len(b))
   231  	for i, x := range b {
   232  		v[i] = x + a
   233  	}
   234  	return v
   235  }
   236  
   237  var myError = errors.New("my error")
   238  
   239  // MyError returns a value and an error according to its argument.
   240  func (t *T) MyError(error bool) (bool, error) {
   241  	if error {
   242  		return true, myError
   243  	}
   244  	return false, nil
   245  }
   246  
   247  // A few methods to test chaining.
   248  func (t *T) GetU() *U {
   249  	return t.U
   250  }
   251  
   252  func (u *U) TrueFalse(b bool) string {
   253  	if b {
   254  		return "true"
   255  	}
   256  	return ""
   257  }
   258  
   259  func typeOf(arg any) string {
   260  	return fmt.Sprintf("%T", arg)
   261  }
   262  
   263  type execTest struct {
   264  	name   string
   265  	input  string
   266  	output string
   267  	data   any
   268  	ok     bool
   269  }
   270  
   271  // bigInt and bigUint are hex string representing numbers either side
   272  // of the max int boundary.
   273  // We do it this way so the test doesn't depend on ints being 32 bits.
   274  var (
   275  	bigInt  = fmt.Sprintf("0x%x", int(1<<uint(reflect.TypeFor[int]().Bits()-1)-1))
   276  	bigUint = fmt.Sprintf("0x%x", uint(1<<uint(reflect.TypeFor[int]().Bits()-1)))
   277  )
   278  
   279  var execTests = []execTest{
   280  	// Trivial cases.
   281  	{"empty", "", "", nil, true},
   282  	{"text", "some text", "some text", nil, true},
   283  	{"nil action", "{{nil}}", "", nil, false},
   284  
   285  	// Ideal constants.
   286  	{"ideal int", "{{typeOf 3}}", "int", 0, true},
   287  	{"ideal float", "{{typeOf 1.0}}", "float64", 0, true},
   288  	{"ideal exp float", "{{typeOf 1e1}}", "float64", 0, true},
   289  	{"ideal complex", "{{typeOf 1i}}", "complex128", 0, true},
   290  	{"ideal int", "{{typeOf " + bigInt + "}}", "int", 0, true},
   291  	{"ideal too big", "{{typeOf " + bigUint + "}}", "", 0, false},
   292  	{"ideal nil without type", "{{nil}}", "", 0, false},
   293  
   294  	// Fields of structs.
   295  	{".X", "-{{.X}}-", "-x-", tVal, true},
   296  	{".U.V", "-{{.U.V}}-", "-v-", tVal, true},
   297  	{".unexported", "{{.unexported}}", "", tVal, false},
   298  
   299  	// Fields on maps.
   300  	{"map .one", "{{.MSI.one}}", "1", tVal, true},
   301  	{"map .two", "{{.MSI.two}}", "2", tVal, true},
   302  	{"map .NO", "{{.MSI.NO}}", "<no value>", tVal, true},
   303  	{"map .one interface", "{{.MXI.one}}", "1", tVal, true},
   304  	{"map .WRONG args", "{{.MSI.one 1}}", "", tVal, false},
   305  	{"map .WRONG type", "{{.MII.one}}", "", tVal, false},
   306  
   307  	// Dots of all kinds to test basic evaluation.
   308  	{"dot int", "<{{.}}>", "<13>", 13, true},
   309  	{"dot uint", "<{{.}}>", "<14>", uint(14), true},
   310  	{"dot float", "<{{.}}>", "<15.1>", 15.1, true},
   311  	{"dot bool", "<{{.}}>", "<true>", true, true},
   312  	{"dot complex", "<{{.}}>", "<(16.2-17i)>", 16.2 - 17i, true},
   313  	{"dot string", "<{{.}}>", "<hello>", "hello", true},
   314  	{"dot slice", "<{{.}}>", "<[-1 -2 -3]>", []int{-1, -2, -3}, true},
   315  	{"dot map", "<{{.}}>", "<map[two:22]>", map[string]int{"two": 22}, true},
   316  	{"dot struct", "<{{.}}>", "<{7 seven}>", struct {
   317  		a int
   318  		b string
   319  	}{7, "seven"}, true},
   320  
   321  	// Variables.
   322  	{"$ int", "{{$}}", "123", 123, true},
   323  	{"$.I", "{{$.I}}", "17", tVal, true},
   324  	{"$.U.V", "{{$.U.V}}", "v", tVal, true},
   325  	{"declare in action", "{{$x := $.U.V}}{{$x}}", "v", tVal, true},
   326  	{"simple assignment", "{{$x := 2}}{{$x = 3}}{{$x}}", "3", tVal, true},
   327  	{"nested assignment",
   328  		"{{$x := 2}}{{if true}}{{$x = 3}}{{end}}{{$x}}",
   329  		"3", tVal, true},
   330  	{"nested assignment changes the last declaration",
   331  		"{{$x := 1}}{{if true}}{{$x := 2}}{{if true}}{{$x = 3}}{{end}}{{end}}{{$x}}",
   332  		"1", tVal, true},
   333  
   334  	// Type with String method.
   335  	{"V{6666}.String()", "-{{.V0}}-", "-<6666>-", tVal, true},
   336  	{"&V{7777}.String()", "-{{.V1}}-", "-<7777>-", tVal, true},
   337  	{"(*V)(nil).String()", "-{{.V2}}-", "-nilV-", tVal, true},
   338  
   339  	// Type with Error method.
   340  	{"W{888}.Error()", "-{{.W0}}-", "-[888]-", tVal, true},
   341  	{"&W{999}.Error()", "-{{.W1}}-", "-[999]-", tVal, true},
   342  	{"(*W)(nil).Error()", "-{{.W2}}-", "-nilW-", tVal, true},
   343  
   344  	// Pointers.
   345  	{"*int", "{{.PI}}", "23", tVal, true},
   346  	{"*string", "{{.PS}}", "a string", tVal, true},
   347  	{"*[]int", "{{.PSI}}", "[21 22 23]", tVal, true},
   348  	{"*[]int[1]", "{{index .PSI 1}}", "22", tVal, true},
   349  	{"NIL", "{{.NIL}}", "<nil>", tVal, true},
   350  
   351  	// Empty interfaces holding values.
   352  	{"empty nil", "{{.Empty0}}", "<no value>", tVal, true},
   353  	{"empty with int", "{{.Empty1}}", "3", tVal, true},
   354  	{"empty with string", "{{.Empty2}}", "empty2", tVal, true},
   355  	{"empty with slice", "{{.Empty3}}", "[7 8]", tVal, true},
   356  	{"empty with struct", "{{.Empty4}}", "{UinEmpty}", tVal, true},
   357  	{"empty with struct, field", "{{.Empty4.V}}", "UinEmpty", tVal, true},
   358  
   359  	// Edge cases with <no value> with an interface value
   360  	{"field on interface", "{{.foo}}", "<no value>", nil, true},
   361  	{"field on parenthesized interface", "{{(.).foo}}", "<no value>", nil, true},
   362  
   363  	// Issue 31810: Parenthesized first element of pipeline with arguments.
   364  	// See also TestIssue31810.
   365  	{"unparenthesized non-function", "{{1 2}}", "", nil, false},
   366  	{"parenthesized non-function", "{{(1) 2}}", "", nil, false},
   367  	{"parenthesized non-function with no args", "{{(1)}}", "1", nil, true}, // This is fine.
   368  
   369  	// Method calls.
   370  	{".Method0", "-{{.Method0}}-", "-M0-", tVal, true},
   371  	{".Method1(1234)", "-{{.Method1 1234}}-", "-1234-", tVal, true},
   372  	{".Method1(.I)", "-{{.Method1 .I}}-", "-17-", tVal, true},
   373  	{".Method2(3, .X)", "-{{.Method2 3 .X}}-", "-Method2: 3 x-", tVal, true},
   374  	{".Method2(.U16, `str`)", "-{{.Method2 .U16 `str`}}-", "-Method2: 16 str-", tVal, true},
   375  	{".Method2(.U16, $x)", "{{if $x := .X}}-{{.Method2 .U16 $x}}{{end}}-", "-Method2: 16 x-", tVal, true},
   376  	{".Method3(nil constant)", "-{{.Method3 nil}}-", "-Method3: <nil>-", tVal, true},
   377  	{".Method3(nil value)", "-{{.Method3 .MXI.unset}}-", "-Method3: <nil>-", tVal, true},
   378  	{"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal, true},
   379  	{"method on chained var",
   380  		"{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
   381  		"true", tVal, true},
   382  	{"chained method",
   383  		"{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",
   384  		"true", tVal, true},
   385  	{"chained method on variable",
   386  		"{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}",
   387  		"true", tVal, true},
   388  	{".NilOKFunc not nil", "{{call .NilOKFunc .PI}}", "false", tVal, true},
   389  	{".NilOKFunc nil", "{{call .NilOKFunc nil}}", "true", tVal, true},
   390  	{"method on nil value from slice", "-{{range .}}{{.Method1 1234}}{{end}}-", "-1234-", tSliceOfNil, true},
   391  	{"method on typed nil interface value", "{{.NonEmptyInterfaceTypedNil.Method0}}", "M0", tVal, true},
   392  
   393  	// Function call builtin.
   394  	{".BinaryFunc", "{{call .BinaryFunc `1` `2`}}", "[1=2]", tVal, true},
   395  	{".VariadicFunc0", "{{call .VariadicFunc}}", "<>", tVal, true},
   396  	{".VariadicFunc2", "{{call .VariadicFunc `he` `llo`}}", "<he+llo>", tVal, true},
   397  	{".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=<he+llo>", tVal, true},
   398  	{"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal, true},
   399  	{"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal, true},
   400  	{"Interface Call", `{{stringer .S}}`, "foozle", map[string]any{"S": bytes.NewBufferString("foozle")}, true},
   401  	{".ErrFunc", "{{call .ErrFunc}}", "bla", tVal, true},
   402  	{"call nil", "{{call nil}}", "", tVal, false},
   403  
   404  	// Erroneous function calls (check args).
   405  	{".BinaryFuncTooFew", "{{call .BinaryFunc `1`}}", "", tVal, false},
   406  	{".BinaryFuncTooMany", "{{call .BinaryFunc `1` `2` `3`}}", "", tVal, false},
   407  	{".BinaryFuncBad0", "{{call .BinaryFunc 1 3}}", "", tVal, false},
   408  	{".BinaryFuncBad1", "{{call .BinaryFunc `1` 3}}", "", tVal, false},
   409  	{".VariadicFuncBad0", "{{call .VariadicFunc 3}}", "", tVal, false},
   410  	{".VariadicFuncIntBad0", "{{call .VariadicFuncInt}}", "", tVal, false},
   411  	{".VariadicFuncIntBad`", "{{call .VariadicFuncInt `x`}}", "", tVal, false},
   412  	{".VariadicFuncNilBad", "{{call .VariadicFunc nil}}", "", tVal, false},
   413  
   414  	// Pipelines.
   415  	{"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true},
   416  	{"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "-<he+<llo>>-", tVal, true},
   417  
   418  	// Nil values aren't missing arguments.
   419  	{"nil pipeline", "{{ .Empty0 | call .NilOKFunc }}", "true", tVal, true},
   420  	{"nil call arg", "{{ call .NilOKFunc .Empty0 }}", "true", tVal, true},
   421  	{"bad nil pipeline", "{{ .Empty0 | .VariadicFunc }}", "", tVal, false},
   422  
   423  	// Parenthesized expressions
   424  	{"parens in pipeline", "{{printf `%d %d %d` (1) (2 | add 3) (add 4 (add 5 6))}}", "1 5 15", tVal, true},
   425  
   426  	// Parenthesized expressions with field accesses
   427  	{"parens: $ in paren", "{{($).X}}", "x", tVal, true},
   428  	{"parens: $.GetU in paren", "{{($.GetU).V}}", "v", tVal, true},
   429  	{"parens: $ in paren in pipe", "{{($ | echo).X}}", "x", tVal, true},
   430  	{"parens: spaces and args", `{{(makemap "up" "down" "left" "right").left}}`, "right", tVal, true},
   431  
   432  	// If.
   433  	{"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true},
   434  	{"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal, true},
   435  	{"if nil", "{{if nil}}TRUE{{end}}", "", tVal, false},
   436  	{"if on typed nil interface value", "{{if .NonEmptyInterfaceTypedNil}}TRUE{{ end }}", "", tVal, true},
   437  	{"if 1", "{{if 1}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
   438  	{"if 0", "{{if 0}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
   439  	{"if 1.5", "{{if 1.5}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
   440  	{"if 0.0", "{{if .FloatZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
   441  	{"if 1.5i", "{{if 1.5i}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
   442  	{"if 0.0i", "{{if .ComplexZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
   443  	{"if emptystring", "{{if ``}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   444  	{"if string", "{{if `notempty`}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
   445  	{"if emptyslice", "{{if .SIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   446  	{"if slice", "{{if .SI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
   447  	{"if emptymap", "{{if .MSIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   448  	{"if map", "{{if .MSI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},
   449  	{"if map unset", "{{if .MXI.none}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
   450  	{"if map not unset", "{{if not .MXI.none}}ZERO{{else}}NON-ZERO{{end}}", "ZERO", tVal, true},
   451  	{"if $x with $y int", "{{if $x := true}}{{with $y := .I}}{{$x}},{{$y}}{{end}}{{end}}", "true,17", tVal, true},
   452  	{"if $x with $x int", "{{if $x := true}}{{with $x := .I}}{{$x}},{{end}}{{$x}}{{end}}", "17,true", tVal, true},
   453  	{"if else if", "{{if false}}FALSE{{else if true}}TRUE{{end}}", "TRUE", tVal, true},
   454  	{"if else chain", "{{if eq 1 3}}1{{else if eq 2 3}}2{{else if eq 3 3}}3{{end}}", "3", tVal, true},
   455  
   456  	// Print etc.
   457  	{"print", `{{print "hello, print"}}`, "hello, print", tVal, true},
   458  	{"print 123", `{{print 1 2 3}}`, "1 2 3", tVal, true},
   459  	{"print nil", `{{print nil}}`, "<nil>", tVal, true},
   460  	{"println", `{{println 1 2 3}}`, "1 2 3\n", tVal, true},
   461  	{"printf int", `{{printf "%04x" 127}}`, "007f", tVal, true},
   462  	{"printf float", `{{printf "%g" 3.5}}`, "3.5", tVal, true},
   463  	{"printf complex", `{{printf "%g" 1+7i}}`, "(1+7i)", tVal, true},
   464  	{"printf string", `{{printf "%s" "hello"}}`, "hello", tVal, true},
   465  	{"printf function", `{{printf "%#q" zeroArgs}}`, "`zeroArgs`", tVal, true},
   466  	{"printf field", `{{printf "%s" .U.V}}`, "v", tVal, true},
   467  	{"printf method", `{{printf "%s" .Method0}}`, "M0", tVal, true},
   468  	{"printf dot", `{{with .I}}{{printf "%d" .}}{{end}}`, "17", tVal, true},
   469  	{"printf var", `{{with $x := .I}}{{printf "%d" $x}}{{end}}`, "17", tVal, true},
   470  	{"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal, true},
   471  
   472  	// HTML.
   473  	{"html", `{{html "<script>alert(\"XSS\");</script>"}}`,
   474  		"&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},
   475  	{"html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`,
   476  		"&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},
   477  	{"html", `{{html .PS}}`, "a string", tVal, true},
   478  	{"html typed nil", `{{html .NIL}}`, "&lt;nil&gt;", tVal, true},
   479  	{"html untyped nil", `{{html .Empty0}}`, "&lt;no value&gt;", tVal, true},
   480  
   481  	// JavaScript.
   482  	{"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true},
   483  
   484  	// URL query.
   485  	{"urlquery", `{{"http://www.example.org/"|urlquery}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true},
   486  
   487  	// Booleans
   488  	{"not", "{{not true}} {{not false}}", "false true", nil, true},
   489  	{"and", "{{and false 0}} {{and 1 0}} {{and 0 true}} {{and 1 1}}", "false 0 0 1", nil, true},
   490  	{"or", "{{or 0 0}} {{or 1 0}} {{or 0 true}} {{or 1 1}}", "0 1 true 1", nil, true},
   491  	{"or short-circuit", "{{or 0 1 (die)}}", "1", nil, true},
   492  	{"and short-circuit", "{{and 1 0 (die)}}", "0", nil, true},
   493  	{"or short-circuit2", "{{or 0 0 (die)}}", "", nil, false},
   494  	{"and short-circuit2", "{{and 1 1 (die)}}", "", nil, false},
   495  	{"and pipe-true", "{{1 | and 1}}", "1", nil, true},
   496  	{"and pipe-false", "{{0 | and 1}}", "0", nil, true},
   497  	{"or pipe-true", "{{1 | or 0}}", "1", nil, true},
   498  	{"or pipe-false", "{{0 | or 0}}", "0", nil, true},
   499  	{"and undef", "{{and 1 .Unknown}}", "<no value>", nil, true},
   500  	{"or undef", "{{or 0 .Unknown}}", "<no value>", nil, true},
   501  	{"boolean if", "{{if and true 1 `hi`}}TRUE{{else}}FALSE{{end}}", "TRUE", tVal, true},
   502  	{"boolean if not", "{{if and true 1 `hi` | not}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true},
   503  	{"boolean if pipe", "{{if true | not | and 1}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true},
   504  
   505  	// Indexing.
   506  	{"slice[0]", "{{index .SI 0}}", "3", tVal, true},
   507  	{"slice[1]", "{{index .SI 1}}", "4", tVal, true},
   508  	{"slice[HUGE]", "{{index .SI 10}}", "", tVal, false},
   509  	{"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false},
   510  	{"slice[nil]", "{{index .SI nil}}", "", tVal, false},
   511  	{"map[one]", "{{index .MSI `one`}}", "1", tVal, true},
   512  	{"map[two]", "{{index .MSI `two`}}", "2", tVal, true},
   513  	{"map[NO]", "{{index .MSI `XXX`}}", "0", tVal, true},
   514  	{"map[nil]", "{{index .MSI nil}}", "", tVal, false},
   515  	{"map[``]", "{{index .MSI ``}}", "0", tVal, true},
   516  	{"map[WRONG]", "{{index .MSI 10}}", "", tVal, false},
   517  	{"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true},
   518  	{"nil[1]", "{{index nil 1}}", "", tVal, false},
   519  	{"map MI64S", "{{index .MI64S 2}}", "i642", tVal, true},
   520  	{"map MI32S", "{{index .MI32S 2}}", "two", tVal, true},
   521  	{"map MUI64S", "{{index .MUI64S 3}}", "ui643", tVal, true},
   522  	{"map MI8S", "{{index .MI8S 3}}", "i83", tVal, true},
   523  	{"map MUI8S", "{{index .MUI8S 2}}", "u82", tVal, true},
   524  	{"index of an interface field", "{{index .Empty3 0}}", "7", tVal, true},
   525  
   526  	// Slicing.
   527  	{"slice[:]", "{{slice .SI}}", "[3 4 5]", tVal, true},
   528  	{"slice[1:]", "{{slice .SI 1}}", "[4 5]", tVal, true},
   529  	{"slice[1:2]", "{{slice .SI 1 2}}", "[4]", tVal, true},
   530  	{"slice[-1:]", "{{slice .SI -1}}", "", tVal, false},
   531  	{"slice[1:-2]", "{{slice .SI 1 -2}}", "", tVal, false},
   532  	{"slice[1:2:-1]", "{{slice .SI 1 2 -1}}", "", tVal, false},
   533  	{"slice[2:1]", "{{slice .SI 2 1}}", "", tVal, false},
   534  	{"slice[2:2:1]", "{{slice .SI 2 2 1}}", "", tVal, false},
   535  	{"out of range", "{{slice .SI 4 5}}", "", tVal, false},
   536  	{"out of range", "{{slice .SI 2 2 5}}", "", tVal, false},
   537  	{"len(s) < indexes < cap(s)", "{{slice .SICap 6 10}}", "[0 0 0 0]", tVal, true},
   538  	{"len(s) < indexes < cap(s)", "{{slice .SICap 6 10 10}}", "[0 0 0 0]", tVal, true},
   539  	{"indexes > cap(s)", "{{slice .SICap 10 11}}", "", tVal, false},
   540  	{"indexes > cap(s)", "{{slice .SICap 6 10 11}}", "", tVal, false},
   541  	{"array[:]", "{{slice .AI}}", "[3 4 5]", tVal, true},
   542  	{"array[1:]", "{{slice .AI 1}}", "[4 5]", tVal, true},
   543  	{"array[1:2]", "{{slice .AI 1 2}}", "[4]", tVal, true},
   544  	{"string[:]", "{{slice .S}}", "xyz", tVal, true},
   545  	{"string[0:1]", "{{slice .S 0 1}}", "x", tVal, true},
   546  	{"string[1:]", "{{slice .S 1}}", "yz", tVal, true},
   547  	{"string[1:2]", "{{slice .S 1 2}}", "y", tVal, true},
   548  	{"out of range", "{{slice .S 1 5}}", "", tVal, false},
   549  	{"3-index slice of string", "{{slice .S 1 2 2}}", "", tVal, false},
   550  	{"slice of an interface field", "{{slice .Empty3 0 1}}", "[7]", tVal, true},
   551  
   552  	// Len.
   553  	{"slice", "{{len .SI}}", "3", tVal, true},
   554  	{"map", "{{len .MSI }}", "3", tVal, true},
   555  	{"len of int", "{{len 3}}", "", tVal, false},
   556  	{"len of nothing", "{{len .Empty0}}", "", tVal, false},
   557  	{"len of an interface field", "{{len .Empty3}}", "2", tVal, true},
   558  
   559  	// With.
   560  	{"with true", "{{with true}}{{.}}{{end}}", "true", tVal, true},
   561  	{"with false", "{{with false}}{{.}}{{else}}FALSE{{end}}", "FALSE", tVal, true},
   562  	{"with 1", "{{with 1}}{{.}}{{else}}ZERO{{end}}", "1", tVal, true},
   563  	{"with 0", "{{with 0}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
   564  	{"with 1.5", "{{with 1.5}}{{.}}{{else}}ZERO{{end}}", "1.5", tVal, true},
   565  	{"with 0.0", "{{with .FloatZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
   566  	{"with 1.5i", "{{with 1.5i}}{{.}}{{else}}ZERO{{end}}", "(0+1.5i)", tVal, true},
   567  	{"with 0.0i", "{{with .ComplexZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},
   568  	{"with emptystring", "{{with ``}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   569  	{"with string", "{{with `notempty`}}{{.}}{{else}}EMPTY{{end}}", "notempty", tVal, true},
   570  	{"with emptyslice", "{{with .SIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   571  	{"with slice", "{{with .SI}}{{.}}{{else}}EMPTY{{end}}", "[3 4 5]", tVal, true},
   572  	{"with emptymap", "{{with .MSIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   573  	{"with map", "{{with .MSIone}}{{.}}{{else}}EMPTY{{end}}", "map[one:1]", tVal, true},
   574  	{"with empty interface, struct field", "{{with .Empty4}}{{.V}}{{end}}", "UinEmpty", tVal, true},
   575  	{"with $x int", "{{with $x := .I}}{{$x}}{{end}}", "17", tVal, true},
   576  	{"with $x struct.U.V", "{{with $x := $}}{{$x.U.V}}{{end}}", "v", tVal, true},
   577  	{"with variable and action", "{{with $x := $}}{{$y := $.U.V}}{{$y}}{{end}}", "v", tVal, true},
   578  	{"with on typed nil interface value", "{{with .NonEmptyInterfaceTypedNil}}TRUE{{ end }}", "", tVal, true},
   579  	{"with else with", "{{with 0}}{{.}}{{else with true}}{{.}}{{end}}", "true", tVal, true},
   580  	{"with else with chain", "{{with 0}}{{.}}{{else with false}}{{.}}{{else with `notempty`}}{{.}}{{end}}", "notempty", tVal, true},
   581  
   582  	// Range.
   583  	{"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal, true},
   584  	{"range empty no else", "{{range .SIEmpty}}-{{.}}-{{end}}", "", tVal, true},
   585  	{"range []int else", "{{range .SI}}-{{.}}-{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true},
   586  	{"range empty else", "{{range .SIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   587  	{"range []int break else", "{{range .SI}}-{{.}}-{{break}}NOTREACHED{{else}}EMPTY{{end}}", "-3-", tVal, true},
   588  	{"range []int continue else", "{{range .SI}}-{{.}}-{{continue}}NOTREACHED{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true},
   589  	{"range []bool", "{{range .SB}}-{{.}}-{{end}}", "-true--false-", tVal, true},
   590  	{"range []int method", "{{range .SI | .MAdd .I}}-{{.}}-{{end}}", "-20--21--22-", tVal, true},
   591  	{"range map", "{{range .MSI}}-{{.}}-{{end}}", "-1--3--2-", tVal, true},
   592  	{"range empty map no else", "{{range .MSIEmpty}}-{{.}}-{{end}}", "", tVal, true},
   593  	{"range map else", "{{range .MSI}}-{{.}}-{{else}}EMPTY{{end}}", "-1--3--2-", tVal, true},
   594  	{"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
   595  	{"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal, true},
   596  	{"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal, true},
   597  	{"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal, true},
   598  	{"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal, true},
   599  	{"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal, true},
   600  	{"range $x $y MSIone", "{{range $x, $y := .MSIone}}<{{$x}}={{$y}}>{{end}}", "<one=1>", tVal, true},
   601  	{"range $x PSI", "{{range $x := .PSI}}<{{$x}}>{{end}}", "<21><22><23>", tVal, true},
   602  	{"declare in range", "{{range $x := .PSI}}<{{$foo:=$x}}{{$x}}>{{end}}", "<21><22><23>", tVal, true},
   603  	{"range count", `{{range $i, $x := count 5}}[{{$i}}]{{$x}}{{end}}`, "[0]a[1]b[2]c[3]d[4]e", tVal, true},
   604  	{"range nil count", `{{range $i, $x := count 0}}{{else}}empty{{end}}`, "empty", tVal, true},
   605  	{"range iter.Seq[int]", `{{range $i := .}}{{$i}}{{end}}`, "01", fVal1(2), true},
   606  	{"i = range iter.Seq[int]", `{{$i := 0}}{{range $i = .}}{{$i}}{{end}}`, "01", fVal1(2), true},
   607  	{"range iter.Seq[int] over two var", `{{range $i, $c := .}}{{$c}}{{end}}`, "", fVal1(2), false},
   608  	{"i, c := range iter.Seq2[int,int]", `{{range $i, $c := .}}{{$i}}{{$c}}{{end}}`, "0112", fVal2(2), true},
   609  	{"i, c = range iter.Seq2[int,int]", `{{$i := 0}}{{$c := 0}}{{range $i, $c = .}}{{$i}}{{$c}}{{end}}`, "0112", fVal2(2), true},
   610  	{"i = range iter.Seq2[int,int]", `{{$i := 0}}{{range $i = .}}{{$i}}{{end}}`, "01", fVal2(2), true},
   611  	{"i := range iter.Seq2[int,int]", `{{range $i := .}}{{$i}}{{end}}`, "01", fVal2(2), true},
   612  	{"i,c,x range iter.Seq2[int,int]", `{{$i := 0}}{{$c := 0}}{{$x := 0}}{{range $i, $c = .}}{{$i}}{{$c}}{{end}}`, "0112", fVal2(2), true},
   613  	{"i,x range iter.Seq[int]", `{{$i := 0}}{{$x := 0}}{{range $i = .}}{{$i}}{{end}}`, "01", fVal1(2), true},
   614  	{"range iter.Seq[int] else", `{{range $i := .}}{{$i}}{{else}}empty{{end}}`, "empty", fVal1(0), true},
   615  	{"range iter.Seq2[int,int] else", `{{range $i := .}}{{$i}}{{else}}empty{{end}}`, "empty", fVal2(0), true},
   616  	{"range int8", rangeTestInt, rangeTestData[int8](), int8(5), true},
   617  	{"range int16", rangeTestInt, rangeTestData[int16](), int16(5), true},
   618  	{"range int32", rangeTestInt, rangeTestData[int32](), int32(5), true},
   619  	{"range int64", rangeTestInt, rangeTestData[int64](), int64(5), true},
   620  	{"range int", rangeTestInt, rangeTestData[int](), int(5), true},
   621  	{"range uint8", rangeTestInt, rangeTestData[uint8](), uint8(5), true},
   622  	{"range uint16", rangeTestInt, rangeTestData[uint16](), uint16(5), true},
   623  	{"range uint32", rangeTestInt, rangeTestData[uint32](), uint32(5), true},
   624  	{"range uint64", rangeTestInt, rangeTestData[uint64](), uint64(5), true},
   625  	{"range uint", rangeTestInt, rangeTestData[uint](), uint(5), true},
   626  	{"range uintptr", rangeTestInt, rangeTestData[uintptr](), uintptr(5), true},
   627  	{"range uintptr(0)", `{{range $v := .}}{{print $v}}{{else}}empty{{end}}`, "empty", uintptr(0), true},
   628  	{"range 5", `{{range $v := 5}}{{printf "%T%d" $v $v}}{{end}}`, rangeTestData[int](), nil, true},
   629  
   630  	// Cute examples.
   631  	{"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal, true},
   632  	{"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal, true},
   633  
   634  	// Error handling.
   635  	{"error method, error", "{{.MyError true}}", "", tVal, false},
   636  	{"error method, no error", "{{.MyError false}}", "false", tVal, true},
   637  
   638  	// Numbers
   639  	{"decimal", "{{print 1234}}", "1234", tVal, true},
   640  	{"decimal _", "{{print 12_34}}", "1234", tVal, true},
   641  	{"binary", "{{print 0b101}}", "5", tVal, true},
   642  	{"binary _", "{{print 0b_1_0_1}}", "5", tVal, true},
   643  	{"BINARY", "{{print 0B101}}", "5", tVal, true},
   644  	{"octal0", "{{print 0377}}", "255", tVal, true},
   645  	{"octal", "{{print 0o377}}", "255", tVal, true},
   646  	{"octal _", "{{print 0o_3_7_7}}", "255", tVal, true},
   647  	{"OCTAL", "{{print 0O377}}", "255", tVal, true},
   648  	{"hex", "{{print 0x123}}", "291", tVal, true},
   649  	{"hex _", "{{print 0x1_23}}", "291", tVal, true},
   650  	{"HEX", "{{print 0X123ABC}}", "1194684", tVal, true},
   651  	{"float", "{{print 123.4}}", "123.4", tVal, true},
   652  	{"float _", "{{print 0_0_1_2_3.4}}", "123.4", tVal, true},
   653  	{"hex float", "{{print +0x1.ep+2}}", "7.5", tVal, true},
   654  	{"hex float _", "{{print +0x_1.e_0p+0_2}}", "7.5", tVal, true},
   655  	{"HEX float", "{{print +0X1.EP+2}}", "7.5", tVal, true},
   656  	{"print multi", "{{print 1_2_3_4 7.5_00_00_00}}", "1234 7.5", tVal, true},
   657  	{"print multi2", "{{print 1234 0x0_1.e_0p+02}}", "1234 7.5", tVal, true},
   658  
   659  	// Fixed bugs.
   660  	// Must separate dot and receiver; otherwise args are evaluated with dot set to variable.
   661  	{"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal, true},
   662  	// Do not loop endlessly in indirect for non-empty interfaces.
   663  	// The bug appears with *interface only; looped forever.
   664  	{"bug1", "{{.Method0}}", "M0", &iVal, true},
   665  	// Was taking address of interface field, so method set was empty.
   666  	{"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal, true},
   667  	// Struct values were not legal in with - mere oversight.
   668  	{"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal, true},
   669  	// Nil interface values in if.
   670  	{"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true},
   671  	// Stringer.
   672  	{"bug5", "{{.Str}}", "foozle", tVal, true},
   673  	{"bug5a", "{{.Err}}", "erroozle", tVal, true},
   674  	// Args need to be indirected and dereferenced sometimes.
   675  	{"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true},
   676  	{"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true},
   677  	{"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal, true},
   678  	{"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal, true},
   679  	// Legal parse but illegal execution: non-function should have no arguments.
   680  	{"bug7a", "{{3 2}}", "", tVal, false},
   681  	{"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal, false},
   682  	{"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal, false},
   683  	// Pipelined arg was not being type-checked.
   684  	{"bug8a", "{{3|oneArg}}", "", tVal, false},
   685  	{"bug8b", "{{4|dddArg 3}}", "", tVal, false},
   686  	// A bug was introduced that broke map lookups for lower-case names.
   687  	{"bug9", "{{.cause}}", "neglect", map[string]string{"cause": "neglect"}, true},
   688  	// Field chain starting with function did not work.
   689  	{"bug10", "{{mapOfThree.three}}-{{(mapOfThree).three}}", "3-3", 0, true},
   690  	// Dereferencing nil pointer while evaluating function arguments should not panic. Issue 7333.
   691  	{"bug11", "{{valueString .PS}}", "", T{}, false},
   692  	// 0xef gave constant type float64. Issue 8622.
   693  	{"bug12xe", "{{printf `%T` 0xef}}", "int", T{}, true},
   694  	{"bug12xE", "{{printf `%T` 0xEE}}", "int", T{}, true},
   695  	{"bug12Xe", "{{printf `%T` 0Xef}}", "int", T{}, true},
   696  	{"bug12XE", "{{printf `%T` 0XEE}}", "int", T{}, true},
   697  	// Chained nodes did not work as arguments. Issue 8473.
   698  	{"bug13", "{{print (.Copy).I}}", "17", tVal, true},
   699  	// Didn't protect against nil or literal values in field chains.
   700  	{"bug14a", "{{(nil).True}}", "", tVal, false},
   701  	{"bug14b", "{{$x := nil}}{{$x.anything}}", "", tVal, false},
   702  	{"bug14c", `{{$x := (1.0)}}{{$y := ("hello")}}{{$x.anything}}{{$y.true}}`, "", tVal, false},
   703  	// Didn't call validateType on function results. Issue 10800.
   704  	{"bug15", "{{valueString returnInt}}", "", tVal, false},
   705  	// Variadic function corner cases. Issue 10946.
   706  	{"bug16a", "{{true|printf}}", "", tVal, false},
   707  	{"bug16b", "{{1|printf}}", "", tVal, false},
   708  	{"bug16c", "{{1.1|printf}}", "", tVal, false},
   709  	{"bug16d", "{{'x'|printf}}", "", tVal, false},
   710  	{"bug16e", "{{0i|printf}}", "", tVal, false},
   711  	{"bug16f", "{{true|twoArgs \"xxx\"}}", "", tVal, false},
   712  	{"bug16g", "{{\"aaa\" |twoArgs \"bbb\"}}", "twoArgs=bbbaaa", tVal, true},
   713  	{"bug16h", "{{1|oneArg}}", "", tVal, false},
   714  	{"bug16i", "{{\"aaa\"|oneArg}}", "oneArg=aaa", tVal, true},
   715  	{"bug16j", "{{1+2i|printf \"%v\"}}", "(1+2i)", tVal, true},
   716  	{"bug16k", "{{\"aaa\"|printf }}", "aaa", tVal, true},
   717  	{"bug17a", "{{.NonEmptyInterface.X}}", "x", tVal, true},
   718  	{"bug17b", "-{{.NonEmptyInterface.Method1 1234}}-", "-1234-", tVal, true},
   719  	{"bug17c", "{{len .NonEmptyInterfacePtS}}", "2", tVal, true},
   720  	{"bug17d", "{{index .NonEmptyInterfacePtS 0}}", "a", tVal, true},
   721  	{"bug17e", "{{range .NonEmptyInterfacePtS}}-{{.}}-{{end}}", "-a--b-", tVal, true},
   722  
   723  	// More variadic function corner cases. Some runes would get evaluated
   724  	// as constant floats instead of ints. Issue 34483.
   725  	{"bug18a", "{{eq . '.'}}", "true", '.', true},
   726  	{"bug18b", "{{eq . 'e'}}", "true", 'e', true},
   727  	{"bug18c", "{{eq . 'P'}}", "true", 'P', true},
   728  
   729  	{"issue56490", "{{$i := 0}}{{$x := 0}}{{range $i = .AI}}{{end}}{{$i}}", "5", tVal, true},
   730  	{"issue60801", "{{$k := 0}}{{$v := 0}}{{range $k, $v = .AI}}{{$k}}={{$v}} {{end}}", "0=3 1=4 2=5 ", tVal, true},
   731  }
   732  
   733  func fVal1(i int) iter.Seq[int] {
   734  	return func(yield func(int) bool) {
   735  		for v := range i {
   736  			if !yield(v) {
   737  				break
   738  			}
   739  		}
   740  	}
   741  }
   742  
   743  func fVal2(i int) iter.Seq2[int, int] {
   744  	return func(yield func(int, int) bool) {
   745  		for v := range i {
   746  			if !yield(v, v+1) {
   747  				break
   748  			}
   749  		}
   750  	}
   751  }
   752  
   753  const rangeTestInt = `{{range $v := .}}{{printf "%T%d" $v $v}}{{end}}`
   754  
   755  func rangeTestData[T int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr]() string {
   756  	I := T(5)
   757  	var buf strings.Builder
   758  	for i := T(0); i < I; i++ {
   759  		fmt.Fprintf(&buf, "%T%d", i, i)
   760  	}
   761  	return buf.String()
   762  }
   763  
   764  func zeroArgs() string {
   765  	return "zeroArgs"
   766  }
   767  
   768  func oneArg(a string) string {
   769  	return "oneArg=" + a
   770  }
   771  
   772  func twoArgs(a, b string) string {
   773  	return "twoArgs=" + a + b
   774  }
   775  
   776  func dddArg(a int, b ...string) string {
   777  	return fmt.Sprintln(a, b)
   778  }
   779  
   780  // count returns a channel that will deliver n sequential 1-letter strings starting at "a"
   781  func count(n int) chan string {
   782  	if n == 0 {
   783  		return nil
   784  	}
   785  	c := make(chan string)
   786  	go func() {
   787  		for i := 0; i < n; i++ {
   788  			c <- "abcdefghijklmnop"[i : i+1]
   789  		}
   790  		close(c)
   791  	}()
   792  	return c
   793  }
   794  
   795  // vfunc takes a *V and a V
   796  func vfunc(V, *V) string {
   797  	return "vfunc"
   798  }
   799  
   800  // valueString takes a string, not a pointer.
   801  func valueString(v string) string {
   802  	return "value is ignored"
   803  }
   804  
   805  // returnInt returns an int
   806  func returnInt() int {
   807  	return 7
   808  }
   809  
   810  func add(args ...int) int {
   811  	sum := 0
   812  	for _, x := range args {
   813  		sum += x
   814  	}
   815  	return sum
   816  }
   817  
   818  func echo(arg any) any {
   819  	return arg
   820  }
   821  
   822  func makemap(arg ...string) map[string]string {
   823  	if len(arg)%2 != 0 {
   824  		panic("bad makemap")
   825  	}
   826  	m := make(map[string]string)
   827  	for i := 0; i < len(arg); i += 2 {
   828  		m[arg[i]] = arg[i+1]
   829  	}
   830  	return m
   831  }
   832  
   833  func stringer(s fmt.Stringer) string {
   834  	return s.String()
   835  }
   836  
   837  func mapOfThree() any {
   838  	return map[string]int{"three": 3}
   839  }
   840  
   841  func testExecute(execTests []execTest, template *Template, t *testing.T) {
   842  	b := new(strings.Builder)
   843  	funcs := FuncMap{
   844  		"add":         add,
   845  		"count":       count,
   846  		"dddArg":      dddArg,
   847  		"die":         func() bool { panic("die") },
   848  		"echo":        echo,
   849  		"makemap":     makemap,
   850  		"mapOfThree":  mapOfThree,
   851  		"oneArg":      oneArg,
   852  		"returnInt":   returnInt,
   853  		"stringer":    stringer,
   854  		"twoArgs":     twoArgs,
   855  		"typeOf":      typeOf,
   856  		"valueString": valueString,
   857  		"vfunc":       vfunc,
   858  		"zeroArgs":    zeroArgs,
   859  	}
   860  	for _, test := range execTests {
   861  		var tmpl *Template
   862  		var err error
   863  		if template == nil {
   864  			tmpl, err = New(test.name).Funcs(funcs).Parse(test.input)
   865  		} else {
   866  			tmpl, err = template.New(test.name).Funcs(funcs).Parse(test.input)
   867  		}
   868  		if err != nil {
   869  			t.Errorf("%s: parse error: %s", test.name, err)
   870  			continue
   871  		}
   872  		b.Reset()
   873  		err = tmpl.Execute(b, test.data)
   874  		switch {
   875  		case !test.ok && err == nil:
   876  			t.Errorf("%s: expected error; got none", test.name)
   877  			continue
   878  		case test.ok && err != nil:
   879  			t.Errorf("%s: unexpected execute error: %s", test.name, err)
   880  			continue
   881  		case !test.ok && err != nil:
   882  			// expected error, got one
   883  			if *debug {
   884  				fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)
   885  			}
   886  		}
   887  		result := b.String()
   888  		if result != test.output {
   889  			t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result)
   890  		}
   891  	}
   892  }
   893  
   894  func TestExecute(t *testing.T) {
   895  	testExecute(execTests, nil, t)
   896  }
   897  
   898  var delimPairs = []string{
   899  	"", "", // default
   900  	"{{", "}}", // same as default
   901  	"<<", ">>", // distinct
   902  	"|", "|", // same
   903  	"(日)", "(本)", // peculiar
   904  }
   905  
   906  func TestDelims(t *testing.T) {
   907  	const hello = "Hello, world"
   908  	var value = struct{ Str string }{hello}
   909  	for i := 0; i < len(delimPairs); i += 2 {
   910  		text := ".Str"
   911  		left := delimPairs[i+0]
   912  		trueLeft := left
   913  		right := delimPairs[i+1]
   914  		trueRight := right
   915  		if left == "" { // default case
   916  			trueLeft = "{{"
   917  		}
   918  		if right == "" { // default case
   919  			trueRight = "}}"
   920  		}
   921  		text = trueLeft + text + trueRight
   922  		// Now add a comment
   923  		text += trueLeft + "/*comment*/" + trueRight
   924  		// Now add  an action containing a string.
   925  		text += trueLeft + `"` + trueLeft + `"` + trueRight
   926  		// At this point text looks like `{{.Str}}{{/*comment*/}}{{"{{"}}`.
   927  		tmpl, err := New("delims").Delims(left, right).Parse(text)
   928  		if err != nil {
   929  			t.Fatalf("delim %q text %q parse err %s", left, text, err)
   930  		}
   931  		var b = new(strings.Builder)
   932  		err = tmpl.Execute(b, value)
   933  		if err != nil {
   934  			t.Fatalf("delim %q exec err %s", left, err)
   935  		}
   936  		if b.String() != hello+trueLeft {
   937  			t.Errorf("expected %q got %q", hello+trueLeft, b.String())
   938  		}
   939  	}
   940  }
   941  
   942  // Check that an error from a method flows back to the top.
   943  func TestExecuteError(t *testing.T) {
   944  	b := new(bytes.Buffer)
   945  	tmpl := New("error")
   946  	_, err := tmpl.Parse("{{.MyError true}}")
   947  	if err != nil {
   948  		t.Fatalf("parse error: %s", err)
   949  	}
   950  	err = tmpl.Execute(b, tVal)
   951  	if err == nil {
   952  		t.Errorf("expected error; got none")
   953  	} else if !strings.Contains(err.Error(), myError.Error()) {
   954  		if *debug {
   955  			fmt.Printf("test execute error: %s\n", err)
   956  		}
   957  		t.Errorf("expected myError; got %s", err)
   958  	}
   959  }
   960  
   961  const execErrorText = `line 1
   962  line 2
   963  line 3
   964  {{template "one" .}}
   965  {{define "one"}}{{template "two" .}}{{end}}
   966  {{define "two"}}{{template "three" .}}{{end}}
   967  {{define "three"}}{{index "hi" $}}{{end}}`
   968  
   969  // Check that an error from a nested template contains all the relevant information.
   970  func TestExecError(t *testing.T) {
   971  	tmpl, err := New("top").Parse(execErrorText)
   972  	if err != nil {
   973  		t.Fatal("parse error:", err)
   974  	}
   975  	var b bytes.Buffer
   976  	err = tmpl.Execute(&b, 5) // 5 is out of range indexing "hi"
   977  	if err == nil {
   978  		t.Fatal("expected error")
   979  	}
   980  	const want = `template: top:7:20: executing "three" at <index "hi" $>: error calling index: index out of range: 5`
   981  	got := err.Error()
   982  	if got != want {
   983  		t.Errorf("expected\n%q\ngot\n%q", want, got)
   984  	}
   985  }
   986  
   987  type CustomError struct{}
   988  
   989  func (*CustomError) Error() string { return "heyo !" }
   990  
   991  // Check that a custom error can be returned.
   992  func TestExecError_CustomError(t *testing.T) {
   993  	failingFunc := func() (string, error) {
   994  		return "", &CustomError{}
   995  	}
   996  	tmpl := Must(New("top").Funcs(FuncMap{
   997  		"err": failingFunc,
   998  	}).Parse("{{ err }}"))
   999  
  1000  	var b bytes.Buffer
  1001  	err := tmpl.Execute(&b, nil)
  1002  
  1003  	var e *CustomError
  1004  	if !errors.As(err, &e) {
  1005  		t.Fatalf("expected custom error; got %s", err)
  1006  	}
  1007  }
  1008  
  1009  func TestJSEscaping(t *testing.T) {
  1010  	testCases := []struct {
  1011  		in, exp string
  1012  	}{
  1013  		{`a`, `a`},
  1014  		{`'foo`, `\'foo`},
  1015  		{`Go "jump" \`, `Go \"jump\" \\`},
  1016  		{`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`},
  1017  		{"unprintable \uFFFE", `unprintable \uFFFE`},
  1018  		{`<html>`, `\u003Chtml\u003E`},
  1019  		{`no = in attributes`, `no \u003D in attributes`},
  1020  		{`&#x27; does not become HTML entity`, `\u0026#x27; does not become HTML entity`},
  1021  	}
  1022  	for _, tc := range testCases {
  1023  		s := JSEscapeString(tc.in)
  1024  		if s != tc.exp {
  1025  			t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp)
  1026  		}
  1027  	}
  1028  }
  1029  
  1030  // A nice example: walk a binary tree.
  1031  
  1032  type Tree struct {
  1033  	Val         int
  1034  	Left, Right *Tree
  1035  }
  1036  
  1037  // Use different delimiters to test Set.Delims.
  1038  // Also test the trimming of leading and trailing spaces.
  1039  const treeTemplate = `
  1040  	(- define "tree" -)
  1041  	[
  1042  		(- .Val -)
  1043  		(- with .Left -)
  1044  			(template "tree" . -)
  1045  		(- end -)
  1046  		(- with .Right -)
  1047  			(- template "tree" . -)
  1048  		(- end -)
  1049  	]
  1050  	(- end -)
  1051  `
  1052  
  1053  func TestTree(t *testing.T) {
  1054  	var tree = &Tree{
  1055  		1,
  1056  		&Tree{
  1057  			2, &Tree{
  1058  				3,
  1059  				&Tree{
  1060  					4, nil, nil,
  1061  				},
  1062  				nil,
  1063  			},
  1064  			&Tree{
  1065  				5,
  1066  				&Tree{
  1067  					6, nil, nil,
  1068  				},
  1069  				nil,
  1070  			},
  1071  		},
  1072  		&Tree{
  1073  			7,
  1074  			&Tree{
  1075  				8,
  1076  				&Tree{
  1077  					9, nil, nil,
  1078  				},
  1079  				nil,
  1080  			},
  1081  			&Tree{
  1082  				10,
  1083  				&Tree{
  1084  					11, nil, nil,
  1085  				},
  1086  				nil,
  1087  			},
  1088  		},
  1089  	}
  1090  	tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate)
  1091  	if err != nil {
  1092  		t.Fatal("parse error:", err)
  1093  	}
  1094  	var b strings.Builder
  1095  	const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]"
  1096  	// First by looking up the template.
  1097  	err = tmpl.Lookup("tree").Execute(&b, tree)
  1098  	if err != nil {
  1099  		t.Fatal("exec error:", err)
  1100  	}
  1101  	result := b.String()
  1102  	if result != expect {
  1103  		t.Errorf("expected %q got %q", expect, result)
  1104  	}
  1105  	// Then direct to execution.
  1106  	b.Reset()
  1107  	err = tmpl.ExecuteTemplate(&b, "tree", tree)
  1108  	if err != nil {
  1109  		t.Fatal("exec error:", err)
  1110  	}
  1111  	result = b.String()
  1112  	if result != expect {
  1113  		t.Errorf("expected %q got %q", expect, result)
  1114  	}
  1115  }
  1116  
  1117  func TestExecuteOnNewTemplate(t *testing.T) {
  1118  	// This is issue 3872.
  1119  	New("Name").Templates()
  1120  	// This is issue 11379.
  1121  	new(Template).Templates()
  1122  	new(Template).Parse("")
  1123  	new(Template).New("abc").Parse("")
  1124  	new(Template).Execute(nil, nil)                // returns an error (but does not crash)
  1125  	new(Template).ExecuteTemplate(nil, "XXX", nil) // returns an error (but does not crash)
  1126  }
  1127  
  1128  const testTemplates = `{{define "one"}}one{{end}}{{define "two"}}two{{end}}`
  1129  
  1130  func TestMessageForExecuteEmpty(t *testing.T) {
  1131  	// Test a truly empty template.
  1132  	tmpl := New("empty")
  1133  	var b bytes.Buffer
  1134  	err := tmpl.Execute(&b, 0)
  1135  	if err == nil {
  1136  		t.Fatal("expected initial error")
  1137  	}
  1138  	got := err.Error()
  1139  	want := `template: empty: "empty" is an incomplete or empty template`
  1140  	if got != want {
  1141  		t.Errorf("expected error %s got %s", want, got)
  1142  	}
  1143  	// Add a non-empty template to check that the error is helpful.
  1144  	tests, err := New("").Parse(testTemplates)
  1145  	if err != nil {
  1146  		t.Fatal(err)
  1147  	}
  1148  	tmpl.AddParseTree("secondary", tests.Tree)
  1149  	err = tmpl.Execute(&b, 0)
  1150  	if err == nil {
  1151  		t.Fatal("expected second error")
  1152  	}
  1153  	got = err.Error()
  1154  	want = `template: empty: "empty" is an incomplete or empty template`
  1155  	if got != want {
  1156  		t.Errorf("expected error %s got %s", want, got)
  1157  	}
  1158  	// Make sure we can execute the secondary.
  1159  	err = tmpl.ExecuteTemplate(&b, "secondary", 0)
  1160  	if err != nil {
  1161  		t.Fatal(err)
  1162  	}
  1163  }
  1164  
  1165  func TestFinalForPrintf(t *testing.T) {
  1166  	tmpl, err := New("").Parse(`{{"x" | printf}}`)
  1167  	if err != nil {
  1168  		t.Fatal(err)
  1169  	}
  1170  	var b bytes.Buffer
  1171  	err = tmpl.Execute(&b, 0)
  1172  	if err != nil {
  1173  		t.Fatal(err)
  1174  	}
  1175  }
  1176  
  1177  type cmpTest struct {
  1178  	expr  string
  1179  	truth string
  1180  	ok    bool
  1181  }
  1182  
  1183  var cmpTests = []cmpTest{
  1184  	{"eq true true", "true", true},
  1185  	{"eq true false", "false", true},
  1186  	{"eq 1+2i 1+2i", "true", true},
  1187  	{"eq 1+2i 1+3i", "false", true},
  1188  	{"eq 1.5 1.5", "true", true},
  1189  	{"eq 1.5 2.5", "false", true},
  1190  	{"eq 1 1", "true", true},
  1191  	{"eq 1 2", "false", true},
  1192  	{"eq `xy` `xy`", "true", true},
  1193  	{"eq `xy` `xyz`", "false", true},
  1194  	{"eq .Uthree .Uthree", "true", true},
  1195  	{"eq .Uthree .Ufour", "false", true},
  1196  	{"eq 3 4 5 6 3", "true", true},
  1197  	{"eq 3 4 5 6 7", "false", true},
  1198  	{"ne true true", "false", true},
  1199  	{"ne true false", "true", true},
  1200  	{"ne 1+2i 1+2i", "false", true},
  1201  	{"ne 1+2i 1+3i", "true", true},
  1202  	{"ne 1.5 1.5", "false", true},
  1203  	{"ne 1.5 2.5", "true", true},
  1204  	{"ne 1 1", "false", true},
  1205  	{"ne 1 2", "true", true},
  1206  	{"ne `xy` `xy`", "false", true},
  1207  	{"ne `xy` `xyz`", "true", true},
  1208  	{"ne .Uthree .Uthree", "false", true},
  1209  	{"ne .Uthree .Ufour", "true", true},
  1210  	{"lt 1.5 1.5", "false", true},
  1211  	{"lt 1.5 2.5", "true", true},
  1212  	{"lt 1 1", "false", true},
  1213  	{"lt 1 2", "true", true},
  1214  	{"lt `xy` `xy`", "false", true},
  1215  	{"lt `xy` `xyz`", "true", true},
  1216  	{"lt .Uthree .Uthree", "false", true},
  1217  	{"lt .Uthree .Ufour", "true", true},
  1218  	{"le 1.5 1.5", "true", true},
  1219  	{"le 1.5 2.5", "true", true},
  1220  	{"le 2.5 1.5", "false", true},
  1221  	{"le 1 1", "true", true},
  1222  	{"le 1 2", "true", true},
  1223  	{"le 2 1", "false", true},
  1224  	{"le `xy` `xy`", "true", true},
  1225  	{"le `xy` `xyz`", "true", true},
  1226  	{"le `xyz` `xy`", "false", true},
  1227  	{"le .Uthree .Uthree", "true", true},
  1228  	{"le .Uthree .Ufour", "true", true},
  1229  	{"le .Ufour .Uthree", "false", true},
  1230  	{"gt 1.5 1.5", "false", true},
  1231  	{"gt 1.5 2.5", "false", true},
  1232  	{"gt 1 1", "false", true},
  1233  	{"gt 2 1", "true", true},
  1234  	{"gt 1 2", "false", true},
  1235  	{"gt `xy` `xy`", "false", true},
  1236  	{"gt `xy` `xyz`", "false", true},
  1237  	{"gt .Uthree .Uthree", "false", true},
  1238  	{"gt .Uthree .Ufour", "false", true},
  1239  	{"gt .Ufour .Uthree", "true", true},
  1240  	{"ge 1.5 1.5", "true", true},
  1241  	{"ge 1.5 2.5", "false", true},
  1242  	{"ge 2.5 1.5", "true", true},
  1243  	{"ge 1 1", "true", true},
  1244  	{"ge 1 2", "false", true},
  1245  	{"ge 2 1", "true", true},
  1246  	{"ge `xy` `xy`", "true", true},
  1247  	{"ge `xy` `xyz`", "false", true},
  1248  	{"ge `xyz` `xy`", "true", true},
  1249  	{"ge .Uthree .Uthree", "true", true},
  1250  	{"ge .Uthree .Ufour", "false", true},
  1251  	{"ge .Ufour .Uthree", "true", true},
  1252  	// Mixing signed and unsigned integers.
  1253  	{"eq .Uthree .Three", "true", true},
  1254  	{"eq .Three .Uthree", "true", true},
  1255  	{"le .Uthree .Three", "true", true},
  1256  	{"le .Three .Uthree", "true", true},
  1257  	{"ge .Uthree .Three", "true", true},
  1258  	{"ge .Three .Uthree", "true", true},
  1259  	{"lt .Uthree .Three", "false", true},
  1260  	{"lt .Three .Uthree", "false", true},
  1261  	{"gt .Uthree .Three", "false", true},
  1262  	{"gt .Three .Uthree", "false", true},
  1263  	{"eq .Ufour .Three", "false", true},
  1264  	{"lt .Ufour .Three", "false", true},
  1265  	{"gt .Ufour .Three", "true", true},
  1266  	{"eq .NegOne .Uthree", "false", true},
  1267  	{"eq .Uthree .NegOne", "false", true},
  1268  	{"ne .NegOne .Uthree", "true", true},
  1269  	{"ne .Uthree .NegOne", "true", true},
  1270  	{"lt .NegOne .Uthree", "true", true},
  1271  	{"lt .Uthree .NegOne", "false", true},
  1272  	{"le .NegOne .Uthree", "true", true},
  1273  	{"le .Uthree .NegOne", "false", true},
  1274  	{"gt .NegOne .Uthree", "false", true},
  1275  	{"gt .Uthree .NegOne", "true", true},
  1276  	{"ge .NegOne .Uthree", "false", true},
  1277  	{"ge .Uthree .NegOne", "true", true},
  1278  	{"eq (index `x` 0) 'x'", "true", true}, // The example that triggered this rule.
  1279  	{"eq (index `x` 0) 'y'", "false", true},
  1280  	{"eq .V1 .V2", "true", true},
  1281  	{"eq .Ptr .Ptr", "true", true},
  1282  	{"eq .Ptr .NilPtr", "false", true},
  1283  	{"eq .NilPtr .NilPtr", "true", true},
  1284  	{"eq .Iface1 .Iface1", "true", true},
  1285  	{"eq .Iface1 .NilIface", "false", true},
  1286  	{"eq .NilIface .NilIface", "true", true},
  1287  	{"eq .NilIface .Iface1", "false", true},
  1288  	{"eq .NilIface 0", "false", true},
  1289  	{"eq 0 .NilIface", "false", true},
  1290  	{"eq .Map .Map", "true", true},        // Uncomparable types but nil is OK.
  1291  	{"eq .Map nil", "true", true},         // Uncomparable types but nil is OK.
  1292  	{"eq nil .Map", "true", true},         // Uncomparable types but nil is OK.
  1293  	{"eq .Map .NonNilMap", "false", true}, // Uncomparable types but nil is OK.
  1294  	// Errors
  1295  	{"eq `xy` 1", "", false},                // Different types.
  1296  	{"eq 2 2.0", "", false},                 // Different types.
  1297  	{"lt true true", "", false},             // Unordered types.
  1298  	{"lt 1+0i 1+0i", "", false},             // Unordered types.
  1299  	{"eq .Ptr 1", "", false},                // Incompatible types.
  1300  	{"eq .Ptr .NegOne", "", false},          // Incompatible types.
  1301  	{"eq .Map .V1", "", false},              // Uncomparable types.
  1302  	{"eq .NonNilMap .NonNilMap", "", false}, // Uncomparable types.
  1303  }
  1304  
  1305  func TestComparison(t *testing.T) {
  1306  	b := new(strings.Builder)
  1307  	var cmpStruct = struct {
  1308  		Uthree, Ufour    uint
  1309  		NegOne, Three    int
  1310  		Ptr, NilPtr      *int
  1311  		NonNilMap        map[int]int
  1312  		Map              map[int]int
  1313  		V1, V2           V
  1314  		Iface1, NilIface fmt.Stringer
  1315  	}{
  1316  		Uthree:    3,
  1317  		Ufour:     4,
  1318  		NegOne:    -1,
  1319  		Three:     3,
  1320  		Ptr:       new(int),
  1321  		NonNilMap: make(map[int]int),
  1322  		Iface1:    b,
  1323  	}
  1324  	for _, test := range cmpTests {
  1325  		text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr)
  1326  		tmpl, err := New("empty").Parse(text)
  1327  		if err != nil {
  1328  			t.Fatalf("%q: %s", test.expr, err)
  1329  		}
  1330  		b.Reset()
  1331  		err = tmpl.Execute(b, &cmpStruct)
  1332  		if test.ok && err != nil {
  1333  			t.Errorf("%s errored incorrectly: %s", test.expr, err)
  1334  			continue
  1335  		}
  1336  		if !test.ok && err == nil {
  1337  			t.Errorf("%s did not error", test.expr)
  1338  			continue
  1339  		}
  1340  		if b.String() != test.truth {
  1341  			t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String())
  1342  		}
  1343  	}
  1344  }
  1345  
  1346  func TestMissingMapKey(t *testing.T) {
  1347  	data := map[string]int{
  1348  		"x": 99,
  1349  	}
  1350  	tmpl, err := New("t1").Parse("{{.x}} {{.y}}")
  1351  	if err != nil {
  1352  		t.Fatal(err)
  1353  	}
  1354  	var b strings.Builder
  1355  	// By default, just get "<no value>"
  1356  	err = tmpl.Execute(&b, data)
  1357  	if err != nil {
  1358  		t.Fatal(err)
  1359  	}
  1360  	want := "99 <no value>"
  1361  	got := b.String()
  1362  	if got != want {
  1363  		t.Errorf("got %q; expected %q", got, want)
  1364  	}
  1365  	// Same if we set the option explicitly to the default.
  1366  	tmpl.Option("missingkey=default")
  1367  	b.Reset()
  1368  	err = tmpl.Execute(&b, data)
  1369  	if err != nil {
  1370  		t.Fatal("default:", err)
  1371  	}
  1372  	want = "99 <no value>"
  1373  	got = b.String()
  1374  	if got != want {
  1375  		t.Errorf("got %q; expected %q", got, want)
  1376  	}
  1377  	// Next we ask for a zero value
  1378  	tmpl.Option("missingkey=zero")
  1379  	b.Reset()
  1380  	err = tmpl.Execute(&b, data)
  1381  	if err != nil {
  1382  		t.Fatal("zero:", err)
  1383  	}
  1384  	want = "99 0"
  1385  	got = b.String()
  1386  	if got != want {
  1387  		t.Errorf("got %q; expected %q", got, want)
  1388  	}
  1389  	// Now we ask for an error.
  1390  	tmpl.Option("missingkey=error")
  1391  	err = tmpl.Execute(&b, data)
  1392  	if err == nil {
  1393  		t.Errorf("expected error; got none")
  1394  	}
  1395  	// same Option, but now a nil interface: ask for an error
  1396  	err = tmpl.Execute(&b, nil)
  1397  	t.Log(err)
  1398  	if err == nil {
  1399  		t.Errorf("expected error for nil-interface; got none")
  1400  	}
  1401  }
  1402  
  1403  // Test that the error message for multiline unterminated string
  1404  // refers to the line number of the opening quote.
  1405  func TestUnterminatedStringError(t *testing.T) {
  1406  	_, err := New("X").Parse("hello\n\n{{`unterminated\n\n\n\n}}\n some more\n\n")
  1407  	if err == nil {
  1408  		t.Fatal("expected error")
  1409  	}
  1410  	str := err.Error()
  1411  	if !strings.Contains(str, "X:3: unterminated raw quoted string") {
  1412  		t.Fatalf("unexpected error: %s", str)
  1413  	}
  1414  }
  1415  
  1416  const alwaysErrorText = "always be failing"
  1417  
  1418  var alwaysError = errors.New(alwaysErrorText)
  1419  
  1420  type ErrorWriter int
  1421  
  1422  func (e ErrorWriter) Write(p []byte) (int, error) {
  1423  	return 0, alwaysError
  1424  }
  1425  
  1426  func TestExecuteGivesExecError(t *testing.T) {
  1427  	// First, a non-execution error shouldn't be an ExecError.
  1428  	tmpl, err := New("X").Parse("hello")
  1429  	if err != nil {
  1430  		t.Fatal(err)
  1431  	}
  1432  	err = tmpl.Execute(ErrorWriter(0), 0)
  1433  	if err == nil {
  1434  		t.Fatal("expected error; got none")
  1435  	}
  1436  	if err.Error() != alwaysErrorText {
  1437  		t.Errorf("expected %q error; got %q", alwaysErrorText, err)
  1438  	}
  1439  	// This one should be an ExecError.
  1440  	tmpl, err = New("X").Parse("hello, {{.X.Y}}")
  1441  	if err != nil {
  1442  		t.Fatal(err)
  1443  	}
  1444  	err = tmpl.Execute(io.Discard, 0)
  1445  	if err == nil {
  1446  		t.Fatal("expected error; got none")
  1447  	}
  1448  	eerr, ok := err.(ExecError)
  1449  	if !ok {
  1450  		t.Fatalf("did not expect ExecError %s", eerr)
  1451  	}
  1452  	expect := "field X in type int"
  1453  	if !strings.Contains(err.Error(), expect) {
  1454  		t.Errorf("expected %q; got %q", expect, err)
  1455  	}
  1456  }
  1457  
  1458  func funcNameTestFunc() int {
  1459  	return 0
  1460  }
  1461  
  1462  func TestGoodFuncNames(t *testing.T) {
  1463  	names := []string{
  1464  		"_",
  1465  		"a",
  1466  		"a1",
  1467  		"a1",
  1468  		"Ӵ",
  1469  	}
  1470  	for _, name := range names {
  1471  		tmpl := New("X").Funcs(
  1472  			FuncMap{
  1473  				name: funcNameTestFunc,
  1474  			},
  1475  		)
  1476  		if tmpl == nil {
  1477  			t.Fatalf("nil result for %q", name)
  1478  		}
  1479  	}
  1480  }
  1481  
  1482  func TestBadFuncNames(t *testing.T) {
  1483  	names := []string{
  1484  		"",
  1485  		"2",
  1486  		"a-b",
  1487  	}
  1488  	for _, name := range names {
  1489  		testBadFuncName(name, t)
  1490  	}
  1491  }
  1492  
  1493  func testBadFuncName(name string, t *testing.T) {
  1494  	t.Helper()
  1495  	defer func() {
  1496  		recover()
  1497  	}()
  1498  	New("X").Funcs(
  1499  		FuncMap{
  1500  			name: funcNameTestFunc,
  1501  		},
  1502  	)
  1503  	// If we get here, the name did not cause a panic, which is how Funcs
  1504  	// reports an error.
  1505  	t.Errorf("%q succeeded incorrectly as function name", name)
  1506  }
  1507  
  1508  func TestBlock(t *testing.T) {
  1509  	const (
  1510  		input   = `a({{block "inner" .}}bar({{.}})baz{{end}})b`
  1511  		want    = `a(bar(hello)baz)b`
  1512  		overlay = `{{define "inner"}}foo({{.}})bar{{end}}`
  1513  		want2   = `a(foo(goodbye)bar)b`
  1514  	)
  1515  	tmpl, err := New("outer").Parse(input)
  1516  	if err != nil {
  1517  		t.Fatal(err)
  1518  	}
  1519  	tmpl2, err := Must(tmpl.Clone()).Parse(overlay)
  1520  	if err != nil {
  1521  		t.Fatal(err)
  1522  	}
  1523  
  1524  	var buf strings.Builder
  1525  	if err := tmpl.Execute(&buf, "hello"); err != nil {
  1526  		t.Fatal(err)
  1527  	}
  1528  	if got := buf.String(); got != want {
  1529  		t.Errorf("got %q, want %q", got, want)
  1530  	}
  1531  
  1532  	buf.Reset()
  1533  	if err := tmpl2.Execute(&buf, "goodbye"); err != nil {
  1534  		t.Fatal(err)
  1535  	}
  1536  	if got := buf.String(); got != want2 {
  1537  		t.Errorf("got %q, want %q", got, want2)
  1538  	}
  1539  }
  1540  
  1541  func TestEvalFieldErrors(t *testing.T) {
  1542  	tests := []struct {
  1543  		name, src string
  1544  		value     any
  1545  		want      string
  1546  	}{
  1547  		{
  1548  			// Check that calling an invalid field on nil pointer
  1549  			// prints a field error instead of a distracting nil
  1550  			// pointer error. https://golang.org/issue/15125
  1551  			"MissingFieldOnNil",
  1552  			"{{.MissingField}}",
  1553  			(*T)(nil),
  1554  			"can't evaluate field MissingField in type *template.T",
  1555  		},
  1556  		{
  1557  			"MissingFieldOnNonNil",
  1558  			"{{.MissingField}}",
  1559  			&T{},
  1560  			"can't evaluate field MissingField in type *template.T",
  1561  		},
  1562  		{
  1563  			"ExistingFieldOnNil",
  1564  			"{{.X}}",
  1565  			(*T)(nil),
  1566  			"nil pointer evaluating *template.T.X",
  1567  		},
  1568  		{
  1569  			"MissingKeyOnNilMap",
  1570  			"{{.MissingKey}}",
  1571  			(*map[string]string)(nil),
  1572  			"nil pointer evaluating *map[string]string.MissingKey",
  1573  		},
  1574  		{
  1575  			"MissingKeyOnNilMapPtr",
  1576  			"{{.MissingKey}}",
  1577  			(*map[string]string)(nil),
  1578  			"nil pointer evaluating *map[string]string.MissingKey",
  1579  		},
  1580  		{
  1581  			"MissingKeyOnMapPtrToNil",
  1582  			"{{.MissingKey}}",
  1583  			&map[string]string{},
  1584  			"<nil>",
  1585  		},
  1586  	}
  1587  	for _, tc := range tests {
  1588  		t.Run(tc.name, func(t *testing.T) {
  1589  			tmpl := Must(New("tmpl").Parse(tc.src))
  1590  			err := tmpl.Execute(io.Discard, tc.value)
  1591  			got := "<nil>"
  1592  			if err != nil {
  1593  				got = err.Error()
  1594  			}
  1595  			if !strings.HasSuffix(got, tc.want) {
  1596  				t.Fatalf("got error %q, want %q", got, tc.want)
  1597  			}
  1598  		})
  1599  	}
  1600  }
  1601  
  1602  func TestMaxExecDepth(t *testing.T) {
  1603  	if testing.Short() {
  1604  		t.Skip("skipping in -short mode")
  1605  	}
  1606  	tmpl := Must(New("tmpl").Parse(`{{template "tmpl" .}}`))
  1607  	err := tmpl.Execute(io.Discard, nil)
  1608  	got := "<nil>"
  1609  	if err != nil {
  1610  		got = err.Error()
  1611  	}
  1612  	const want = "exceeded maximum template depth"
  1613  	if !strings.Contains(got, want) {
  1614  		t.Errorf("got error %q; want %q", got, want)
  1615  	}
  1616  }
  1617  
  1618  func TestAddrOfIndex(t *testing.T) {
  1619  	// golang.org/issue/14916.
  1620  	// Before index worked on reflect.Values, the .String could not be
  1621  	// found on the (incorrectly unaddressable) V value,
  1622  	// in contrast to range, which worked fine.
  1623  	// Also testing that passing a reflect.Value to tmpl.Execute works.
  1624  	texts := []string{
  1625  		`{{range .}}{{.String}}{{end}}`,
  1626  		`{{with index . 0}}{{.String}}{{end}}`,
  1627  	}
  1628  	for _, text := range texts {
  1629  		tmpl := Must(New("tmpl").Parse(text))
  1630  		var buf strings.Builder
  1631  		err := tmpl.Execute(&buf, reflect.ValueOf([]V{{1}}))
  1632  		if err != nil {
  1633  			t.Fatalf("%s: Execute: %v", text, err)
  1634  		}
  1635  		if buf.String() != "<1>" {
  1636  			t.Fatalf("%s: template output = %q, want %q", text, &buf, "<1>")
  1637  		}
  1638  	}
  1639  }
  1640  
  1641  func TestInterfaceValues(t *testing.T) {
  1642  	// golang.org/issue/17714.
  1643  	// Before index worked on reflect.Values, interface values
  1644  	// were always implicitly promoted to the underlying value,
  1645  	// except that nil interfaces were promoted to the zero reflect.Value.
  1646  	// Eliminating a round trip to interface{} and back to reflect.Value
  1647  	// eliminated this promotion, breaking these cases.
  1648  	tests := []struct {
  1649  		text string
  1650  		out  string
  1651  	}{
  1652  		{`{{index .Nil 1}}`, "ERROR: index of untyped nil"},
  1653  		{`{{index .Slice 2}}`, "2"},
  1654  		{`{{index .Slice .Two}}`, "2"},
  1655  		{`{{call .Nil 1}}`, "ERROR: call of nil"},
  1656  		{`{{call .PlusOne 1}}`, "2"},
  1657  		{`{{call .PlusOne .One}}`, "2"},
  1658  		{`{{and (index .Slice 0) true}}`, "0"},
  1659  		{`{{and .Zero true}}`, "0"},
  1660  		{`{{and (index .Slice 1) false}}`, "false"},
  1661  		{`{{and .One false}}`, "false"},
  1662  		{`{{or (index .Slice 0) false}}`, "false"},
  1663  		{`{{or .Zero false}}`, "false"},
  1664  		{`{{or (index .Slice 1) true}}`, "1"},
  1665  		{`{{or .One true}}`, "1"},
  1666  		{`{{not (index .Slice 0)}}`, "true"},
  1667  		{`{{not .Zero}}`, "true"},
  1668  		{`{{not (index .Slice 1)}}`, "false"},
  1669  		{`{{not .One}}`, "false"},
  1670  		{`{{eq (index .Slice 0) .Zero}}`, "true"},
  1671  		{`{{eq (index .Slice 1) .One}}`, "true"},
  1672  		{`{{ne (index .Slice 0) .Zero}}`, "false"},
  1673  		{`{{ne (index .Slice 1) .One}}`, "false"},
  1674  		{`{{ge (index .Slice 0) .One}}`, "false"},
  1675  		{`{{ge (index .Slice 1) .Zero}}`, "true"},
  1676  		{`{{gt (index .Slice 0) .One}}`, "false"},
  1677  		{`{{gt (index .Slice 1) .Zero}}`, "true"},
  1678  		{`{{le (index .Slice 0) .One}}`, "true"},
  1679  		{`{{le (index .Slice 1) .Zero}}`, "false"},
  1680  		{`{{lt (index .Slice 0) .One}}`, "true"},
  1681  		{`{{lt (index .Slice 1) .Zero}}`, "false"},
  1682  	}
  1683  
  1684  	for _, tt := range tests {
  1685  		tmpl := Must(New("tmpl").Parse(tt.text))
  1686  		var buf strings.Builder
  1687  		err := tmpl.Execute(&buf, map[string]any{
  1688  			"PlusOne": func(n int) int {
  1689  				return n + 1
  1690  			},
  1691  			"Slice": []int{0, 1, 2, 3},
  1692  			"One":   1,
  1693  			"Two":   2,
  1694  			"Nil":   nil,
  1695  			"Zero":  0,
  1696  		})
  1697  		if strings.HasPrefix(tt.out, "ERROR:") {
  1698  			e := strings.TrimSpace(strings.TrimPrefix(tt.out, "ERROR:"))
  1699  			if err == nil || !strings.Contains(err.Error(), e) {
  1700  				t.Errorf("%s: Execute: %v, want error %q", tt.text, err, e)
  1701  			}
  1702  			continue
  1703  		}
  1704  		if err != nil {
  1705  			t.Errorf("%s: Execute: %v", tt.text, err)
  1706  			continue
  1707  		}
  1708  		if buf.String() != tt.out {
  1709  			t.Errorf("%s: template output = %q, want %q", tt.text, &buf, tt.out)
  1710  		}
  1711  	}
  1712  }
  1713  
  1714  // Check that panics during calls are recovered and returned as errors.
  1715  func TestExecutePanicDuringCall(t *testing.T) {
  1716  	funcs := map[string]any{
  1717  		"doPanic": func() string {
  1718  			panic("custom panic string")
  1719  		},
  1720  	}
  1721  	tests := []struct {
  1722  		name    string
  1723  		input   string
  1724  		data    any
  1725  		wantErr string
  1726  	}{
  1727  		{
  1728  			"direct func call panics",
  1729  			"{{doPanic}}", (*T)(nil),
  1730  			`template: t:1:2: executing "t" at <doPanic>: error calling doPanic: custom panic string`,
  1731  		},
  1732  		{
  1733  			"indirect func call panics",
  1734  			"{{call doPanic}}", (*T)(nil),
  1735  			`template: t:1:7: executing "t" at <doPanic>: error calling doPanic: custom panic string`,
  1736  		},
  1737  		{
  1738  			"direct method call panics",
  1739  			"{{.GetU}}", (*T)(nil),
  1740  			`template: t:1:2: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`,
  1741  		},
  1742  		{
  1743  			"indirect method call panics",
  1744  			"{{call .GetU}}", (*T)(nil),
  1745  			`template: t:1:7: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`,
  1746  		},
  1747  		{
  1748  			"func field call panics",
  1749  			"{{call .PanicFunc}}", tVal,
  1750  			`template: t:1:2: executing "t" at <call .PanicFunc>: error calling call: test panic`,
  1751  		},
  1752  		{
  1753  			"method call on nil interface",
  1754  			"{{.NonEmptyInterfaceNil.Method0}}", tVal,
  1755  			`template: t:1:23: executing "t" at <.NonEmptyInterfaceNil.Method0>: nil pointer evaluating template.I.Method0`,
  1756  		},
  1757  	}
  1758  	for _, tc := range tests {
  1759  		b := new(bytes.Buffer)
  1760  		tmpl, err := New("t").Funcs(funcs).Parse(tc.input)
  1761  		if err != nil {
  1762  			t.Fatalf("parse error: %s", err)
  1763  		}
  1764  		err = tmpl.Execute(b, tc.data)
  1765  		if err == nil {
  1766  			t.Errorf("%s: expected error; got none", tc.name)
  1767  		} else if !strings.Contains(err.Error(), tc.wantErr) {
  1768  			if *debug {
  1769  				fmt.Printf("%s: test execute error: %s\n", tc.name, err)
  1770  			}
  1771  			t.Errorf("%s: expected error:\n%s\ngot:\n%s", tc.name, tc.wantErr, err)
  1772  		}
  1773  	}
  1774  }
  1775  
  1776  func TestFunctionCheckDuringCall(t *testing.T) {
  1777  	tests := []struct {
  1778  		name    string
  1779  		input   string
  1780  		data    any
  1781  		wantErr string
  1782  	}{{
  1783  		name:    "call nothing",
  1784  		input:   `{{call}}`,
  1785  		data:    tVal,
  1786  		wantErr: "wrong number of args for call: want at least 1 got 0",
  1787  	},
  1788  		{
  1789  			name:    "call non-function",
  1790  			input:   "{{call .True}}",
  1791  			data:    tVal,
  1792  			wantErr: "error calling call: non-function .True of type bool",
  1793  		},
  1794  		{
  1795  			name:    "call func with wrong argument",
  1796  			input:   "{{call .BinaryFunc 1}}",
  1797  			data:    tVal,
  1798  			wantErr: "error calling call: wrong number of args for .BinaryFunc: got 1 want 2",
  1799  		},
  1800  		{
  1801  			name:    "call variadic func with wrong argument",
  1802  			input:   `{{call .VariadicFuncInt}}`,
  1803  			data:    tVal,
  1804  			wantErr: "error calling call: wrong number of args for .VariadicFuncInt: got 0 want at least 1",
  1805  		},
  1806  		{
  1807  			name:    "call too few return number func",
  1808  			input:   `{{call .TooFewReturnCountFunc}}`,
  1809  			data:    tVal,
  1810  			wantErr: "error calling call: function .TooFewReturnCountFunc has 0 return values; should be 1 or 2",
  1811  		},
  1812  		{
  1813  			name:    "call too many return number func",
  1814  			input:   `{{call .TooManyReturnCountFunc}}`,
  1815  			data:    tVal,
  1816  			wantErr: "error calling call: function .TooManyReturnCountFunc has 3 return values; should be 1 or 2",
  1817  		},
  1818  		{
  1819  			name:    "call invalid return type func",
  1820  			input:   `{{call .InvalidReturnTypeFunc}}`,
  1821  			data:    tVal,
  1822  			wantErr: "error calling call: invalid function signature for .InvalidReturnTypeFunc: second return value should be error; is bool",
  1823  		},
  1824  		{
  1825  			name:    "call pipeline",
  1826  			input:   `{{call (len "test")}}`,
  1827  			data:    nil,
  1828  			wantErr: "error calling call: non-function len \"test\" of type int",
  1829  		},
  1830  	}
  1831  
  1832  	for _, tc := range tests {
  1833  		b := new(bytes.Buffer)
  1834  		tmpl, err := New("t").Parse(tc.input)
  1835  		if err != nil {
  1836  			t.Fatalf("parse error: %s", err)
  1837  		}
  1838  		err = tmpl.Execute(b, tc.data)
  1839  		if err == nil {
  1840  			t.Errorf("%s: expected error; got none", tc.name)
  1841  		} else if tc.wantErr == "" || !strings.Contains(err.Error(), tc.wantErr) {
  1842  			if *debug {
  1843  				fmt.Printf("%s: test execute error: %s\n", tc.name, err)
  1844  			}
  1845  			t.Errorf("%s: expected error:\n%s\ngot:\n%s", tc.name, tc.wantErr, err)
  1846  		}
  1847  	}
  1848  }
  1849  
  1850  // Issue 31810. Check that a parenthesized first argument behaves properly.
  1851  func TestIssue31810(t *testing.T) {
  1852  	// A simple value with no arguments is fine.
  1853  	var b strings.Builder
  1854  	const text = "{{ (.)  }}"
  1855  	tmpl, err := New("").Parse(text)
  1856  	if err != nil {
  1857  		t.Error(err)
  1858  	}
  1859  	err = tmpl.Execute(&b, "result")
  1860  	if err != nil {
  1861  		t.Error(err)
  1862  	}
  1863  	if b.String() != "result" {
  1864  		t.Errorf("%s got %q, expected %q", text, b.String(), "result")
  1865  	}
  1866  
  1867  	// Even a plain function fails - need to use call.
  1868  	f := func() string { return "result" }
  1869  	b.Reset()
  1870  	err = tmpl.Execute(&b, f)
  1871  	if err == nil {
  1872  		t.Error("expected error with no call, got none")
  1873  	}
  1874  
  1875  	// Works if the function is explicitly called.
  1876  	const textCall = "{{ (call .)  }}"
  1877  	tmpl, err = New("").Parse(textCall)
  1878  	b.Reset()
  1879  	err = tmpl.Execute(&b, f)
  1880  	if err != nil {
  1881  		t.Error(err)
  1882  	}
  1883  	if b.String() != "result" {
  1884  		t.Errorf("%s got %q, expected %q", textCall, b.String(), "result")
  1885  	}
  1886  }
  1887  
  1888  // Issue 43065, range over send only channel
  1889  func TestIssue43065(t *testing.T) {
  1890  	var b bytes.Buffer
  1891  	tmp := Must(New("").Parse(`{{range .}}{{end}}`))
  1892  	ch := make(chan<- int)
  1893  	err := tmp.Execute(&b, ch)
  1894  	if err == nil {
  1895  		t.Error("expected err got nil")
  1896  	} else if !strings.Contains(err.Error(), "range over send-only channel") {
  1897  		t.Errorf("%s", err)
  1898  	}
  1899  }
  1900  
  1901  // Issue 39807: data race in html/template & text/template
  1902  func TestIssue39807(t *testing.T) {
  1903  	var wg sync.WaitGroup
  1904  
  1905  	tplFoo, err := New("foo").Parse(`{{ template "bar" . }}`)
  1906  	if err != nil {
  1907  		t.Error(err)
  1908  	}
  1909  
  1910  	tplBar, err := New("bar").Parse("bar")
  1911  	if err != nil {
  1912  		t.Error(err)
  1913  	}
  1914  
  1915  	gofuncs := 10
  1916  	numTemplates := 10
  1917  
  1918  	for i := 1; i <= gofuncs; i++ {
  1919  		wg.Add(1)
  1920  		go func() {
  1921  			defer wg.Done()
  1922  			for j := 0; j < numTemplates; j++ {
  1923  				_, err := tplFoo.AddParseTree(tplBar.Name(), tplBar.Tree)
  1924  				if err != nil {
  1925  					t.Error(err)
  1926  				}
  1927  				err = tplFoo.Execute(io.Discard, nil)
  1928  				if err != nil {
  1929  					t.Error(err)
  1930  				}
  1931  			}
  1932  		}()
  1933  	}
  1934  
  1935  	wg.Wait()
  1936  }
  1937  
  1938  // Issue 48215: embedded nil pointer causes panic.
  1939  // Fixed by adding FieldByIndexErr to the reflect package.
  1940  func TestIssue48215(t *testing.T) {
  1941  	type A struct {
  1942  		S string
  1943  	}
  1944  	type B struct {
  1945  		*A
  1946  	}
  1947  	tmpl, err := New("").Parse(`{{ .S }}`)
  1948  	if err != nil {
  1949  		t.Fatal(err)
  1950  	}
  1951  	err = tmpl.Execute(io.Discard, B{})
  1952  	// We expect an error, not a panic.
  1953  	if err == nil {
  1954  		t.Fatal("did not get error for nil embedded struct")
  1955  	}
  1956  	if !strings.Contains(err.Error(), "reflect: indirection through nil pointer to embedded struct field A") {
  1957  		t.Fatal(err)
  1958  	}
  1959  }
  1960  

View as plain text