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

View as plain text