Source file src/text/template/exec.go

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

View as plain text