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