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