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