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