"README.rst" did not exist on "6d37f216bcd1982dfe1fc67ff9df9c9cfcf30f18"
exec.go 22.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// 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 (
	"fmt"
	"io"
	"reflect"
11
	"runtime"
12
	"sort"
13
	"strings"
14
	"text/template/parse"
15 16 17 18 19 20 21 22
)

// 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 {
	tmpl *Template
	wr   io.Writer
Rob Pike's avatar
Rob Pike committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
	line int        // line number for errors
	vars []variable // push-down stack of variable values.
}

// 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]
}

48 49 50
// setVar overwrites the top-nth variable on the stack. Used by range iterations.
func (s *state) setVar(n int, value reflect.Value) {
	s.vars[len(s.vars)-n].value = value
Rob Pike's avatar
Rob Pike committed
51 52
}

53 54
// varValue returns the value of the named variable.
func (s *state) varValue(name string) reflect.Value {
Rob Pike's avatar
Rob Pike committed
55 56 57 58 59 60 61
	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
62 63
}

64 65
var zero reflect.Value

66 67
// errorf formats the error and terminates processing.
func (s *state) errorf(format string, args ...interface{}) {
68
	format = fmt.Sprintf("template: %s:%d: %s", s.tmpl.Name(), s.line, format)
69 70 71 72
	panic(fmt.Errorf(format, args...))
}

// error terminates processing.
73
func (s *state) error(err error) {
74 75 76
	s.errorf("%s", err)
}

77 78
// errRecover is the handler that turns panics into returns from the top
// level of Parse.
79
func errRecover(errp *error) {
80 81
	e := recover()
	if e != nil {
82 83 84 85 86 87
		switch err := e.(type) {
		case runtime.Error:
			panic(e)
		case error:
			*errp = err
		default:
88 89 90 91 92
			panic(e)
		}
	}
}

Rob Pike's avatar
Rob Pike committed
93 94 95 96 97 98 99 100 101 102
// ExecuteTemplate applies the template associated with t that has the given name
// to the specified data object and writes the output to wr.
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
	tmpl := t.tmpl[name]
	if tmpl == nil {
		return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
	}
	return tmpl.Execute(wr, data)
}

103
// Execute applies a parsed template to the specified data object,
Rob Pike's avatar
Rob Pike committed
104
// and writes the output to wr.
105
func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
106
	defer errRecover(&err)
Rob Pike's avatar
Rob Pike committed
107
	value := reflect.ValueOf(data)
108 109 110 111
	state := &state{
		tmpl: t,
		wr:   wr,
		line: 1,
Rob Pike's avatar
Rob Pike committed
112
		vars: []variable{{"$", value}},
113
	}
114
	if t.Tree == nil || t.Root == nil {
115
		state.errorf("%q is an incomplete or empty template", t.name)
116
	}
117
	state.walk(value, t.Root)
118 119 120 121 122
	return
}

// Walk functions step through the major pieces of the template structure,
// generating output as they go.
123
func (s *state) walk(dot reflect.Value, n parse.Node) {
124
	switch n := n.(type) {
125 126
	case *parse.ActionNode:
		s.line = n.Line
127
		// Do not pop variables so they persist until next end.
128
		// Also, if the action declares variables, don't print the result.
129 130
		val := s.evalPipeline(dot, n.Pipe)
		if len(n.Pipe.Decl) == 0 {
131 132
			s.printValue(n, val)
		}
133 134 135 136 137
	case *parse.IfNode:
		s.line = n.Line
		s.walkIfOrWith(parse.NodeIf, dot, n.Pipe, n.List, n.ElseList)
	case *parse.ListNode:
		for _, node := range n.Nodes {
138
			s.walk(dot, node)
139
		}
140 141
	case *parse.RangeNode:
		s.line = n.Line
142
		s.walkRange(dot, n)
143 144
	case *parse.TemplateNode:
		s.line = n.Line
145
		s.walkTemplate(dot, n)
146 147
	case *parse.TextNode:
		if _, err := s.wr.Write(n.Text); err != nil {
148 149
			s.error(err)
		}
150 151 152
	case *parse.WithNode:
		s.line = n.Line
		s.walkIfOrWith(parse.NodeWith, dot, n.Pipe, n.List, n.ElseList)
153 154 155 156 157
	default:
		s.errorf("unknown node: %s", n)
	}
}

158 159
// walkIfOrWith walks an 'if' or 'with' node. The two control structures
// are identical in behavior except that 'with' sets dot.
160
func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
Rob Pike's avatar
Rob Pike committed
161
	defer s.pop(s.mark())
162
	val := s.evalPipeline(dot, pipe)
163 164
	truth, ok := isTrue(val)
	if !ok {
165
		s.errorf("if/with can't use %v", val)
166 167
	}
	if truth {
168
		if typ == parse.NodeWith {
169
			s.walk(val, list)
170
		} else {
171
			s.walk(dot, list)
172 173
		}
	} else if elseList != nil {
174
		s.walk(dot, elseList)
175 176 177 178 179 180
	}
}

// isTrue returns whether the value is 'true', in the sense of not the zero of its type,
// and whether the value has a meaningful truth value.
func isTrue(val reflect.Value) (truth, ok bool) {
181 182 183 184
	if !val.IsValid() {
		// Something like var x interface{}, never set. It's a form of nil.
		return false, true
	}
185 186 187 188 189 190 191
	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
192
	case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
193
		truth = !val.IsNil()
194 195 196 197 198 199
	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
200 201
	case reflect.Struct:
		truth = true // Struct values are always true.
202
	default:
203
		return
204
	}
205
	return truth, true
206 207
}

208
func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
Rob Pike's avatar
Rob Pike committed
209
	defer s.pop(s.mark())
210
	val, _ := indirect(s.evalPipeline(dot, r.Pipe))
211 212
	// mark top of stack before any variables in the body are pushed.
	mark := s.mark()
Rob Pike's avatar
Rob Pike committed
213 214 215 216 217 218 219 220 221 222 223 224
	oneIteration := func(index, elem reflect.Value) {
		// Set top var (lexically the second if there are two) to the element.
		if len(r.Pipe.Decl) > 0 {
			s.setVar(1, elem)
		}
		// Set next var (lexically the first if there are two) to the index.
		if len(r.Pipe.Decl) > 1 {
			s.setVar(2, index)
		}
		s.walk(elem, r.List)
		s.pop(mark)
	}
225 226 227 228 229 230
	switch val.Kind() {
	case reflect.Array, reflect.Slice:
		if val.Len() == 0 {
			break
		}
		for i := 0; i < val.Len(); i++ {
Rob Pike's avatar
Rob Pike committed
231
			oneIteration(reflect.ValueOf(i), val.Index(i))
232 233 234 235 236 237
		}
		return
	case reflect.Map:
		if val.Len() == 0 {
			break
		}
238
		for _, key := range sortKeys(val.MapKeys()) {
Rob Pike's avatar
Rob Pike committed
239 240 241 242 243 244 245 246 247 248 249 250
			oneIteration(key, val.MapIndex(key))
		}
		return
	case reflect.Chan:
		if val.IsNil() {
			break
		}
		i := 0
		for ; ; i++ {
			elem, ok := val.Recv()
			if !ok {
				break
Rob Pike's avatar
Rob Pike committed
251
			}
Rob Pike's avatar
Rob Pike committed
252 253 254 255
			oneIteration(reflect.ValueOf(i), elem)
		}
		if i == 0 {
			break
256 257
		}
		return
258 259
	case reflect.Invalid:
		break // An invalid value is likely a nil map, etc. and acts like an empty map.
260
	default:
261
		s.errorf("range can't iterate over %v", val)
262
	}
263 264
	if r.ElseList != nil {
		s.walk(dot, r.ElseList)
265 266 267
	}
}

268
func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
Rob Pike's avatar
Rob Pike committed
269
	tmpl := s.tmpl.tmpl[t.Name]
270
	if tmpl == nil {
Rob Pike's avatar
Rob Pike committed
271
		s.errorf("template %q not defined", t.Name)
272
	}
273
	// Variables declared by the pipeline persist.
274
	dot = s.evalPipeline(dot, t.Pipe)
275 276
	newState := *s
	newState.tmpl = tmpl
Rob Pike's avatar
Rob Pike committed
277
	// No dynamic scoping: template invocations inherit no variables.
278
	newState.vars = []variable{{"$", dot}}
279
	newState.walk(dot, tmpl.Root)
280 281
}

282 283 284 285
// 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.

Rob Pike's avatar
Rob Pike committed
286 287 288 289
// 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.
290
func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
291 292 293
	if pipe == nil {
		return
	}
294
	for _, cmd := range pipe.Cmds {
295
		value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
296 297 298 299
		// 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!
		}
300
	}
301 302
	for _, variable := range pipe.Decl {
		s.push(variable.Ident[0], value)
Rob Pike's avatar
Rob Pike committed
303
	}
304 305 306
	return value
}

307
func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
Rob Pike's avatar
Rob Pike committed
308 309 310 311 312
	if len(args) > 1 || final.IsValid() {
		s.errorf("can't give argument to non-function %s", args[0])
	}
}

313 314
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
315
	switch n := firstWord.(type) {
316 317 318
	case *parse.FieldNode:
		return s.evalFieldNode(dot, n, cmd.Args, final)
	case *parse.IdentifierNode:
319
		// Must be a function.
320 321 322
		return s.evalFunction(dot, n.Ident, cmd.Args, final)
	case *parse.VariableNode:
		return s.evalVariableNode(dot, n, cmd.Args, final)
323
	}
324
	s.notAFunction(cmd.Args, final)
325
	switch word := firstWord.(type) {
326 327 328
	case *parse.BoolNode:
		return reflect.ValueOf(word.True)
	case *parse.DotNode:
329
		return dot
330
	case *parse.NumberNode:
331
		return s.idealConstant(word)
332 333
	case *parse.StringNode:
		return reflect.ValueOf(word.Text)
334
	}
335
	s.errorf("can't evaluate command %q", firstWord)
336 337 338
	panic("not reached")
}

339 340 341 342
// 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
// its type, and we use Go rules to resolve.  Note there is no such thing as
// a uint ideal constant in this situation - the value must be of int type.
343
func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
344 345 346 347
	// 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.
	switch {
348 349 350 351 352 353 354 355
	case constant.IsComplex:
		return reflect.ValueOf(constant.Complex128) // incontrovertible.
	case constant.IsFloat && strings.IndexAny(constant.Text, ".eE") >= 0:
		return reflect.ValueOf(constant.Float64)
	case constant.IsInt:
		n := int(constant.Int64)
		if int64(n) != constant.Int64 {
			s.errorf("%s overflows int", constant.Text)
356 357
		}
		return reflect.ValueOf(n)
358 359
	case constant.IsUint:
		s.errorf("%s overflows int", constant.Text)
360 361 362 363
	}
	return zero
}

364 365
func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
	return s.evalFieldChain(dot, dot, field.Ident, args, final)
366 367
}

368
func (s *state) evalVariableNode(dot reflect.Value, v *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
369
	// $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
370 371
	value := s.varValue(v.Ident[0])
	if len(v.Ident) == 1 {
372
		s.notAFunction(args, final)
373
		return value
374
	}
375
	return s.evalFieldChain(dot, value, v.Ident[1:], args, final)
376 377
}

378 379 380
// 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.
381
func (s *state) evalFieldChain(dot, receiver reflect.Value, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
382
	n := len(ident)
383
	for i := 0; i < n-1; i++ {
384
		receiver = s.evalField(dot, ident[i], nil, zero, receiver)
385
	}
386
	// Now if it's a method, it gets the arguments.
387
	return s.evalField(dot, ident[n-1], args, final, receiver)
388 389
}

390
func (s *state) evalFunction(dot reflect.Value, name string, args []parse.Node, final reflect.Value) reflect.Value {
Rob Pike's avatar
Rob Pike committed
391
	function, ok := findFunction(name, s.tmpl)
392 393 394
	if !ok {
		s.errorf("%q is not a defined function", name)
	}
395
	return s.evalCall(dot, function, name, args, final)
396 397
}

398 399 400
// 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.
401
func (s *state) evalField(dot reflect.Value, fieldName string, args []parse.Node, final, receiver reflect.Value) reflect.Value {
402 403 404 405 406
	if !receiver.IsValid() {
		return zero
	}
	typ := receiver.Type()
	receiver, _ = indirect(receiver)
407 408
	// Unless it's an interface, need to get to a value of type *T to guarantee
	// we see all methods of T and *T.
409
	ptr := receiver
410
	if ptr.Kind() != reflect.Interface && ptr.CanAddr() {
411 412
		ptr = ptr.Addr()
	}
Rob Pike's avatar
Rob Pike committed
413
	if method := ptr.MethodByName(fieldName); method.IsValid() {
414
		return s.evalCall(dot, method, fieldName, args, final)
415
	}
416
	hasArgs := len(args) > 1 || final.IsValid()
417
	// It's not a method; is it a field of a struct?
418 419
	receiver, isNil := indirect(receiver)
	if receiver.Kind() == reflect.Struct {
420 421 422 423
		tField, ok := receiver.Type().FieldByName(fieldName)
		if ok {
			field := receiver.FieldByIndex(tField.Index)
			if tField.PkgPath == "" { // field is exported
424 425
				// If it's a function, we must call it.
				if hasArgs {
426
					s.errorf("%s has arguments but cannot be invoked as function", fieldName)
427
				}
428
				return field
429 430
			}
		}
431
	}
432 433 434 435 436 437 438 439 440 441
	// If it's a map, attempt to use the field name as a key.
	if receiver.Kind() == reflect.Map {
		nameVal := reflect.ValueOf(fieldName)
		if nameVal.Type().AssignableTo(receiver.Type().Key()) {
			if hasArgs {
				s.errorf("%s is not a method but has arguments", fieldName)
			}
			return receiver.MapIndex(nameVal)
		}
	}
442 443 444
	if isNil {
		s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
	}
445
	s.errorf("can't evaluate field %s in type %s", fieldName, typ)
446 447 448 449
	panic("not reached")
}

var (
Russ Cox's avatar
Russ Cox committed
450
	errorType       = reflect.TypeOf((*error)(nil)).Elem()
451
	fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
452 453
)

454 455 456
// evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
// it looks just like a function call.  The arg list, if non-nil, includes (in the manner of the shell), arg[0]
// as the function itself.
457
func (s *state) evalCall(dot, fun reflect.Value, name string, args []parse.Node, final reflect.Value) reflect.Value {
458 459
	if args != nil {
		args = args[1:] // Zeroth arg is function name/node; not passed to function.
Rob Pike's avatar
Rob Pike committed
460
	}
461
	typ := fun.Type()
462 463 464 465
	numIn := len(args)
	if final.IsValid() {
		numIn++
	}
Rob Pike's avatar
Rob Pike committed
466 467 468 469 470 471 472 473
	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))
		}
	} else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() {
		s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args))
474
	}
Rob Pike's avatar
Rob Pike committed
475 476
	if !goodFunc(typ) {
		s.errorf("can't handle multiple results from method/function %q", name)
477 478 479
	}
	// Build the arg list.
	argv := make([]reflect.Value, numIn)
480
	// Args must be evaluated. Fixed args first.
Rob Pike's avatar
Rob Pike committed
481 482
	i := 0
	for ; i < numFixed; i++ {
483
		argv[i] = s.evalArg(dot, typ.In(i), args[i])
484
	}
485
	// Now the ... args.
Rob Pike's avatar
Rob Pike committed
486 487 488
	if typ.IsVariadic() {
		argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
		for ; i < len(args); i++ {
489
			argv[i] = s.evalArg(dot, argType, args[i])
Rob Pike's avatar
Rob Pike committed
490 491
		}
	}
492 493
	// Add final value if necessary.
	if final.IsValid() {
494 495 496 497 498
		t := typ.In(typ.NumIn() - 1)
		if typ.IsVariadic() {
			t = t.Elem()
		}
		argv[i] = s.validateType(final, t)
499 500
	}
	result := fun.Call(argv)
501
	// If we have an error that is not nil, stop execution and return that error to the caller.
502
	if len(result) == 2 && !result[1].IsNil() {
503
		s.errorf("error calling %s: %s", name, result[1].Interface().(error))
504 505 506 507
	}
	return result[0]
}

508
// validateType guarantees that the value is valid and assignable to the type.
509
func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
510
	if !value.IsValid() {
511 512 513
		switch typ.Kind() {
		case reflect.Interface, reflect.Ptr, reflect.Chan, reflect.Map, reflect.Slice, reflect.Func:
			// An untyped nil interface{}. Accept as a proper nil value.
514
			// TODO: Can we delete the other types in this list? Should we?
515 516 517 518
			value = reflect.Zero(typ)
		default:
			s.errorf("invalid value; expected %s", typ)
		}
519
	}
520
	if !value.Type().AssignableTo(typ) {
521 522 523 524 525 526 527
		if value.Kind() == reflect.Interface && !value.IsNil() {
			value = value.Elem()
			if value.Type().AssignableTo(typ) {
				return value
			}
			// fallthrough
		}
528 529 530 531 532
		// 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 {
533
		case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
534 535 536 537 538 539
			value = value.Elem()
		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())
		}
540 541 542 543
	}
	return value
}

544
func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
545
	switch arg := n.(type) {
546
	case *parse.DotNode:
547
		return s.validateType(dot, typ)
548 549 550
	case *parse.FieldNode:
		return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, zero), typ)
	case *parse.VariableNode:
551
		return s.validateType(s.evalVariableNode(dot, arg, nil, zero), typ)
552 553
	}
	switch typ.Kind() {
Rob Pike's avatar
Rob Pike committed
554
	case reflect.Bool:
Rob Pike's avatar
Rob Pike committed
555
		return s.evalBool(typ, n)
556
	case reflect.Complex64, reflect.Complex128:
Rob Pike's avatar
Rob Pike committed
557
		return s.evalComplex(typ, n)
558 559 560 561
	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
562 563
	case reflect.Interface:
		if typ.NumMethod() == 0 {
564
			return s.evalEmptyInterface(dot, n)
Rob Pike's avatar
Rob Pike committed
565
		}
566 567 568 569
	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)
570
	}
Rob Pike's avatar
Rob Pike committed
571
	s.errorf("can't handle %s for arg of type %s", n, typ)
572 573 574
	panic("not reached")
}

575 576
func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
	if n, ok := n.(*parse.BoolNode); ok {
Rob Pike's avatar
Rob Pike committed
577
		value := reflect.New(typ).Elem()
578
		value.SetBool(n.True)
Rob Pike's avatar
Rob Pike committed
579 580 581 582 583 584
		return value
	}
	s.errorf("expected bool; found %s", n)
	panic("not reached")
}

585 586
func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
	if n, ok := n.(*parse.StringNode); ok {
587
		value := reflect.New(typ).Elem()
588
		value.SetString(n.Text)
589 590 591 592 593 594
		return value
	}
	s.errorf("expected string; found %s", n)
	panic("not reached")
}

595 596
func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
	if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
597
		value := reflect.New(typ).Elem()
598
		value.SetInt(n.Int64)
599 600 601 602 603 604
		return value
	}
	s.errorf("expected integer; found %s", n)
	panic("not reached")
}

605 606
func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
	if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
607
		value := reflect.New(typ).Elem()
608
		value.SetUint(n.Uint64)
609 610 611 612 613 614
		return value
	}
	s.errorf("expected unsigned integer; found %s", n)
	panic("not reached")
}

615 616
func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
	if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
617
		value := reflect.New(typ).Elem()
618
		value.SetFloat(n.Float64)
619 620 621 622 623 624
		return value
	}
	s.errorf("expected float; found %s", n)
	panic("not reached")
}

625 626
func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
	if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
627
		value := reflect.New(typ).Elem()
628
		value.SetComplex(n.Complex128)
629 630 631 632 633 634
		return value
	}
	s.errorf("expected complex; found %s", n)
	panic("not reached")
}

635
func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
Rob Pike's avatar
Rob Pike committed
636
	switch n := n.(type) {
637 638 639
	case *parse.BoolNode:
		return reflect.ValueOf(n.True)
	case *parse.DotNode:
640
		return dot
641
	case *parse.FieldNode:
642
		return s.evalFieldNode(dot, n, nil, zero)
643 644 645
	case *parse.IdentifierNode:
		return s.evalFunction(dot, n.Ident, nil, zero)
	case *parse.NumberNode:
646
		return s.idealConstant(n)
647 648 649
	case *parse.StringNode:
		return reflect.ValueOf(n.Text)
	case *parse.VariableNode:
650
		return s.evalVariableNode(dot, n, nil, zero)
Rob Pike's avatar
Rob Pike committed
651 652 653 654 655
	}
	s.errorf("can't handle assignment of %s to empty interface argument", n)
	panic("not reached")
}

656
// indirect returns the item at the end of indirection, and a bool to indicate if it's nil.
657 658
// We indirect through pointers and empty interfaces (only) because
// non-empty interfaces have methods we might need.
659
func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
660
	for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
661 662 663
		if v.IsNil() {
			return v, true
		}
664 665
		if v.Kind() == reflect.Interface && v.NumMethod() > 0 {
			break
666
		}
667 668 669 670
	}
	return v, false
}

671 672
// printValue writes the textual representation of the value to the output of
// the template.
673
func (s *state) printValue(n parse.Node, v reflect.Value) {
674 675 676
	if v.Kind() == reflect.Ptr {
		v, _ = indirect(v) // fmt.Fprint handles nil.
	}
677
	if !v.IsValid() {
678
		fmt.Fprint(s.wr, "<no value>")
679 680
		return
	}
681

Russ Cox's avatar
Russ Cox committed
682
	if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
683
		if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
684 685 686 687 688 689 690
			v = v.Addr()
		} else {
			switch v.Kind() {
			case reflect.Chan, reflect.Func:
				s.errorf("can't print %s of type %s", n, v.Type())
			}
		}
691
	}
692 693
	fmt.Fprint(s.wr, v.Interface())
}
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734

// Types to help sort the keys in a map for reproducible output.

type rvs []reflect.Value

func (x rvs) Len() int      { return len(x) }
func (x rvs) Swap(i, j int) { x[i], x[j] = x[j], x[i] }

type rvInts struct{ rvs }

func (x rvInts) Less(i, j int) bool { return x.rvs[i].Int() < x.rvs[j].Int() }

type rvUints struct{ rvs }

func (x rvUints) Less(i, j int) bool { return x.rvs[i].Uint() < x.rvs[j].Uint() }

type rvFloats struct{ rvs }

func (x rvFloats) Less(i, j int) bool { return x.rvs[i].Float() < x.rvs[j].Float() }

type rvStrings struct{ rvs }

func (x rvStrings) Less(i, j int) bool { return x.rvs[i].String() < x.rvs[j].String() }

// 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:
		sort.Sort(rvFloats{v})
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		sort.Sort(rvInts{v})
	case reflect.String:
		sort.Sort(rvStrings{v})
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		sort.Sort(rvUints{v})
	}
	return v
}