...
Run Format

Source file src/text/template/exec.go

Documentation: text/template

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

View as plain text