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

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