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