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

View as plain text