hugo

Fork of github.com/gohugoio/hugo with reverse pagination support

git clone git://git.shimmy1996.com/hugo.git

exec.go (32224B)

    1 // Copyright 2011 The Go Authors. All rights reserved.
    2 // Use of this source code is governed by a BSD-style
    3 // license that can be found in the LICENSE file.
    4 
    5 package template
    6 
    7 import (
    8 	"errors"
    9 	"fmt"
   10 	"github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort"
   11 	"github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
   12 	"io"
   13 	"reflect"
   14 	"runtime"
   15 	"strings"
   16 )
   17 
   18 // maxExecDepth specifies the maximum stack depth of templates within
   19 // templates. This limit is only practically reached by accidentally
   20 // recursive template invocations. This limit allows us to return
   21 // an error instead of triggering a stack overflow.
   22 var maxExecDepth = initMaxExecDepth()
   23 
   24 func initMaxExecDepth() int {
   25 	if runtime.GOARCH == "wasm" {
   26 		return 1000
   27 	}
   28 	return 100000
   29 }
   30 
   31 // state represents the state of an execution. It's not part of the
   32 // template so that multiple executions of the same template
   33 // can execute in parallel.
   34 type stateOld struct {
   35 	tmpl  *Template
   36 	wr    io.Writer
   37 	node  parse.Node // current node, for errors
   38 	vars  []variable // push-down stack of variable values.
   39 	depth int        // the height of the stack of executing templates.
   40 }
   41 
   42 // variable holds the dynamic value of a variable such as $, $x etc.
   43 type variable struct {
   44 	name  string
   45 	value reflect.Value
   46 }
   47 
   48 // push pushes a new variable on the stack.
   49 func (s *state) push(name string, value reflect.Value) {
   50 	s.vars = append(s.vars, variable{name, value})
   51 }
   52 
   53 // mark returns the length of the variable stack.
   54 func (s *state) mark() int {
   55 	return len(s.vars)
   56 }
   57 
   58 // pop pops the variable stack up to the mark.
   59 func (s *state) pop(mark int) {
   60 	s.vars = s.vars[0:mark]
   61 }
   62 
   63 // setVar overwrites the last declared variable with the given name.
   64 // Used by variable assignments.
   65 func (s *state) setVar(name string, value reflect.Value) {
   66 	for i := s.mark() - 1; i >= 0; i-- {
   67 		if s.vars[i].name == name {
   68 			s.vars[i].value = value
   69 			return
   70 		}
   71 	}
   72 	s.errorf("undefined variable: %s", name)
   73 }
   74 
   75 // setTopVar overwrites the top-nth variable on the stack. Used by range iterations.
   76 func (s *state) setTopVar(n int, value reflect.Value) {
   77 	s.vars[len(s.vars)-n].value = value
   78 }
   79 
   80 // varValue returns the value of the named variable.
   81 func (s *state) varValue(name string) reflect.Value {
   82 	for i := s.mark() - 1; i >= 0; i-- {
   83 		if s.vars[i].name == name {
   84 			return s.vars[i].value
   85 		}
   86 	}
   87 	s.errorf("undefined variable: %s", name)
   88 	return zero
   89 }
   90 
   91 var zero reflect.Value
   92 
   93 type missingValType struct{}
   94 
   95 var missingVal = reflect.ValueOf(missingValType{})
   96 
   97 // at marks the state to be on node n, for error reporting.
   98 func (s *state) at(node parse.Node) {
   99 	s.node = node
  100 }
  101 
  102 // doublePercent returns the string with %'s replaced by %%, if necessary,
  103 // so it can be used safely inside a Printf format string.
  104 func doublePercent(str string) string {
  105 	return strings.ReplaceAll(str, "%", "%%")
  106 }
  107 
  108 // TODO: It would be nice if ExecError was more broken down, but
  109 // the way ErrorContext embeds the template name makes the
  110 // processing too clumsy.
  111 
  112 // ExecError is the custom error type returned when Execute has an
  113 // error evaluating its template. (If a write error occurs, the actual
  114 // error is returned; it will not be of type ExecError.)
  115 type ExecError struct {
  116 	Name string // Name of template.
  117 	Err  error  // Pre-formatted error.
  118 }
  119 
  120 func (e ExecError) Error() string {
  121 	return e.Err.Error()
  122 }
  123 
  124 func (e ExecError) Unwrap() error {
  125 	return e.Err
  126 }
  127 
  128 // errorf records an ExecError and terminates processing.
  129 func (s *state) errorf(format string, args ...any) {
  130 	name := doublePercent(s.tmpl.Name())
  131 	if s.node == nil {
  132 		format = fmt.Sprintf("template: %s: %s", name, format)
  133 	} else {
  134 		location, context := s.tmpl.ErrorContext(s.node)
  135 		format = fmt.Sprintf("template: %s: executing %q at <%s>: %s", location, name, doublePercent(context), format)
  136 	}
  137 	panic(ExecError{
  138 		Name: s.tmpl.Name(),
  139 		Err:  fmt.Errorf(format, args...),
  140 	})
  141 }
  142 
  143 // writeError is the wrapper type used internally when Execute has an
  144 // error writing to its output. We strip the wrapper in errRecover.
  145 // Note that this is not an implementation of error, so it cannot escape
  146 // from the package as an error value.
  147 type writeError struct {
  148 	Err error // Original error.
  149 }
  150 
  151 func (s *state) writeError(err error) {
  152 	panic(writeError{
  153 		Err: err,
  154 	})
  155 }
  156 
  157 // errRecover is the handler that turns panics into returns from the top
  158 // level of Parse.
  159 func errRecover(errp *error) {
  160 	e := recover()
  161 	if e != nil {
  162 		switch err := e.(type) {
  163 		case runtime.Error:
  164 			panic(e)
  165 		case writeError:
  166 			*errp = err.Err // Strip the wrapper.
  167 		case ExecError:
  168 			*errp = err // Keep the wrapper.
  169 		default:
  170 			panic(e)
  171 		}
  172 	}
  173 }
  174 
  175 // ExecuteTemplate applies the template associated with t that has the given name
  176 // to the specified data object and writes the output to wr.
  177 // If an error occurs executing the template or writing its output,
  178 // execution stops, but partial results may already have been written to
  179 // the output writer.
  180 // A template may be executed safely in parallel, although if parallel
  181 // executions share a Writer the output may be interleaved.
  182 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error {
  183 	tmpl := t.Lookup(name)
  184 	if tmpl == nil {
  185 		return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
  186 	}
  187 	return tmpl.Execute(wr, data)
  188 }
  189 
  190 // Execute applies a parsed template to the specified data object,
  191 // and writes the output to wr.
  192 // If an error occurs executing the template or writing its output,
  193 // execution stops, but partial results may already have been written to
  194 // the output writer.
  195 // A template may be executed safely in parallel, although if parallel
  196 // executions share a Writer the output may be interleaved.
  197 //
  198 // If data is a reflect.Value, the template applies to the concrete
  199 // value that the reflect.Value holds, as in fmt.Print.
  200 func (t *Template) Execute(wr io.Writer, data any) error {
  201 	return t.execute(wr, data)
  202 }
  203 
  204 func (t *Template) execute(wr io.Writer, data any) (err error) {
  205 	defer errRecover(&err)
  206 	value, ok := data.(reflect.Value)
  207 	if !ok {
  208 		value = reflect.ValueOf(data)
  209 	}
  210 	state := &state{
  211 		tmpl: t,
  212 		wr:   wr,
  213 		vars: []variable{{"$", value}},
  214 	}
  215 	if t.Tree == nil || t.Root == nil {
  216 		state.errorf("%q is an incomplete or empty template", t.Name())
  217 	}
  218 	state.walk(value, t.Root)
  219 	return
  220 }
  221 
  222 // DefinedTemplates returns a string listing the defined templates,
  223 // prefixed by the string "; defined templates are: ". If there are none,
  224 // it returns the empty string. For generating an error message here
  225 // and in html/template.
  226 func (t *Template) DefinedTemplates() string {
  227 	if t.common == nil {
  228 		return ""
  229 	}
  230 	var b strings.Builder
  231 	t.muTmpl.RLock()
  232 	defer t.muTmpl.RUnlock()
  233 	for name, tmpl := range t.tmpl {
  234 		if tmpl.Tree == nil || tmpl.Root == nil {
  235 			continue
  236 		}
  237 		if b.Len() == 0 {
  238 			b.WriteString("; defined templates are: ")
  239 		} else {
  240 			b.WriteString(", ")
  241 		}
  242 		fmt.Fprintf(&b, "%q", name)
  243 	}
  244 	return b.String()
  245 }
  246 
  247 // Sentinel errors for use with panic to signal early exits from range loops.
  248 var (
  249 	walkBreak    = errors.New("break")
  250 	walkContinue = errors.New("continue")
  251 )
  252 
  253 // Walk functions step through the major pieces of the template structure,
  254 // generating output as they go.
  255 func (s *state) walk(dot reflect.Value, node parse.Node) {
  256 	s.at(node)
  257 	switch node := node.(type) {
  258 	case *parse.ActionNode:
  259 		// Do not pop variables so they persist until next end.
  260 		// Also, if the action declares variables, don't print the result.
  261 		val := s.evalPipeline(dot, node.Pipe)
  262 		if len(node.Pipe.Decl) == 0 {
  263 			s.printValue(node, val)
  264 		}
  265 	case *parse.BreakNode:
  266 		panic(walkBreak)
  267 	case *parse.CommentNode:
  268 	case *parse.ContinueNode:
  269 		panic(walkContinue)
  270 	case *parse.IfNode:
  271 		s.walkIfOrWith(parse.NodeIf, dot, node.Pipe, node.List, node.ElseList)
  272 	case *parse.ListNode:
  273 		for _, node := range node.Nodes {
  274 			s.walk(dot, node)
  275 		}
  276 	case *parse.RangeNode:
  277 		s.walkRange(dot, node)
  278 	case *parse.TemplateNode:
  279 		s.walkTemplate(dot, node)
  280 	case *parse.TextNode:
  281 		if _, err := s.wr.Write(node.Text); err != nil {
  282 			s.writeError(err)
  283 		}
  284 	case *parse.WithNode:
  285 		s.walkIfOrWith(parse.NodeWith, dot, node.Pipe, node.List, node.ElseList)
  286 	default:
  287 		s.errorf("unknown node: %s", node)
  288 	}
  289 }
  290 
  291 // walkIfOrWith walks an 'if' or 'with' node. The two control structures
  292 // are identical in behavior except that 'with' sets dot.
  293 func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
  294 	defer s.pop(s.mark())
  295 	val := s.evalPipeline(dot, pipe)
  296 	truth, ok := isTrue(indirectInterface(val))
  297 	if !ok {
  298 		s.errorf("if/with can't use %v", val)
  299 	}
  300 	if truth {
  301 		if typ == parse.NodeWith {
  302 			s.walk(val, list)
  303 		} else {
  304 			s.walk(dot, list)
  305 		}
  306 	} else if elseList != nil {
  307 		s.walk(dot, elseList)
  308 	}
  309 }
  310 
  311 // IsTrue reports whether the value is 'true', in the sense of not the zero of its type,
  312 // and whether the value has a meaningful truth value. This is the definition of
  313 // truth used by if and other such actions.
  314 func IsTrue(val any) (truth, ok bool) {
  315 	return isTrue(reflect.ValueOf(val))
  316 }
  317 
  318 func isTrueOld(val reflect.Value) (truth, ok bool) {
  319 	if !val.IsValid() {
  320 		// Something like var x interface{}, never set. It's a form of nil.
  321 		return false, true
  322 	}
  323 	switch val.Kind() {
  324 	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
  325 		truth = val.Len() > 0
  326 	case reflect.Bool:
  327 		truth = val.Bool()
  328 	case reflect.Complex64, reflect.Complex128:
  329 		truth = val.Complex() != 0
  330 	case reflect.Chan, reflect.Func, reflect.Pointer, reflect.Interface:
  331 		truth = !val.IsNil()
  332 	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  333 		truth = val.Int() != 0
  334 	case reflect.Float32, reflect.Float64:
  335 		truth = val.Float() != 0
  336 	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  337 		truth = val.Uint() != 0
  338 	case reflect.Struct:
  339 		truth = true // Struct values are always true.
  340 	default:
  341 		return
  342 	}
  343 	return truth, true
  344 }
  345 
  346 func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
  347 	s.at(r)
  348 	defer func() {
  349 		if r := recover(); r != nil && r != walkBreak {
  350 			panic(r)
  351 		}
  352 	}()
  353 	defer s.pop(s.mark())
  354 	val, _ := indirect(s.evalPipeline(dot, r.Pipe))
  355 	// mark top of stack before any variables in the body are pushed.
  356 	mark := s.mark()
  357 	oneIteration := func(index, elem reflect.Value) {
  358 		// Set top var (lexically the second if there are two) to the element.
  359 		if len(r.Pipe.Decl) > 0 {
  360 			s.setTopVar(1, elem)
  361 		}
  362 		// Set next var (lexically the first if there are two) to the index.
  363 		if len(r.Pipe.Decl) > 1 {
  364 			s.setTopVar(2, index)
  365 		}
  366 		defer s.pop(mark)
  367 		defer func() {
  368 			// Consume panic(walkContinue)
  369 			if r := recover(); r != nil && r != walkContinue {
  370 				panic(r)
  371 			}
  372 		}()
  373 		s.walk(elem, r.List)
  374 	}
  375 	switch val.Kind() {
  376 	case reflect.Array, reflect.Slice:
  377 		if val.Len() == 0 {
  378 			break
  379 		}
  380 		for i := 0; i < val.Len(); i++ {
  381 			oneIteration(reflect.ValueOf(i), val.Index(i))
  382 		}
  383 		return
  384 	case reflect.Map:
  385 		if val.Len() == 0 {
  386 			break
  387 		}
  388 		om := fmtsort.Sort(val)
  389 		for i, key := range om.Key {
  390 			oneIteration(key, om.Value[i])
  391 		}
  392 		return
  393 	case reflect.Chan:
  394 		if val.IsNil() {
  395 			break
  396 		}
  397 		if val.Type().ChanDir() == reflect.SendDir {
  398 			s.errorf("range over send-only channel %v", val)
  399 			break
  400 		}
  401 		i := 0
  402 		for ; ; i++ {
  403 			elem, ok := val.Recv()
  404 			if !ok {
  405 				break
  406 			}
  407 			oneIteration(reflect.ValueOf(i), elem)
  408 		}
  409 		if i == 0 {
  410 			break
  411 		}
  412 		return
  413 	case reflect.Invalid:
  414 		break // An invalid value is likely a nil map, etc. and acts like an empty map.
  415 	default:
  416 		s.errorf("range can't iterate over %v", val)
  417 	}
  418 	if r.ElseList != nil {
  419 		s.walk(dot, r.ElseList)
  420 	}
  421 }
  422 
  423 func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
  424 	s.at(t)
  425 	tmpl := s.tmpl.Lookup(t.Name)
  426 	if tmpl == nil {
  427 		s.errorf("template %q not defined", t.Name)
  428 	}
  429 	if s.depth == maxExecDepth {
  430 		s.errorf("exceeded maximum template depth (%v)", maxExecDepth)
  431 	}
  432 	// Variables declared by the pipeline persist.
  433 	dot = s.evalPipeline(dot, t.Pipe)
  434 	newState := *s
  435 	newState.depth++
  436 	newState.tmpl = tmpl
  437 	// No dynamic scoping: template invocations inherit no variables.
  438 	newState.vars = []variable{{"$", dot}}
  439 	newState.walk(dot, tmpl.Root)
  440 }
  441 
  442 // Eval functions evaluate pipelines, commands, and their elements and extract
  443 // values from the data structure by examining fields, calling methods, and so on.
  444 // The printing of those values happens only through walk functions.
  445 
  446 // evalPipeline returns the value acquired by evaluating a pipeline. If the
  447 // pipeline has a variable declaration, the variable will be pushed on the
  448 // stack. Callers should therefore pop the stack after they are finished
  449 // executing commands depending on the pipeline value.
  450 func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
  451 	if pipe == nil {
  452 		return
  453 	}
  454 	s.at(pipe)
  455 	value = missingVal
  456 	for _, cmd := range pipe.Cmds {
  457 		value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
  458 		// If the object has type interface{}, dig down one level to the thing inside.
  459 		if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
  460 			value = reflect.ValueOf(value.Interface()) // lovely!
  461 		}
  462 	}
  463 	for _, variable := range pipe.Decl {
  464 		if pipe.IsAssign {
  465 			s.setVar(variable.Ident[0], value)
  466 		} else {
  467 			s.push(variable.Ident[0], value)
  468 		}
  469 	}
  470 	return value
  471 }
  472 
  473 func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
  474 	if len(args) > 1 || final != missingVal {
  475 		s.errorf("can't give argument to non-function %s", args[0])
  476 	}
  477 }
  478 
  479 func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
  480 	firstWord := cmd.Args[0]
  481 	switch n := firstWord.(type) {
  482 	case *parse.FieldNode:
  483 		return s.evalFieldNode(dot, n, cmd.Args, final)
  484 	case *parse.ChainNode:
  485 		return s.evalChainNode(dot, n, cmd.Args, final)
  486 	case *parse.IdentifierNode:
  487 		// Must be a function.
  488 		return s.evalFunction(dot, n, cmd, cmd.Args, final)
  489 	case *parse.PipeNode:
  490 		// Parenthesized pipeline. The arguments are all inside the pipeline; final must be absent.
  491 		s.notAFunction(cmd.Args, final)
  492 		return s.evalPipeline(dot, n)
  493 	case *parse.VariableNode:
  494 		return s.evalVariableNode(dot, n, cmd.Args, final)
  495 	}
  496 	s.at(firstWord)
  497 	s.notAFunction(cmd.Args, final)
  498 	switch word := firstWord.(type) {
  499 	case *parse.BoolNode:
  500 		return reflect.ValueOf(word.True)
  501 	case *parse.DotNode:
  502 		return dot
  503 	case *parse.NilNode:
  504 		s.errorf("nil is not a command")
  505 	case *parse.NumberNode:
  506 		return s.idealConstant(word)
  507 	case *parse.StringNode:
  508 		return reflect.ValueOf(word.Text)
  509 	}
  510 	s.errorf("can't evaluate command %q", firstWord)
  511 	panic("not reached")
  512 }
  513 
  514 // idealConstant is called to return the value of a number in a context where
  515 // we don't know the type. In that case, the syntax of the number tells us
  516 // its type, and we use Go rules to resolve. Note there is no such thing as
  517 // a uint ideal constant in this situation - the value must be of int type.
  518 func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
  519 	// These are ideal constants but we don't know the type
  520 	// and we have no context.  (If it was a method argument,
  521 	// we'd know what we need.) The syntax guides us to some extent.
  522 	s.at(constant)
  523 	switch {
  524 	case constant.IsComplex:
  525 		return reflect.ValueOf(constant.Complex128) // incontrovertible.
  526 
  527 	case constant.IsFloat &&
  528 		!isHexInt(constant.Text) && !isRuneInt(constant.Text) &&
  529 		strings.ContainsAny(constant.Text, ".eEpP"):
  530 		return reflect.ValueOf(constant.Float64)
  531 
  532 	case constant.IsInt:
  533 		n := int(constant.Int64)
  534 		if int64(n) != constant.Int64 {
  535 			s.errorf("%s overflows int", constant.Text)
  536 		}
  537 		return reflect.ValueOf(n)
  538 
  539 	case constant.IsUint:
  540 		s.errorf("%s overflows int", constant.Text)
  541 	}
  542 	return zero
  543 }
  544 
  545 func isRuneInt(s string) bool {
  546 	return len(s) > 0 && s[0] == '\''
  547 }
  548 
  549 func isHexInt(s string) bool {
  550 	return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') && !strings.ContainsAny(s, "pP")
  551 }
  552 
  553 func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
  554 	s.at(field)
  555 	return s.evalFieldChain(dot, dot, field, field.Ident, args, final)
  556 }
  557 
  558 func (s *state) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value {
  559 	s.at(chain)
  560 	if len(chain.Field) == 0 {
  561 		s.errorf("internal error: no fields in evalChainNode")
  562 	}
  563 	if chain.Node.Type() == parse.NodeNil {
  564 		s.errorf("indirection through explicit nil in %s", chain)
  565 	}
  566 	// (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields.
  567 	pipe := s.evalArg(dot, nil, chain.Node)
  568 	return s.evalFieldChain(dot, pipe, chain, chain.Field, args, final)
  569 }
  570 
  571 func (s *state) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
  572 	// $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
  573 	s.at(variable)
  574 	value := s.varValue(variable.Ident[0])
  575 	if len(variable.Ident) == 1 {
  576 		s.notAFunction(args, final)
  577 		return value
  578 	}
  579 	return s.evalFieldChain(dot, value, variable, variable.Ident[1:], args, final)
  580 }
  581 
  582 // evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
  583 // dot is the environment in which to evaluate arguments, while
  584 // receiver is the value being walked along the chain.
  585 func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
  586 	n := len(ident)
  587 	for i := 0; i < n-1; i++ {
  588 		receiver = s.evalField(dot, ident[i], node, nil, missingVal, receiver)
  589 	}
  590 	// Now if it's a method, it gets the arguments.
  591 	return s.evalField(dot, ident[n-1], node, args, final, receiver)
  592 }
  593 
  594 func (s *state) evalFunctionOld(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
  595 	s.at(node)
  596 	name := node.Ident
  597 	function, isBuiltin, ok := findFunction(name, s.tmpl)
  598 	if !ok {
  599 		s.errorf("%q is not a defined function", name)
  600 	}
  601 	return s.evalCall(dot, function, isBuiltin, cmd, name, args, final)
  602 }
  603 
  604 // evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
  605 // The 'final' argument represents the return value from the preceding
  606 // value of the pipeline, if any.
  607 func (s *state) evalFieldOld(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
  608 	if !receiver.IsValid() {
  609 		if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key.
  610 			s.errorf("nil data; no entry for key %q", fieldName)
  611 		}
  612 		return zero
  613 	}
  614 	typ := receiver.Type()
  615 	receiver, isNil := indirect(receiver)
  616 	if receiver.Kind() == reflect.Interface && isNil {
  617 		// Calling a method on a nil interface can't work. The
  618 		// MethodByName method call below would panic.
  619 		s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
  620 		return zero
  621 	}
  622 
  623 	// Unless it's an interface, need to get to a value of type *T to guarantee
  624 	// we see all methods of T and *T.
  625 	ptr := receiver
  626 	if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Pointer && ptr.CanAddr() {
  627 		ptr = ptr.Addr()
  628 	}
  629 	if method := ptr.MethodByName(fieldName); method.IsValid() {
  630 		return s.evalCall(dot, method, false, node, fieldName, args, final)
  631 	}
  632 	hasArgs := len(args) > 1 || final != missingVal
  633 	// It's not a method; must be a field of a struct or an element of a map.
  634 	switch receiver.Kind() {
  635 	case reflect.Struct:
  636 		tField, ok := receiver.Type().FieldByName(fieldName)
  637 		if ok {
  638 			field, err := receiver.FieldByIndexErr(tField.Index)
  639 			if !tField.IsExported() {
  640 				s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
  641 			}
  642 			if err != nil {
  643 				s.errorf("%v", err)
  644 			}
  645 			// If it's a function, we must call it.
  646 			if hasArgs {
  647 				s.errorf("%s has arguments but cannot be invoked as function", fieldName)
  648 			}
  649 			return field
  650 		}
  651 	case reflect.Map:
  652 		// If it's a map, attempt to use the field name as a key.
  653 		nameVal := reflect.ValueOf(fieldName)
  654 		if nameVal.Type().AssignableTo(receiver.Type().Key()) {
  655 			if hasArgs {
  656 				s.errorf("%s is not a method but has arguments", fieldName)
  657 			}
  658 			result := receiver.MapIndex(nameVal)
  659 			if !result.IsValid() {
  660 				switch s.tmpl.option.missingKey {
  661 				case mapInvalid:
  662 					// Just use the invalid value.
  663 				case mapZeroValue:
  664 					result = reflect.Zero(receiver.Type().Elem())
  665 				case mapError:
  666 					s.errorf("map has no entry for key %q", fieldName)
  667 				}
  668 			}
  669 			return result
  670 		}
  671 	case reflect.Pointer:
  672 		etyp := receiver.Type().Elem()
  673 		if etyp.Kind() == reflect.Struct {
  674 			if _, ok := etyp.FieldByName(fieldName); !ok {
  675 				// If there's no such field, say "can't evaluate"
  676 				// instead of "nil pointer evaluating".
  677 				break
  678 			}
  679 		}
  680 		if isNil {
  681 			s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
  682 		}
  683 	}
  684 	s.errorf("can't evaluate field %s in type %s", fieldName, typ)
  685 	panic("not reached")
  686 }
  687 
  688 var (
  689 	errorType        = reflect.TypeOf((*error)(nil)).Elem()
  690 	fmtStringerType  = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
  691 	reflectValueType = reflect.TypeOf((*reflect.Value)(nil)).Elem()
  692 )
  693 
  694 // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
  695 // it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
  696 // as the function itself.
  697 func (s *state) evalCallOld(dot, fun reflect.Value, isBuiltin bool, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value {
  698 	if args != nil {
  699 		args = args[1:] // Zeroth arg is function name/node; not passed to function.
  700 	}
  701 	typ := fun.Type()
  702 	numIn := len(args)
  703 	if final != missingVal {
  704 		numIn++
  705 	}
  706 	numFixed := len(args)
  707 	if typ.IsVariadic() {
  708 		numFixed = typ.NumIn() - 1 // last arg is the variadic one.
  709 		if numIn < numFixed {
  710 			s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
  711 		}
  712 	} else if numIn != typ.NumIn() {
  713 		s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), numIn)
  714 	}
  715 	if !goodFunc(typ) {
  716 		// TODO: This could still be a confusing error; maybe goodFunc should provide info.
  717 		s.errorf("can't call method/function %q with %d results", name, typ.NumOut())
  718 	}
  719 
  720 	unwrap := func(v reflect.Value) reflect.Value {
  721 		if v.Type() == reflectValueType {
  722 			v = v.Interface().(reflect.Value)
  723 		}
  724 		return v
  725 	}
  726 
  727 	// Special case for builtin and/or, which short-circuit.
  728 	if isBuiltin && (name == "and" || name == "or") {
  729 		argType := typ.In(0)
  730 		var v reflect.Value
  731 		for _, arg := range args {
  732 			v = s.evalArg(dot, argType, arg).Interface().(reflect.Value)
  733 			if truth(v) == (name == "or") {
  734 				// This value was already unwrapped
  735 				// by the .Interface().(reflect.Value).
  736 				return v
  737 			}
  738 		}
  739 		if final != missingVal {
  740 			// The last argument to and/or is coming from
  741 			// the pipeline. We didn't short circuit on an earlier
  742 			// argument, so we are going to return this one.
  743 			// We don't have to evaluate final, but we do
  744 			// have to check its type. Then, since we are
  745 			// going to return it, we have to unwrap it.
  746 			v = unwrap(s.validateType(final, argType))
  747 		}
  748 		return v
  749 	}
  750 
  751 	// Build the arg list.
  752 	argv := make([]reflect.Value, numIn)
  753 	// Args must be evaluated. Fixed args first.
  754 	i := 0
  755 	for ; i < numFixed && i < len(args); i++ {
  756 		argv[i] = s.evalArg(dot, typ.In(i), args[i])
  757 	}
  758 	// Now the ... args.
  759 	if typ.IsVariadic() {
  760 		argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
  761 		for ; i < len(args); i++ {
  762 			argv[i] = s.evalArg(dot, argType, args[i])
  763 		}
  764 	}
  765 	// Add final value if necessary.
  766 	if final != missingVal {
  767 		t := typ.In(typ.NumIn() - 1)
  768 		if typ.IsVariadic() {
  769 			if numIn-1 < numFixed {
  770 				// The added final argument corresponds to a fixed parameter of the function.
  771 				// Validate against the type of the actual parameter.
  772 				t = typ.In(numIn - 1)
  773 			} else {
  774 				// The added final argument corresponds to the variadic part.
  775 				// Validate against the type of the elements of the variadic slice.
  776 				t = t.Elem()
  777 			}
  778 		}
  779 		argv[i] = s.validateType(final, t)
  780 	}
  781 	v, err := safeCall(fun, argv)
  782 	// If we have an error that is not nil, stop execution and return that
  783 	// error to the caller.
  784 	if err != nil {
  785 		s.at(node)
  786 		s.errorf("error calling %s: %w", name, err)
  787 	}
  788 	return unwrap(v)
  789 }
  790 
  791 // canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero.
  792 func canBeNil(typ reflect.Type) bool {
  793 	switch typ.Kind() {
  794 	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
  795 		return true
  796 	case reflect.Struct:
  797 		return typ == reflectValueType
  798 	}
  799 	return false
  800 }
  801 
  802 // validateType guarantees that the value is valid and assignable to the type.
  803 func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
  804 	if !value.IsValid() {
  805 		if typ == nil {
  806 			// An untyped nil interface{}. Accept as a proper nil value.
  807 			return reflect.ValueOf(nil)
  808 		}
  809 		if canBeNil(typ) {
  810 			// Like above, but use the zero value of the non-nil type.
  811 			return reflect.Zero(typ)
  812 		}
  813 		s.errorf("invalid value; expected %s", typ)
  814 	}
  815 	if typ == reflectValueType && value.Type() != typ {
  816 		return reflect.ValueOf(value)
  817 	}
  818 	if typ != nil && !value.Type().AssignableTo(typ) {
  819 		if value.Kind() == reflect.Interface && !value.IsNil() {
  820 			value = value.Elem()
  821 			if value.Type().AssignableTo(typ) {
  822 				return value
  823 			}
  824 			// fallthrough
  825 		}
  826 		// Does one dereference or indirection work? We could do more, as we
  827 		// do with method receivers, but that gets messy and method receivers
  828 		// are much more constrained, so it makes more sense there than here.
  829 		// Besides, one is almost always all you need.
  830 		switch {
  831 		case value.Kind() == reflect.Pointer && value.Type().Elem().AssignableTo(typ):
  832 			value = value.Elem()
  833 			if !value.IsValid() {
  834 				s.errorf("dereference of nil pointer of type %s", typ)
  835 			}
  836 		case reflect.PointerTo(value.Type()).AssignableTo(typ) && value.CanAddr():
  837 			value = value.Addr()
  838 		default:
  839 			s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
  840 		}
  841 	}
  842 	return value
  843 }
  844 
  845 func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
  846 	s.at(n)
  847 	switch arg := n.(type) {
  848 	case *parse.DotNode:
  849 		return s.validateType(dot, typ)
  850 	case *parse.NilNode:
  851 		if canBeNil(typ) {
  852 			return reflect.Zero(typ)
  853 		}
  854 		s.errorf("cannot assign nil to %s", typ)
  855 	case *parse.FieldNode:
  856 		return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, missingVal), typ)
  857 	case *parse.VariableNode:
  858 		return s.validateType(s.evalVariableNode(dot, arg, nil, missingVal), typ)
  859 	case *parse.PipeNode:
  860 		return s.validateType(s.evalPipeline(dot, arg), typ)
  861 	case *parse.IdentifierNode:
  862 		return s.validateType(s.evalFunction(dot, arg, arg, nil, missingVal), typ)
  863 	case *parse.ChainNode:
  864 		return s.validateType(s.evalChainNode(dot, arg, nil, missingVal), typ)
  865 	}
  866 	switch typ.Kind() {
  867 	case reflect.Bool:
  868 		return s.evalBool(typ, n)
  869 	case reflect.Complex64, reflect.Complex128:
  870 		return s.evalComplex(typ, n)
  871 	case reflect.Float32, reflect.Float64:
  872 		return s.evalFloat(typ, n)
  873 	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  874 		return s.evalInteger(typ, n)
  875 	case reflect.Interface:
  876 		if typ.NumMethod() == 0 {
  877 			return s.evalEmptyInterface(dot, n)
  878 		}
  879 	case reflect.Struct:
  880 		if typ == reflectValueType {
  881 			return reflect.ValueOf(s.evalEmptyInterface(dot, n))
  882 		}
  883 	case reflect.String:
  884 		return s.evalString(typ, n)
  885 	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  886 		return s.evalUnsignedInteger(typ, n)
  887 	}
  888 	s.errorf("can't handle %s for arg of type %s", n, typ)
  889 	panic("not reached")
  890 }
  891 
  892 func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
  893 	s.at(n)
  894 	if n, ok := n.(*parse.BoolNode); ok {
  895 		value := reflect.New(typ).Elem()
  896 		value.SetBool(n.True)
  897 		return value
  898 	}
  899 	s.errorf("expected bool; found %s", n)
  900 	panic("not reached")
  901 }
  902 
  903 func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
  904 	s.at(n)
  905 	if n, ok := n.(*parse.StringNode); ok {
  906 		value := reflect.New(typ).Elem()
  907 		value.SetString(n.Text)
  908 		return value
  909 	}
  910 	s.errorf("expected string; found %s", n)
  911 	panic("not reached")
  912 }
  913 
  914 func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
  915 	s.at(n)
  916 	if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
  917 		value := reflect.New(typ).Elem()
  918 		value.SetInt(n.Int64)
  919 		return value
  920 	}
  921 	s.errorf("expected integer; found %s", n)
  922 	panic("not reached")
  923 }
  924 
  925 func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
  926 	s.at(n)
  927 	if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
  928 		value := reflect.New(typ).Elem()
  929 		value.SetUint(n.Uint64)
  930 		return value
  931 	}
  932 	s.errorf("expected unsigned integer; found %s", n)
  933 	panic("not reached")
  934 }
  935 
  936 func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
  937 	s.at(n)
  938 	if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
  939 		value := reflect.New(typ).Elem()
  940 		value.SetFloat(n.Float64)
  941 		return value
  942 	}
  943 	s.errorf("expected float; found %s", n)
  944 	panic("not reached")
  945 }
  946 
  947 func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
  948 	if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
  949 		value := reflect.New(typ).Elem()
  950 		value.SetComplex(n.Complex128)
  951 		return value
  952 	}
  953 	s.errorf("expected complex; found %s", n)
  954 	panic("not reached")
  955 }
  956 
  957 func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
  958 	s.at(n)
  959 	switch n := n.(type) {
  960 	case *parse.BoolNode:
  961 		return reflect.ValueOf(n.True)
  962 	case *parse.DotNode:
  963 		return dot
  964 	case *parse.FieldNode:
  965 		return s.evalFieldNode(dot, n, nil, missingVal)
  966 	case *parse.IdentifierNode:
  967 		return s.evalFunction(dot, n, n, nil, missingVal)
  968 	case *parse.NilNode:
  969 		// NilNode is handled in evalArg, the only place that calls here.
  970 		s.errorf("evalEmptyInterface: nil (can't happen)")
  971 	case *parse.NumberNode:
  972 		return s.idealConstant(n)
  973 	case *parse.StringNode:
  974 		return reflect.ValueOf(n.Text)
  975 	case *parse.VariableNode:
  976 		return s.evalVariableNode(dot, n, nil, missingVal)
  977 	case *parse.PipeNode:
  978 		return s.evalPipeline(dot, n)
  979 	}
  980 	s.errorf("can't handle assignment of %s to empty interface argument", n)
  981 	panic("not reached")
  982 }
  983 
  984 // indirect returns the item at the end of indirection, and a bool to indicate
  985 // if it's nil. If the returned bool is true, the returned value's kind will be
  986 // either a pointer or interface.
  987 func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
  988 	for ; v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface; v = v.Elem() {
  989 		if v.IsNil() {
  990 			return v, true
  991 		}
  992 	}
  993 	return v, false
  994 }
  995 
  996 // indirectInterface returns the concrete value in an interface value,
  997 // or else the zero reflect.Value.
  998 // That is, if v represents the interface value x, the result is the same as reflect.ValueOf(x):
  999 // the fact that x was an interface value is forgotten.
 1000 func indirectInterface(v reflect.Value) reflect.Value {
 1001 	if v.Kind() != reflect.Interface {
 1002 		return v
 1003 	}
 1004 	if v.IsNil() {
 1005 		return reflect.Value{}
 1006 	}
 1007 	return v.Elem()
 1008 }
 1009 
 1010 // printValue writes the textual representation of the value to the output of
 1011 // the template.
 1012 func (s *state) printValue(n parse.Node, v reflect.Value) {
 1013 	s.at(n)
 1014 	iface, ok := printableValue(v)
 1015 	if !ok {
 1016 		s.errorf("can't print %s of type %s", n, v.Type())
 1017 	}
 1018 	_, err := fmt.Fprint(s.wr, iface)
 1019 	if err != nil {
 1020 		s.writeError(err)
 1021 	}
 1022 }
 1023 
 1024 // printableValue returns the, possibly indirected, interface value inside v that
 1025 // is best for a call to formatted printer.
 1026 func printableValue(v reflect.Value) (any, bool) {
 1027 	if v.Kind() == reflect.Pointer {
 1028 		v, _ = indirect(v) // fmt.Fprint handles nil.
 1029 	}
 1030 	if !v.IsValid() {
 1031 		return "<no value>", true
 1032 	}
 1033 
 1034 	if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
 1035 		if v.CanAddr() && (reflect.PointerTo(v.Type()).Implements(errorType) || reflect.PointerTo(v.Type()).Implements(fmtStringerType)) {
 1036 			v = v.Addr()
 1037 		} else {
 1038 			switch v.Kind() {
 1039 			case reflect.Chan, reflect.Func:
 1040 				return nil, false
 1041 			}
 1042 		}
 1043 	}
 1044 	return v.Interface(), true
 1045 }