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