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