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