Black Lives Matter. Support the Equal Justice Initiative.

Source file src/text/template/exec.go

Documentation: text/template

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

View as plain text