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

View as plain text