Black Lives Matter. Support the Equal Justice Initiative.

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

View as plain text