Source file src/pkg/text/template/exec.go
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package template
6
7 import (
8 "fmt"
9 "io"
10 "reflect"
11 "runtime"
12 "sort"
13 "strings"
14 "text/template/parse"
15 )
16
17 // state represents the state of an execution. It's not part of the
18 // template so that multiple executions of the same template
19 // can execute in parallel.
20 type state struct {
21 tmpl *Template
22 wr io.Writer
23 line int // line number for errors
24 vars []variable // push-down stack of variable values.
25 }
26
27 // variable holds the dynamic value of a variable such as $, $x etc.
28 type variable struct {
29 name string
30 value reflect.Value
31 }
32
33 // push pushes a new variable on the stack.
34 func (s *state) push(name string, value reflect.Value) {
35 s.vars = append(s.vars, variable{name, value})
36 }
37
38 // mark returns the length of the variable stack.
39 func (s *state) mark() int {
40 return len(s.vars)
41 }
42
43 // pop pops the variable stack up to the mark.
44 func (s *state) pop(mark int) {
45 s.vars = s.vars[0:mark]
46 }
47
48 // setVar overwrites the top-nth variable on the stack. Used by range iterations.
49 func (s *state) setVar(n int, value reflect.Value) {
50 s.vars[len(s.vars)-n].value = value
51 }
52
53 // varValue returns the value of the named variable.
54 func (s *state) varValue(name string) reflect.Value {
55 for i := s.mark() - 1; i >= 0; i-- {
56 if s.vars[i].name == name {
57 return s.vars[i].value
58 }
59 }
60 s.errorf("undefined variable: %s", name)
61 return zero
62 }
63
64 var zero reflect.Value
65
66 // errorf formats the error and terminates processing.
67 func (s *state) errorf(format string, args ...interface{}) {
68 format = fmt.Sprintf("template: %s:%d: %s", s.tmpl.Name(), s.line, format)
69 panic(fmt.Errorf(format, args...))
70 }
71
72 // error terminates processing.
73 func (s *state) error(err error) {
74 s.errorf("%s", err)
75 }
76
77 // errRecover is the handler that turns panics into returns from the top
78 // level of Parse.
79 func errRecover(errp *error) {
80 e := recover()
81 if e != nil {
82 switch err := e.(type) {
83 case runtime.Error:
84 panic(e)
85 case error:
86 *errp = err
87 default:
88 panic(e)
89 }
90 }
91 }
92
93 // ExecuteTemplate applies the template associated with t that has the given name
94 // to the specified data object and writes the output to wr.
95 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
96 tmpl := t.tmpl[name]
97 if tmpl == nil {
98 return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
99 }
100 return tmpl.Execute(wr, data)
101 }
102
103 // Execute applies a parsed template to the specified data object,
104 // and writes the output to wr.
105 func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
106 defer errRecover(&err)
107 value := reflect.ValueOf(data)
108 state := &state{
109 tmpl: t,
110 wr: wr,
111 line: 1,
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 return
119 }
120
121 // Walk functions step through the major pieces of the template structure,
122 // generating output as they go.
123 func (s *state) walk(dot reflect.Value, n parse.Node) {
124 switch n := n.(type) {
125 case *parse.ActionNode:
126 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 val := s.evalPipeline(dot, n.Pipe)
130 if len(n.Pipe.Decl) == 0 {
131 s.printValue(n, val)
132 }
133 case *parse.IfNode:
134 s.line = n.Line
135 s.walkIfOrWith(parse.NodeIf, dot, n.Pipe, n.List, n.ElseList)
136 case *parse.ListNode:
137 for _, node := range n.Nodes {
138 s.walk(dot, node)
139 }
140 case *parse.RangeNode:
141 s.line = n.Line
142 s.walkRange(dot, n)
143 case *parse.TemplateNode:
144 s.line = n.Line
145 s.walkTemplate(dot, n)
146 case *parse.TextNode:
147 if _, err := s.wr.Write(n.Text); err != nil {
148 s.error(err)
149 }
150 case *parse.WithNode:
151 s.line = n.Line
152 s.walkIfOrWith(parse.NodeWith, dot, n.Pipe, n.List, n.ElseList)
153 default:
154 s.errorf("unknown node: %s", n)
155 }
156 }
157
158 // walkIfOrWith walks an 'if' or 'with' node. The two control structures
159 // 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) {
161 defer s.pop(s.mark())
162 val := s.evalPipeline(dot, pipe)
163 truth, ok := isTrue(val)
164 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 // isTrue returns whether the value is 'true', in the sense of not the zero of its type,
179 // and whether the value has a meaningful truth value.
180 func isTrue(val reflect.Value) (truth, ok bool) {
181 if !val.IsValid() {
182 // Something like var x interface{}, never set. It's a form of nil.
183 return false, true
184 }
185 switch val.Kind() {
186 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
187 truth = val.Len() > 0
188 case reflect.Bool:
189 truth = val.Bool()
190 case reflect.Complex64, reflect.Complex128:
191 truth = val.Complex() != 0
192 case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
193 truth = !val.IsNil()
194 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
195 truth = val.Int() != 0
196 case reflect.Float32, reflect.Float64:
197 truth = val.Float() != 0
198 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
199 truth = val.Uint() != 0
200 case reflect.Struct:
201 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) {
209 defer s.pop(s.mark())
210 val, _ := indirect(s.evalPipeline(dot, r.Pipe))
211 // mark top of stack before any variables in the body are pushed.
212 mark := s.mark()
213 oneIteration := func(index, elem reflect.Value) {
214 // Set top var (lexically the second if there are two) to the element.
215 if len(r.Pipe.Decl) > 0 {
216 s.setVar(1, elem)
217 }
218 // Set next var (lexically the first if there are two) to the index.
219 if len(r.Pipe.Decl) > 1 {
220 s.setVar(2, index)
221 }
222 s.walk(elem, r.List)
223 s.pop(mark)
224 }
225 switch val.Kind() {
226 case reflect.Array, reflect.Slice:
227 if val.Len() == 0 {
228 break
229 }
230 for i := 0; i < val.Len(); i++ {
231 oneIteration(reflect.ValueOf(i), val.Index(i))
232 }
233 return
234 case reflect.Map:
235 if val.Len() == 0 {
236 break
237 }
238 for _, key := range sortKeys(val.MapKeys()) {
239 oneIteration(key, val.MapIndex(key))
240 }
241 return
242 case reflect.Chan:
243 if val.IsNil() {
244 break
245 }
246 i := 0
247 for ; ; i++ {
248 elem, ok := val.Recv()
249 if !ok {
250 break
251 }
252 oneIteration(reflect.ValueOf(i), elem)
253 }
254 if i == 0 {
255 break
256 }
257 return
258 case reflect.Invalid:
259 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 if r.ElseList != nil {
264 s.walk(dot, r.ElseList)
265 }
266 }
267
268 func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
269 tmpl := s.tmpl.tmpl[t.Name]
270 if tmpl == nil {
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 newState := *s
276 newState.tmpl = tmpl
277 // No dynamic scoping: template invocations inherit no variables.
278 newState.vars = []variable{{"$", dot}}
279 newState.walk(dot, tmpl.Root)
280 }
281
282 // Eval functions evaluate pipelines, commands, and their elements and extract
283 // values from the data structure by examining fields, calling methods, and so on.
284 // The printing of those values happens only through walk functions.
285
286 // evalPipeline returns the value acquired by evaluating a pipeline. If the
287 // pipeline has a variable declaration, the variable will be pushed on the
288 // stack. Callers should therefore pop the stack after they are finished
289 // executing commands depending on the pipeline value.
290 func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
291 if pipe == nil {
292 return
293 }
294 for _, cmd := range pipe.Cmds {
295 value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
296 // If the object has type interface{}, dig down one level to the thing inside.
297 if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
298 value = reflect.ValueOf(value.Interface()) // lovely!
299 }
300 }
301 for _, variable := range pipe.Decl {
302 s.push(variable.Ident[0], value)
303 }
304 return value
305 }
306
307 func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
308 if len(args) > 1 || final.IsValid() {
309 s.errorf("can't give argument to non-function %s", args[0])
310 }
311 }
312
313 func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
314 firstWord := cmd.Args[0]
315 switch n := firstWord.(type) {
316 case *parse.FieldNode:
317 return s.evalFieldNode(dot, n, cmd.Args, final)
318 case *parse.IdentifierNode:
319 // Must be a function.
320 return s.evalFunction(dot, n.Ident, cmd.Args, final)
321 case *parse.VariableNode:
322 return s.evalVariableNode(dot, n, cmd.Args, final)
323 }
324 s.notAFunction(cmd.Args, final)
325 switch word := firstWord.(type) {
326 case *parse.BoolNode:
327 return reflect.ValueOf(word.True)
328 case *parse.DotNode:
329 return dot
330 case *parse.NumberNode:
331 return s.idealConstant(word)
332 case *parse.StringNode:
333 return reflect.ValueOf(word.Text)
334 }
335 s.errorf("can't evaluate command %q", firstWord)
336 panic("not reached")
337 }
338
339 // idealConstant is called to return the value of a number in a context where
340 // we don't know the type. In that case, the syntax of the number tells us
341 // its type, and we use Go rules to resolve. Note there is no such thing as
342 // 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 // These are ideal constants but we don't know the type
345 // and we have no context. (If it was a method argument,
346 // we'd know what we need.) The syntax guides us to some extent.
347 switch {
348 case constant.IsComplex:
349 return reflect.ValueOf(constant.Complex128) // incontrovertible.
350 case constant.IsFloat && strings.IndexAny(constant.Text, ".eE") >= 0:
351 return reflect.ValueOf(constant.Float64)
352 case constant.IsInt:
353 n := int(constant.Int64)
354 if int64(n) != constant.Int64 {
355 s.errorf("%s overflows int", constant.Text)
356 }
357 return reflect.ValueOf(n)
358 case constant.IsUint:
359 s.errorf("%s overflows int", constant.Text)
360 }
361 return zero
362 }
363
364 func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
365 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 value := s.varValue(v.Ident[0])
371 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 // evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
379 // dot is the environment in which to evaluate arguments, while
380 // 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 {
391 function, ok := findFunction(name, s.tmpl)
392 if !ok {
393 s.errorf("%q is not a defined function", name)
394 }
395 return s.evalCall(dot, function, name, args, final)
396 }
397
398 // evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
399 // The 'final' argument represents the return value from the preceding
400 // 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 if !receiver.IsValid() {
403 return zero
404 }
405 typ := receiver.Type()
406 receiver, _ = indirect(receiver)
407 // Unless it's an interface, need to get to a value of type *T to guarantee
408 // we see all methods of T and *T.
409 ptr := receiver
410 if ptr.Kind() != reflect.Interface && ptr.CanAddr() {
411 ptr = ptr.Addr()
412 }
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 receiver, isNil := indirect(receiver)
419 if receiver.Kind() == reflect.Struct {
420 tField, ok := receiver.Type().FieldByName(fieldName)
421 if ok {
422 field := receiver.FieldByIndex(tField.Index)
423 if tField.PkgPath == "" { // field is exported
424 // If it's a function, we must call it.
425 if hasArgs {
426 s.errorf("%s has arguments but cannot be invoked as function", fieldName)
427 }
428 return field
429 }
430 }
431 }
432 // If it's a map, attempt to use the field name as a key.
433 if receiver.Kind() == reflect.Map {
434 nameVal := reflect.ValueOf(fieldName)
435 if nameVal.Type().AssignableTo(receiver.Type().Key()) {
436 if hasArgs {
437 s.errorf("%s is not a method but has arguments", fieldName)
438 }
439 return receiver.MapIndex(nameVal)
440 }
441 }
442 if isNil {
443 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
444 }
445 s.errorf("can't evaluate field %s in type %s", fieldName, typ)
446 panic("not reached")
447 }
448
449 var (
450 errorType = reflect.TypeOf((*error)(nil)).Elem()
451 fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
452 )
453
454 // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
455 // it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
456 // as the function itself.
457 func (s *state) evalCall(dot, fun reflect.Value, name string, args []parse.Node, final reflect.Value) reflect.Value {
458 if args != nil {
459 args = args[1:] // Zeroth arg is function name/node; not passed to function.
460 }
461 typ := fun.Type()
462 numIn := len(args)
463 if final.IsValid() {
464 numIn++
465 }
466 numFixed := len(args)
467 if typ.IsVariadic() {
468 numFixed = typ.NumIn() - 1 // last arg is the variadic one.
469 if numIn < numFixed {
470 s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
471 }
472 } else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() {
473 s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args))
474 }
475 if !goodFunc(typ) {
476 s.errorf("can't handle multiple results from method/function %q", name)
477 }
478 // Build the arg list.
479 argv := make([]reflect.Value, numIn)
480 // Args must be evaluated. Fixed args first.
481 i := 0
482 for ; i < numFixed; i++ {
483 argv[i] = s.evalArg(dot, typ.In(i), args[i])
484 }
485 // Now the ... args.
486 if typ.IsVariadic() {
487 argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
488 for ; i < len(args); i++ {
489 argv[i] = s.evalArg(dot, argType, args[i])
490 }
491 }
492 // Add final value if necessary.
493 if final.IsValid() {
494 t := typ.In(typ.NumIn() - 1)
495 if typ.IsVariadic() {
496 t = t.Elem()
497 }
498 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 return result[0]
506 }
507
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 switch typ.Kind() {
512 case reflect.Interface, reflect.Ptr, reflect.Chan, reflect.Map, reflect.Slice, reflect.Func:
513 // An untyped nil interface{}. Accept as a proper nil value.
514 // TODO: Can we delete the other types in this list? Should we?
515 value = reflect.Zero(typ)
516 default:
517 s.errorf("invalid value; expected %s", typ)
518 }
519 }
520 if !value.Type().AssignableTo(typ) {
521 // Does one dereference or indirection work? We could do more, as we
522 // do with method receivers, but that gets messy and method receivers
523 // are much more constrained, so it makes more sense there than here.
524 // Besides, one is almost always all you need.
525 switch {
526 case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
527 value = value.Elem()
528 case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
529 value = value.Addr()
530 default:
531 s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
532 }
533 }
534 return value
535 }
536
537 func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
538 switch arg := n.(type) {
539 case *parse.DotNode:
540 return s.validateType(dot, typ)
541 case *parse.FieldNode:
542 return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, zero), typ)
543 case *parse.VariableNode:
544 return s.validateType(s.evalVariableNode(dot, arg, nil, zero), typ)
545 }
546 switch typ.Kind() {
547 case reflect.Bool:
548 return s.evalBool(typ, n)
549 case reflect.Complex64, reflect.Complex128:
550 return s.evalComplex(typ, n)
551 case reflect.Float32, reflect.Float64:
552 return s.evalFloat(typ, n)
553 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
554 return s.evalInteger(typ, n)
555 case reflect.Interface:
556 if typ.NumMethod() == 0 {
557 return s.evalEmptyInterface(dot, n)
558 }
559 case reflect.String:
560 return s.evalString(typ, n)
561 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
562 return s.evalUnsignedInteger(typ, n)
563 }
564 s.errorf("can't handle %s for arg of type %s", n, typ)
565 panic("not reached")
566 }
567
568 func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
569 if n, ok := n.(*parse.BoolNode); ok {
570 value := reflect.New(typ).Elem()
571 value.SetBool(n.True)
572 return value
573 }
574 s.errorf("expected bool; found %s", n)
575 panic("not reached")
576 }
577
578 func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
579 if n, ok := n.(*parse.StringNode); ok {
580 value := reflect.New(typ).Elem()
581 value.SetString(n.Text)
582 return value
583 }
584 s.errorf("expected string; found %s", n)
585 panic("not reached")
586 }
587
588 func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
589 if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
590 value := reflect.New(typ).Elem()
591 value.SetInt(n.Int64)
592 return value
593 }
594 s.errorf("expected integer; found %s", n)
595 panic("not reached")
596 }
597
598 func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
599 if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
600 value := reflect.New(typ).Elem()
601 value.SetUint(n.Uint64)
602 return value
603 }
604 s.errorf("expected unsigned integer; found %s", n)
605 panic("not reached")
606 }
607
608 func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
609 if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
610 value := reflect.New(typ).Elem()
611 value.SetFloat(n.Float64)
612 return value
613 }
614 s.errorf("expected float; found %s", n)
615 panic("not reached")
616 }
617
618 func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
619 if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
620 value := reflect.New(typ).Elem()
621 value.SetComplex(n.Complex128)
622 return value
623 }
624 s.errorf("expected complex; found %s", n)
625 panic("not reached")
626 }
627
628 func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
629 switch n := n.(type) {
630 case *parse.BoolNode:
631 return reflect.ValueOf(n.True)
632 case *parse.DotNode:
633 return dot
634 case *parse.FieldNode:
635 return s.evalFieldNode(dot, n, nil, zero)
636 case *parse.IdentifierNode:
637 return s.evalFunction(dot, n.Ident, nil, zero)
638 case *parse.NumberNode:
639 return s.idealConstant(n)
640 case *parse.StringNode:
641 return reflect.ValueOf(n.Text)
642 case *parse.VariableNode:
643 return s.evalVariableNode(dot, n, nil, zero)
644 }
645 s.errorf("can't handle assignment of %s to empty interface argument", n)
646 panic("not reached")
647 }
648
649 // indirect returns the item at the end of indirection, and a bool to indicate if it's nil.
650 // We indirect through pointers and empty interfaces (only) because
651 // non-empty interfaces have methods we might need.
652 func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
653 for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
654 if v.IsNil() {
655 return v, true
656 }
657 if v.Kind() == reflect.Interface && v.NumMethod() > 0 {
658 break
659 }
660 }
661 return v, false
662 }
663
664 // printValue writes the textual representation of the value to the output of
665 // the template.
666 func (s *state) printValue(n parse.Node, v reflect.Value) {
667 if v.Kind() == reflect.Ptr {
668 v, _ = indirect(v) // fmt.Fprint handles nil.
669 }
670 if !v.IsValid() {
671 fmt.Fprint(s.wr, "<no value>")
672 return
673 }
674
675 if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
676 if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
677 v = v.Addr()
678 } else {
679 switch v.Kind() {
680 case reflect.Chan, reflect.Func:
681 s.errorf("can't print %s of type %s", n, v.Type())
682 }
683 }
684 }
685 fmt.Fprint(s.wr, v.Interface())
686 }
687
688 // Types to help sort the keys in a map for reproducible output.
689
690 type rvs []reflect.Value
691
692 func (x rvs) Len() int { return len(x) }
693 func (x rvs) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
694
695 type rvInts struct{ rvs }
696
697 func (x rvInts) Less(i, j int) bool { return x.rvs[i].Int() < x.rvs[j].Int() }
698
699 type rvUints struct{ rvs }
700
701 func (x rvUints) Less(i, j int) bool { return x.rvs[i].Uint() < x.rvs[j].Uint() }
702
703 type rvFloats struct{ rvs }
704
705 func (x rvFloats) Less(i, j int) bool { return x.rvs[i].Float() < x.rvs[j].Float() }
706
707 type rvStrings struct{ rvs }
708
709 func (x rvStrings) Less(i, j int) bool { return x.rvs[i].String() < x.rvs[j].String() }
710
711 // sortKeys sorts (if it can) the slice of reflect.Values, which is a slice of map keys.
712 func sortKeys(v []reflect.Value) []reflect.Value {
713 if len(v) <= 1 {
714 return v
715 }
716 switch v[0].Kind() {
717 case reflect.Float32, reflect.Float64:
718 sort.Sort(rvFloats{v})
719 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
720 sort.Sort(rvInts{v})
721 case reflect.String:
722 sort.Sort(rvStrings{v})
723 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
724 sort.Sort(rvUints{v})
725 }
726 return v
727 }