...
Run Format

Source file src/text/template/exec.go

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

View as plain text