exec.go 29.9 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package template

import (
8
	"bytes"
9
	"fmt"
10
	"internal/fmtsort"
11 12
	"io"
	"reflect"
13
	"runtime"
14
	"sort"
15
	"strings"
16
	"text/template/parse"
17 18
)

19 20 21 22
// maxExecDepth specifies the maximum stack depth of templates within
// templates. This limit is only practically reached by accidentally
// recursive template invocations. This limit allows us to return
// an error instead of triggering a stack overflow.
23 24 25 26 27 28 29 30
var maxExecDepth = initMaxExecDepth()

func initMaxExecDepth() int {
	if runtime.GOARCH == "wasm" {
		return 1000
	}
	return 100000
}
31

32 33 34 35
// state represents the state of an execution. It's not part of the
// template so that multiple executions of the same template
// can execute in parallel.
type state struct {
36 37 38 39 40
	tmpl  *Template
	wr    io.Writer
	node  parse.Node // current node, for errors
	vars  []variable // push-down stack of variable values.
	depth int        // the height of the stack of executing templates.
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
}

// variable holds the dynamic value of a variable such as $, $x etc.
type variable struct {
	name  string
	value reflect.Value
}

// push pushes a new variable on the stack.
func (s *state) push(name string, value reflect.Value) {
	s.vars = append(s.vars, variable{name, value})
}

// mark returns the length of the variable stack.
func (s *state) mark() int {
	return len(s.vars)
}

// pop pops the variable stack up to the mark.
func (s *state) pop(mark int) {
	s.vars = s.vars[0:mark]
}

64 65 66 67 68 69 70 71 72 73 74 75 76 77
// setVar overwrites the last declared variable with the given name.
// Used by variable assignments.
func (s *state) setVar(name string, value reflect.Value) {
	for i := s.mark() - 1; i >= 0; i-- {
		if s.vars[i].name == name {
			s.vars[i].value = value
			return
		}
	}
	s.errorf("undefined variable: %s", name)
}

// setTopVar overwrites the top-nth variable on the stack. Used by range iterations.
func (s *state) setTopVar(n int, value reflect.Value) {
78
	s.vars[len(s.vars)-n].value = value
79 80
}

81 82
// varValue returns the value of the named variable.
func (s *state) varValue(name string) reflect.Value {
83 84 85 86 87 88 89
	for i := s.mark() - 1; i >= 0; i-- {
		if s.vars[i].name == name {
			return s.vars[i].value
		}
	}
	s.errorf("undefined variable: %s", name)
	return zero
90 91
}

92 93
var zero reflect.Value

94 95 96 97
type missingValType struct{}

var missingVal = reflect.ValueOf(missingValType{})

98 99 100 101 102 103 104 105
// at marks the state to be on node n, for error reporting.
func (s *state) at(node parse.Node) {
	s.node = node
}

// doublePercent returns the string with %'s replaced by %%, if necessary,
// so it can be used safely inside a Printf format string.
func doublePercent(str string) string {
106
	return strings.ReplaceAll(str, "%", "%%")
107 108
}

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
// TODO: It would be nice if ExecError was more broken down, but
// the way ErrorContext embeds the template name makes the
// processing too clumsy.

// ExecError is the custom error type returned when Execute has an
// error evaluating its template. (If a write error occurs, the actual
// error is returned; it will not be of type ExecError.)
type ExecError struct {
	Name string // Name of template.
	Err  error  // Pre-formatted error.
}

func (e ExecError) Error() string {
	return e.Err.Error()
}

// errorf records an ExecError and terminates processing.
126
func (s *state) errorf(format string, args ...interface{}) {
127 128 129 130 131 132 133
	name := doublePercent(s.tmpl.Name())
	if s.node == nil {
		format = fmt.Sprintf("template: %s: %s", name, format)
	} else {
		location, context := s.tmpl.ErrorContext(s.node)
		format = fmt.Sprintf("template: %s: executing %q at <%s>: %s", location, name, doublePercent(context), format)
	}
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
	panic(ExecError{
		Name: s.tmpl.Name(),
		Err:  fmt.Errorf(format, args...),
	})
}

// writeError is the wrapper type used internally when Execute has an
// error writing to its output. We strip the wrapper in errRecover.
// Note that this is not an implementation of error, so it cannot escape
// from the package as an error value.
type writeError struct {
	Err error // Original error.
}

func (s *state) writeError(err error) {
	panic(writeError{
		Err: err,
	})
152 153
}

154 155
// errRecover is the handler that turns panics into returns from the top
// level of Parse.
156
func errRecover(errp *error) {
157 158
	e := recover()
	if e != nil {
159 160 161
		switch err := e.(type) {
		case runtime.Error:
			panic(e)
162 163 164 165
		case writeError:
			*errp = err.Err // Strip the wrapper.
		case ExecError:
			*errp = err // Keep the wrapper.
166
		default:
167 168 169 170 171
			panic(e)
		}
	}
}

Rob Pike's avatar
Rob Pike committed
172 173
// ExecuteTemplate applies the template associated with t that has the given name
// to the specified data object and writes the output to wr.
174 175 176
// If an error occurs executing the template or writing its output,
// execution stops, but partial results may already have been written to
// the output writer.
177 178
// A template may be executed safely in parallel, although if parallel
// executions share a Writer the output may be interleaved.
Rob Pike's avatar
Rob Pike committed
179
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
180 181 182 183
	var tmpl *Template
	if t.common != nil {
		tmpl = t.tmpl[name]
	}
Rob Pike's avatar
Rob Pike committed
184 185 186 187 188 189
	if tmpl == nil {
		return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
	}
	return tmpl.Execute(wr, data)
}

190
// Execute applies a parsed template to the specified data object,
Rob Pike's avatar
Rob Pike committed
191
// and writes the output to wr.
192 193 194
// If an error occurs executing the template or writing its output,
// execution stops, but partial results may already have been written to
// the output writer.
195 196
// A template may be executed safely in parallel, although if parallel
// executions share a Writer the output may be interleaved.
197 198 199
//
// If data is a reflect.Value, the template applies to the concrete
// value that the reflect.Value holds, as in fmt.Print.
200 201 202 203 204
func (t *Template) Execute(wr io.Writer, data interface{}) error {
	return t.execute(wr, data)
}

func (t *Template) execute(wr io.Writer, data interface{}) (err error) {
205
	defer errRecover(&err)
206 207 208 209
	value, ok := data.(reflect.Value)
	if !ok {
		value = reflect.ValueOf(data)
	}
210 211 212
	state := &state{
		tmpl: t,
		wr:   wr,
213
		vars: []variable{{"$", value}},
214
	}
215
	if t.Tree == nil || t.Root == nil {
216
		state.errorf("%q is an incomplete or empty template", t.Name())
217 218 219 220 221 222
	}
	state.walk(value, t.Root)
	return
}

// DefinedTemplates returns a string listing the defined templates,
223
// prefixed by the string "; defined templates are: ". If there are none,
224 225 226
// it returns the empty string. For generating an error message here
// and in html/template.
func (t *Template) DefinedTemplates() string {
227 228 229
	if t.common == nil {
		return ""
	}
230 231 232 233
	var b bytes.Buffer
	for name, tmpl := range t.tmpl {
		if tmpl.Tree == nil || tmpl.Root == nil {
			continue
234 235
		}
		if b.Len() > 0 {
236
			b.WriteString(", ")
237
		}
238
		fmt.Fprintf(&b, "%q", name)
239
	}
240 241 242 243 244
	var s string
	if b.Len() > 0 {
		s = "; defined templates are: " + b.String()
	}
	return s
245 246 247 248
}

// Walk functions step through the major pieces of the template structure,
// generating output as they go.
249
func (s *state) walk(dot reflect.Value, node parse.Node) {
250 251
	s.at(node)
	switch node := node.(type) {
252
	case *parse.ActionNode:
253
		// Do not pop variables so they persist until next end.
254
		// Also, if the action declares variables, don't print the result.
255
		val := s.evalPipeline(dot, node.Pipe)
256
		if len(node.Pipe.Decl) == 0 {
257
			s.printValue(node, val)
258
		}
259
	case *parse.IfNode:
260
		s.walkIfOrWith(parse.NodeIf, dot, node.Pipe, node.List, node.ElseList)
261
	case *parse.ListNode:
262
		for _, node := range node.Nodes {
263
			s.walk(dot, node)
264
		}
265
	case *parse.RangeNode:
266
		s.walkRange(dot, node)
267
	case *parse.TemplateNode:
268
		s.walkTemplate(dot, node)
269
	case *parse.TextNode:
270
		if _, err := s.wr.Write(node.Text); err != nil {
271
			s.writeError(err)
272
		}
273
	case *parse.WithNode:
274
		s.walkIfOrWith(parse.NodeWith, dot, node.Pipe, node.List, node.ElseList)
275
	default:
276
		s.errorf("unknown node: %s", node)
277 278 279
	}
}

280 281
// walkIfOrWith walks an 'if' or 'with' node. The two control structures
// are identical in behavior except that 'with' sets dot.
282
func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
283
	defer s.pop(s.mark())
284
	val := s.evalPipeline(dot, pipe)
285
	truth, ok := isTrue(val)
286
	if !ok {
287
		s.errorf("if/with can't use %v", val)
288 289
	}
	if truth {
290
		if typ == parse.NodeWith {
291
			s.walk(val, list)
292
		} else {
293
			s.walk(dot, list)
294 295
		}
	} else if elseList != nil {
296
		s.walk(dot, elseList)
297 298 299
	}
}

Rob Pike's avatar
Rob Pike committed
300 301 302
// IsTrue reports whether the value is 'true', in the sense of not the zero of its type,
// and whether the value has a meaningful truth value. This is the definition of
// truth used by if and other such actions.
303 304 305 306 307
func IsTrue(val interface{}) (truth, ok bool) {
	return isTrue(reflect.ValueOf(val))
}

func isTrue(val reflect.Value) (truth, ok bool) {
308 309 310 311
	if !val.IsValid() {
		// Something like var x interface{}, never set. It's a form of nil.
		return false, true
	}
312 313 314 315 316 317 318
	switch val.Kind() {
	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
		truth = val.Len() > 0
	case reflect.Bool:
		truth = val.Bool()
	case reflect.Complex64, reflect.Complex128:
		truth = val.Complex() != 0
319
	case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
320
		truth = !val.IsNil()
321 322 323 324 325 326
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		truth = val.Int() != 0
	case reflect.Float32, reflect.Float64:
		truth = val.Float() != 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		truth = val.Uint() != 0
327 328
	case reflect.Struct:
		truth = true // Struct values are always true.
329
	default:
330
		return
331
	}
332
	return truth, true
333 334
}

335
func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
336
	s.at(r)
337
	defer s.pop(s.mark())
338
	val, _ := indirect(s.evalPipeline(dot, r.Pipe))
339 340
	// mark top of stack before any variables in the body are pushed.
	mark := s.mark()
341
	oneIteration := func(index, elem reflect.Value) {
Rob Pike's avatar
Rob Pike committed
342
		// Set top var (lexically the second if there are two) to the element.
343
		if len(r.Pipe.Decl) > 0 {
344
			s.setTopVar(1, elem)
Rob Pike's avatar
Rob Pike committed
345 346
		}
		// Set next var (lexically the first if there are two) to the index.
347
		if len(r.Pipe.Decl) > 1 {
348
			s.setTopVar(2, index)
Rob Pike's avatar
Rob Pike committed
349
		}
350
		s.walk(elem, r.List)
Rob Pike's avatar
Rob Pike committed
351 352
		s.pop(mark)
	}
353 354 355 356 357 358
	switch val.Kind() {
	case reflect.Array, reflect.Slice:
		if val.Len() == 0 {
			break
		}
		for i := 0; i < val.Len(); i++ {
359
			oneIteration(reflect.ValueOf(i), val.Index(i))
360
		}
361
		return
362 363 364 365
	case reflect.Map:
		if val.Len() == 0 {
			break
		}
366 367 368
		om := fmtsort.Sort(val)
		for i, key := range om.Key {
			oneIteration(key, om.Value[i])
Rob Pike's avatar
Rob Pike committed
369
		}
370
		return
Rob Pike's avatar
Rob Pike committed
371 372 373 374 375 376 377 378 379
	case reflect.Chan:
		if val.IsNil() {
			break
		}
		i := 0
		for ; ; i++ {
			elem, ok := val.Recv()
			if !ok {
				break
380
			}
381
			oneIteration(reflect.ValueOf(i), elem)
Rob Pike's avatar
Rob Pike committed
382 383 384
		}
		if i == 0 {
			break
385
		}
386
		return
387 388
	case reflect.Invalid:
		break // An invalid value is likely a nil map, etc. and acts like an empty map.
389
	default:
390
		s.errorf("range can't iterate over %v", val)
391
	}
392
	if r.ElseList != nil {
393
		s.walk(dot, r.ElseList)
394 395 396
	}
}

397
func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
398
	s.at(t)
Rob Pike's avatar
Rob Pike committed
399
	tmpl := s.tmpl.tmpl[t.Name]
400
	if tmpl == nil {
Rob Pike's avatar
Rob Pike committed
401
		s.errorf("template %q not defined", t.Name)
402
	}
403 404 405
	if s.depth == maxExecDepth {
		s.errorf("exceeded maximum template depth (%v)", maxExecDepth)
	}
406
	// Variables declared by the pipeline persist.
407
	dot = s.evalPipeline(dot, t.Pipe)
408
	newState := *s
409
	newState.depth++
410
	newState.tmpl = tmpl
411
	// No dynamic scoping: template invocations inherit no variables.
412
	newState.vars = []variable{{"$", dot}}
413
	newState.walk(dot, tmpl.Root)
414 415
}

416 417 418 419
// Eval functions evaluate pipelines, commands, and their elements and extract
// values from the data structure by examining fields, calling methods, and so on.
// The printing of those values happens only through walk functions.

420 421 422 423
// evalPipeline returns the value acquired by evaluating a pipeline. If the
// pipeline has a variable declaration, the variable will be pushed on the
// stack. Callers should therefore pop the stack after they are finished
// executing commands depending on the pipeline value.
424
func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
425 426 427
	if pipe == nil {
		return
	}
428
	s.at(pipe)
429
	value = missingVal
430
	for _, cmd := range pipe.Cmds {
431
		value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
432 433 434 435
		// If the object has type interface{}, dig down one level to the thing inside.
		if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
			value = reflect.ValueOf(value.Interface()) // lovely!
		}
436
	}
437 438
	for _, variable := range pipe.Decl {
		if pipe.IsAssign {
439
			s.setVar(variable.Ident[0], value)
440 441
		} else {
			s.push(variable.Ident[0], value)
442
		}
443
	}
444 445 446
	return value
}

447
func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
448
	if len(args) > 1 || final != missingVal {
449 450 451 452
		s.errorf("can't give argument to non-function %s", args[0])
	}
}

453 454
func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
	firstWord := cmd.Args[0]
Rob Pike's avatar
Rob Pike committed
455
	switch n := firstWord.(type) {
456 457
	case *parse.FieldNode:
		return s.evalFieldNode(dot, n, cmd.Args, final)
458 459
	case *parse.ChainNode:
		return s.evalChainNode(dot, n, cmd.Args, final)
460
	case *parse.IdentifierNode:
461
		// Must be a function.
462
		return s.evalFunction(dot, n, cmd, cmd.Args, final)
463 464 465
	case *parse.PipeNode:
		// Parenthesized pipeline. The arguments are all inside the pipeline; final is ignored.
		return s.evalPipeline(dot, n)
466
	case *parse.VariableNode:
467
		return s.evalVariableNode(dot, n, cmd.Args, final)
468
	}
469
	s.at(firstWord)
470
	s.notAFunction(cmd.Args, final)
471
	switch word := firstWord.(type) {
472 473 474
	case *parse.BoolNode:
		return reflect.ValueOf(word.True)
	case *parse.DotNode:
475
		return dot
476 477
	case *parse.NilNode:
		s.errorf("nil is not a command")
478
	case *parse.NumberNode:
479
		return s.idealConstant(word)
480 481
	case *parse.StringNode:
		return reflect.ValueOf(word.Text)
482
	}
483
	s.errorf("can't evaluate command %q", firstWord)
484 485 486
	panic("not reached")
}

487 488
// idealConstant is called to return the value of a number in a context where
// we don't know the type. In that case, the syntax of the number tells us
489
// its type, and we use Go rules to resolve. Note there is no such thing as
490
// a uint ideal constant in this situation - the value must be of int type.
491
func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
492 493 494
	// These are ideal constants but we don't know the type
	// and we have no context.  (If it was a method argument,
	// we'd know what we need.) The syntax guides us to some extent.
495
	s.at(constant)
496
	switch {
497 498
	case constant.IsComplex:
		return reflect.ValueOf(constant.Complex128) // incontrovertible.
499
	case constant.IsFloat && !isHexConstant(constant.Text) && strings.ContainsAny(constant.Text, ".eE"):
500 501 502 503 504
		return reflect.ValueOf(constant.Float64)
	case constant.IsInt:
		n := int(constant.Int64)
		if int64(n) != constant.Int64 {
			s.errorf("%s overflows int", constant.Text)
505 506
		}
		return reflect.ValueOf(n)
507 508
	case constant.IsUint:
		s.errorf("%s overflows int", constant.Text)
509 510 511 512
	}
	return zero
}

513 514 515 516
func isHexConstant(s string) bool {
	return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')
}

517
func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
518 519
	s.at(field)
	return s.evalFieldChain(dot, dot, field, field.Ident, args, final)
520 521
}

522
func (s *state) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value {
523
	s.at(chain)
524 525 526
	if len(chain.Field) == 0 {
		s.errorf("internal error: no fields in evalChainNode")
	}
527 528 529 530 531
	if chain.Node.Type() == parse.NodeNil {
		s.errorf("indirection through explicit nil in %s", chain)
	}
	// (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields.
	pipe := s.evalArg(dot, nil, chain.Node)
532
	return s.evalFieldChain(dot, pipe, chain, chain.Field, args, final)
533 534
}

535
func (s *state) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
536
	// $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
537 538 539
	s.at(variable)
	value := s.varValue(variable.Ident[0])
	if len(variable.Ident) == 1 {
540
		s.notAFunction(args, final)
541
		return value
542
	}
543
	return s.evalFieldChain(dot, value, variable, variable.Ident[1:], args, final)
544 545
}

546 547 548
// evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
// dot is the environment in which to evaluate arguments, while
// receiver is the value being walked along the chain.
549
func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
550
	n := len(ident)
551
	for i := 0; i < n-1; i++ {
552
		receiver = s.evalField(dot, ident[i], node, nil, missingVal, receiver)
553
	}
554
	// Now if it's a method, it gets the arguments.
555
	return s.evalField(dot, ident[n-1], node, args, final, receiver)
556 557
}

558 559 560
func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
	s.at(node)
	name := node.Ident
Rob Pike's avatar
Rob Pike committed
561
	function, ok := findFunction(name, s.tmpl)
562 563 564
	if !ok {
		s.errorf("%q is not a defined function", name)
	}
565
	return s.evalCall(dot, function, cmd, name, args, final)
566 567
}

568 569 570
// evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
// The 'final' argument represents the return value from the preceding
// value of the pipeline, if any.
571
func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
572
	if !receiver.IsValid() {
573 574 575
		if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key.
			s.errorf("nil data; no entry for key %q", fieldName)
		}
576 577 578
		return zero
	}
	typ := receiver.Type()
579
	receiver, isNil := indirect(receiver)
580 581
	// Unless it's an interface, need to get to a value of type *T to guarantee
	// we see all methods of T and *T.
582
	ptr := receiver
583
	if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Ptr && ptr.CanAddr() {
584 585
		ptr = ptr.Addr()
	}
Rob Pike's avatar
Rob Pike committed
586
	if method := ptr.MethodByName(fieldName); method.IsValid() {
587
		return s.evalCall(dot, method, node, fieldName, args, final)
588
	}
589
	hasArgs := len(args) > 1 || final != missingVal
590
	// It's not a method; must be a field of a struct or an element of a map.
591 592
	switch receiver.Kind() {
	case reflect.Struct:
593 594
		tField, ok := receiver.Type().FieldByName(fieldName)
		if ok {
595 596 597
			if isNil {
				s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
			}
598
			field := receiver.FieldByIndex(tField.Index)
599 600
			if tField.PkgPath != "" { // field is unexported
				s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
601
			}
602 603 604 605 606
			// If it's a function, we must call it.
			if hasArgs {
				s.errorf("%s has arguments but cannot be invoked as function", fieldName)
			}
			return field
607
		}
608
	case reflect.Map:
609 610 611
		if isNil {
			s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
		}
612
		// If it's a map, attempt to use the field name as a key.
613 614 615 616 617
		nameVal := reflect.ValueOf(fieldName)
		if nameVal.Type().AssignableTo(receiver.Type().Key()) {
			if hasArgs {
				s.errorf("%s is not a method but has arguments", fieldName)
			}
618 619 620 621 622 623 624 625 626 627 628 629
			result := receiver.MapIndex(nameVal)
			if !result.IsValid() {
				switch s.tmpl.option.missingKey {
				case mapInvalid:
					// Just use the invalid value.
				case mapZeroValue:
					result = reflect.Zero(receiver.Type().Elem())
				case mapError:
					s.errorf("map has no entry for key %q", fieldName)
				}
			}
			return result
630 631
		}
	}
632
	s.errorf("can't evaluate field %s in type %s", fieldName, typ)
633 634 635 636
	panic("not reached")
}

var (
637 638 639
	errorType        = reflect.TypeOf((*error)(nil)).Elem()
	fmtStringerType  = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
	reflectValueType = reflect.TypeOf((*reflect.Value)(nil)).Elem()
640 641
)

642
// evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
643
// it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
644
// as the function itself.
645
func (s *state) evalCall(dot, fun reflect.Value, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value {
646 647
	if args != nil {
		args = args[1:] // Zeroth arg is function name/node; not passed to function.
Rob Pike's avatar
Rob Pike committed
648
	}
649
	typ := fun.Type()
650
	numIn := len(args)
651
	if final != missingVal {
652 653
		numIn++
	}
Rob Pike's avatar
Rob Pike committed
654 655 656 657 658 659
	numFixed := len(args)
	if typ.IsVariadic() {
		numFixed = typ.NumIn() - 1 // last arg is the variadic one.
		if numIn < numFixed {
			s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
		}
660
	} else if numIn != typ.NumIn() {
661
		s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), numIn)
662
	}
Rob Pike's avatar
Rob Pike committed
663
	if !goodFunc(typ) {
664 665
		// TODO: This could still be a confusing error; maybe goodFunc should provide info.
		s.errorf("can't call method/function %q with %d results", name, typ.NumOut())
666 667 668
	}
	// Build the arg list.
	argv := make([]reflect.Value, numIn)
669
	// Args must be evaluated. Fixed args first.
Rob Pike's avatar
Rob Pike committed
670
	i := 0
671
	for ; i < numFixed && i < len(args); i++ {
672
		argv[i] = s.evalArg(dot, typ.In(i), args[i])
673
	}
674
	// Now the ... args.
Rob Pike's avatar
Rob Pike committed
675 676 677
	if typ.IsVariadic() {
		argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
		for ; i < len(args); i++ {
678
			argv[i] = s.evalArg(dot, argType, args[i])
Rob Pike's avatar
Rob Pike committed
679 680
		}
	}
681
	// Add final value if necessary.
682
	if final != missingVal {
683 684
		t := typ.In(typ.NumIn() - 1)
		if typ.IsVariadic() {
685 686 687 688 689 690 691 692 693
			if numIn-1 < numFixed {
				// The added final argument corresponds to a fixed parameter of the function.
				// Validate against the type of the actual parameter.
				t = typ.In(numIn - 1)
			} else {
				// The added final argument corresponds to the variadic part.
				// Validate against the type of the elements of the variadic slice.
				t = t.Elem()
			}
694 695
		}
		argv[i] = s.validateType(final, t)
696 697
	}
	result := fun.Call(argv)
698
	// If we have an error that is not nil, stop execution and return that error to the caller.
699
	if len(result) == 2 && !result[1].IsNil() {
700
		s.at(node)
701
		s.errorf("error calling %s: %s", name, result[1].Interface().(error))
702
	}
703 704 705 706 707
	v := result[0]
	if v.Type() == reflectValueType {
		v = v.Interface().(reflect.Value)
	}
	return v
708 709
}

710 711 712 713 714
// canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero.
func canBeNil(typ reflect.Type) bool {
	switch typ.Kind() {
	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
		return true
715 716
	case reflect.Struct:
		return typ == reflectValueType
717 718 719 720
	}
	return false
}

721
// validateType guarantees that the value is valid and assignable to the type.
722
func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
723
	if !value.IsValid() {
724
		if typ == nil {
725
			// An untyped nil interface{}. Accept as a proper nil value.
726 727 728 729
			return reflect.ValueOf(nil)
		}
		if canBeNil(typ) {
			// Like above, but use the zero value of the non-nil type.
730
			return reflect.Zero(typ)
731
		}
732
		s.errorf("invalid value; expected %s", typ)
733
	}
734 735 736
	if typ == reflectValueType && value.Type() != typ {
		return reflect.ValueOf(value)
	}
737
	if typ != nil && !value.Type().AssignableTo(typ) {
738 739 740 741 742 743 744
		if value.Kind() == reflect.Interface && !value.IsNil() {
			value = value.Elem()
			if value.Type().AssignableTo(typ) {
				return value
			}
			// fallthrough
		}
745 746 747 748 749
		// Does one dereference or indirection work? We could do more, as we
		// do with method receivers, but that gets messy and method receivers
		// are much more constrained, so it makes more sense there than here.
		// Besides, one is almost always all you need.
		switch {
750
		case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
751
			value = value.Elem()
752 753 754
			if !value.IsValid() {
				s.errorf("dereference of nil pointer of type %s", typ)
			}
755 756 757 758 759
		case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
			value = value.Addr()
		default:
			s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
		}
760 761 762 763
	}
	return value
}

764
func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
765
	s.at(n)
766
	switch arg := n.(type) {
767
	case *parse.DotNode:
768
		return s.validateType(dot, typ)
769 770 771 772 773
	case *parse.NilNode:
		if canBeNil(typ) {
			return reflect.Zero(typ)
		}
		s.errorf("cannot assign nil to %s", typ)
774
	case *parse.FieldNode:
775
		return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, missingVal), typ)
776
	case *parse.VariableNode:
777
		return s.validateType(s.evalVariableNode(dot, arg, nil, missingVal), typ)
778 779
	case *parse.PipeNode:
		return s.validateType(s.evalPipeline(dot, arg), typ)
780
	case *parse.IdentifierNode:
781
		return s.validateType(s.evalFunction(dot, arg, arg, nil, missingVal), typ)
782
	case *parse.ChainNode:
783
		return s.validateType(s.evalChainNode(dot, arg, nil, missingVal), typ)
784 785
	}
	switch typ.Kind() {
Rob Pike's avatar
Rob Pike committed
786
	case reflect.Bool:
Rob Pike's avatar
Rob Pike committed
787
		return s.evalBool(typ, n)
788
	case reflect.Complex64, reflect.Complex128:
Rob Pike's avatar
Rob Pike committed
789
		return s.evalComplex(typ, n)
790 791 792 793
	case reflect.Float32, reflect.Float64:
		return s.evalFloat(typ, n)
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return s.evalInteger(typ, n)
Rob Pike's avatar
Rob Pike committed
794 795
	case reflect.Interface:
		if typ.NumMethod() == 0 {
796
			return s.evalEmptyInterface(dot, n)
Rob Pike's avatar
Rob Pike committed
797
		}
798 799 800 801
	case reflect.Struct:
		if typ == reflectValueType {
			return reflect.ValueOf(s.evalEmptyInterface(dot, n))
		}
802 803 804 805
	case reflect.String:
		return s.evalString(typ, n)
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return s.evalUnsignedInteger(typ, n)
806
	}
Rob Pike's avatar
Rob Pike committed
807
	s.errorf("can't handle %s for arg of type %s", n, typ)
808 809 810
	panic("not reached")
}

811
func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
812
	s.at(n)
813
	if n, ok := n.(*parse.BoolNode); ok {
Rob Pike's avatar
Rob Pike committed
814
		value := reflect.New(typ).Elem()
815
		value.SetBool(n.True)
Rob Pike's avatar
Rob Pike committed
816 817 818 819 820 821
		return value
	}
	s.errorf("expected bool; found %s", n)
	panic("not reached")
}

822
func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
823
	s.at(n)
824
	if n, ok := n.(*parse.StringNode); ok {
825
		value := reflect.New(typ).Elem()
826
		value.SetString(n.Text)
827 828 829 830 831 832
		return value
	}
	s.errorf("expected string; found %s", n)
	panic("not reached")
}

833
func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
834
	s.at(n)
835
	if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
836
		value := reflect.New(typ).Elem()
837
		value.SetInt(n.Int64)
838 839 840 841 842 843
		return value
	}
	s.errorf("expected integer; found %s", n)
	panic("not reached")
}

844
func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
845
	s.at(n)
846
	if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
847
		value := reflect.New(typ).Elem()
848
		value.SetUint(n.Uint64)
849 850 851 852 853 854
		return value
	}
	s.errorf("expected unsigned integer; found %s", n)
	panic("not reached")
}

855
func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
856
	s.at(n)
857
	if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
858
		value := reflect.New(typ).Elem()
859
		value.SetFloat(n.Float64)
860 861 862 863 864 865
		return value
	}
	s.errorf("expected float; found %s", n)
	panic("not reached")
}

866 867
func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
	if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
868
		value := reflect.New(typ).Elem()
869
		value.SetComplex(n.Complex128)
870 871 872 873 874 875
		return value
	}
	s.errorf("expected complex; found %s", n)
	panic("not reached")
}

876
func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
877
	s.at(n)
Rob Pike's avatar
Rob Pike committed
878
	switch n := n.(type) {
879 880 881
	case *parse.BoolNode:
		return reflect.ValueOf(n.True)
	case *parse.DotNode:
882
		return dot
883
	case *parse.FieldNode:
884
		return s.evalFieldNode(dot, n, nil, missingVal)
885
	case *parse.IdentifierNode:
886
		return s.evalFunction(dot, n, n, nil, missingVal)
887 888 889
	case *parse.NilNode:
		// NilNode is handled in evalArg, the only place that calls here.
		s.errorf("evalEmptyInterface: nil (can't happen)")
890
	case *parse.NumberNode:
891
		return s.idealConstant(n)
892 893
	case *parse.StringNode:
		return reflect.ValueOf(n.Text)
894
	case *parse.VariableNode:
895
		return s.evalVariableNode(dot, n, nil, missingVal)
896 897
	case *parse.PipeNode:
		return s.evalPipeline(dot, n)
Rob Pike's avatar
Rob Pike committed
898 899 900 901 902
	}
	s.errorf("can't handle assignment of %s to empty interface argument", n)
	panic("not reached")
}

903 904
// indirect returns the item at the end of indirection, and a bool to indicate if it's nil.
func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
905
	for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
906 907 908 909 910 911 912
		if v.IsNil() {
			return v, true
		}
	}
	return v, false
}

913 914 915 916 917 918 919 920 921 922 923 924 925 926
// indirectInterface returns the concrete value in an interface value,
// or else the zero reflect.Value.
// That is, if v represents the interface value x, the result is the same as reflect.ValueOf(x):
// the fact that x was an interface value is forgotten.
func indirectInterface(v reflect.Value) reflect.Value {
	if v.Kind() != reflect.Interface {
		return v
	}
	if v.IsNil() {
		return reflect.Value{}
	}
	return v.Elem()
}

927 928
// printValue writes the textual representation of the value to the output of
// the template.
929
func (s *state) printValue(n parse.Node, v reflect.Value) {
930
	s.at(n)
931 932 933 934
	iface, ok := printableValue(v)
	if !ok {
		s.errorf("can't print %s of type %s", n, v.Type())
	}
935 936 937 938
	_, err := fmt.Fprint(s.wr, iface)
	if err != nil {
		s.writeError(err)
	}
939 940 941 942 943
}

// printableValue returns the, possibly indirected, interface value inside v that
// is best for a call to formatted printer.
func printableValue(v reflect.Value) (interface{}, bool) {
944 945 946
	if v.Kind() == reflect.Ptr {
		v, _ = indirect(v) // fmt.Fprint handles nil.
	}
947
	if !v.IsValid() {
948
		return "<no value>", true
949
	}
950

Russ Cox's avatar
Russ Cox committed
951
	if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
952
		if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
953 954 955 956
			v = v.Addr()
		} else {
			switch v.Kind() {
			case reflect.Chan, reflect.Func:
957
				return nil, false
958 959
			}
		}
960
	}
961
	return v.Interface(), true
962
}
963 964 965 966 967 968 969 970

// sortKeys sorts (if it can) the slice of reflect.Values, which is a slice of map keys.
func sortKeys(v []reflect.Value) []reflect.Value {
	if len(v) <= 1 {
		return v
	}
	switch v[0].Kind() {
	case reflect.Float32, reflect.Float64:
971 972 973
		sort.Slice(v, func(i, j int) bool {
			return v[i].Float() < v[j].Float()
		})
974
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
975 976 977
		sort.Slice(v, func(i, j int) bool {
			return v[i].Int() < v[j].Int()
		})
978
	case reflect.String:
979 980 981
		sort.Slice(v, func(i, j int) bool {
			return v[i].String() < v[j].String()
		})
982
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
983 984 985
		sort.Slice(v, func(i, j int) bool {
			return v[i].Uint() < v[j].Uint()
		})
986 987 988
	}
	return v
}