OSDN Git Service

ad0118e4e6821a16890552dc5759325a9c4295b2
[pf3gnuchains/gcc-fork.git] / libgo / go / 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                 return value
373         }
374         return s.evalFieldChain(dot, value, v.Ident[1:], args, final)
375 }
376
377 // evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
378 // dot is the environment in which to evaluate arguments, while
379 // receiver is the value being walked along the chain.
380 func (s *state) evalFieldChain(dot, receiver reflect.Value, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
381         n := len(ident)
382         for i := 0; i < n-1; i++ {
383                 receiver = s.evalField(dot, ident[i], nil, zero, receiver)
384         }
385         // Now if it's a method, it gets the arguments.
386         return s.evalField(dot, ident[n-1], args, final, receiver)
387 }
388
389 func (s *state) evalFunction(dot reflect.Value, name string, args []parse.Node, final reflect.Value) reflect.Value {
390         function, ok := findFunction(name, s.tmpl)
391         if !ok {
392                 s.errorf("%q is not a defined function", name)
393         }
394         return s.evalCall(dot, function, name, args, final)
395 }
396
397 // evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
398 // The 'final' argument represents the return value from the preceding
399 // value of the pipeline, if any.
400 func (s *state) evalField(dot reflect.Value, fieldName string, args []parse.Node, final, receiver reflect.Value) reflect.Value {
401         if !receiver.IsValid() {
402                 return zero
403         }
404         typ := receiver.Type()
405         receiver, _ = indirect(receiver)
406         // Unless it's an interface, need to get to a value of type *T to guarantee
407         // we see all methods of T and *T.
408         ptr := receiver
409         if ptr.Kind() != reflect.Interface && ptr.CanAddr() {
410                 ptr = ptr.Addr()
411         }
412         if method := ptr.MethodByName(fieldName); method.IsValid() {
413                 return s.evalCall(dot, method, fieldName, args, final)
414         }
415         hasArgs := len(args) > 1 || final.IsValid()
416         // It's not a method; is it a field of a struct?
417         receiver, isNil := indirect(receiver)
418         if receiver.Kind() == reflect.Struct {
419                 tField, ok := receiver.Type().FieldByName(fieldName)
420                 if ok {
421                         field := receiver.FieldByIndex(tField.Index)
422                         if tField.PkgPath == "" { // field is exported
423                                 // If it's a function, we must call it.
424                                 if hasArgs {
425                                         s.errorf("%s has arguments but cannot be invoked as function", fieldName)
426                                 }
427                                 return field
428                         }
429                 }
430         }
431         // If it's a map, attempt to use the field name as a key.
432         if receiver.Kind() == reflect.Map {
433                 nameVal := reflect.ValueOf(fieldName)
434                 if nameVal.Type().AssignableTo(receiver.Type().Key()) {
435                         if hasArgs {
436                                 s.errorf("%s is not a method but has arguments", fieldName)
437                         }
438                         return receiver.MapIndex(nameVal)
439                 }
440         }
441         if isNil {
442                 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
443         }
444         s.errorf("can't evaluate field %s in type %s", fieldName, typ)
445         panic("not reached")
446 }
447
448 var (
449         errorType       = reflect.TypeOf((*error)(nil)).Elem()
450         fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
451 )
452
453 // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
454 // it looks just like a function call.  The arg list, if non-nil, includes (in the manner of the shell), arg[0]
455 // as the function itself.
456 func (s *state) evalCall(dot, fun reflect.Value, name string, args []parse.Node, final reflect.Value) reflect.Value {
457         if args != nil {
458                 args = args[1:] // Zeroth arg is function name/node; not passed to function.
459         }
460         typ := fun.Type()
461         numIn := len(args)
462         if final.IsValid() {
463                 numIn++
464         }
465         numFixed := len(args)
466         if typ.IsVariadic() {
467                 numFixed = typ.NumIn() - 1 // last arg is the variadic one.
468                 if numIn < numFixed {
469                         s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
470                 }
471         } else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() {
472                 s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args))
473         }
474         if !goodFunc(typ) {
475                 s.errorf("can't handle multiple results from method/function %q", name)
476         }
477         // Build the arg list.
478         argv := make([]reflect.Value, numIn)
479         // Args must be evaluated. Fixed args first.
480         i := 0
481         for ; i < numFixed; i++ {
482                 argv[i] = s.evalArg(dot, typ.In(i), args[i])
483         }
484         // Now the ... args.
485         if typ.IsVariadic() {
486                 argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
487                 for ; i < len(args); i++ {
488                         argv[i] = s.evalArg(dot, argType, args[i])
489                 }
490         }
491         // Add final value if necessary.
492         if final.IsValid() {
493                 argv[i] = final
494         }
495         result := fun.Call(argv)
496         // If we have an error that is not nil, stop execution and return that error to the caller.
497         if len(result) == 2 && !result[1].IsNil() {
498                 s.errorf("error calling %s: %s", name, result[1].Interface().(error))
499         }
500         return result[0]
501 }
502
503 // validateType guarantees that the value is valid and assignable to the type.
504 func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
505         if !value.IsValid() {
506                 switch typ.Kind() {
507                 case reflect.Interface, reflect.Ptr, reflect.Chan, reflect.Map, reflect.Slice, reflect.Func:
508                         // An untyped nil interface{}. Accept as a proper nil value.
509                         value = reflect.Zero(typ)
510                 default:
511                         s.errorf("invalid value; expected %s", typ)
512                 }
513         }
514         if !value.Type().AssignableTo(typ) {
515                 // Does one dereference or indirection work? We could do more, as we
516                 // do with method receivers, but that gets messy and method receivers
517                 // are much more constrained, so it makes more sense there than here.
518                 // Besides, one is almost always all you need.
519                 switch {
520                 case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
521                         value = value.Elem()
522                 case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
523                         value = value.Addr()
524                 default:
525                         s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
526                 }
527         }
528         return value
529 }
530
531 func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
532         switch arg := n.(type) {
533         case *parse.DotNode:
534                 return s.validateType(dot, typ)
535         case *parse.FieldNode:
536                 return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, zero), typ)
537         case *parse.VariableNode:
538                 return s.validateType(s.evalVariableNode(dot, arg, nil, zero), typ)
539         }
540         switch typ.Kind() {
541         case reflect.Bool:
542                 return s.evalBool(typ, n)
543         case reflect.Complex64, reflect.Complex128:
544                 return s.evalComplex(typ, n)
545         case reflect.Float32, reflect.Float64:
546                 return s.evalFloat(typ, n)
547         case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
548                 return s.evalInteger(typ, n)
549         case reflect.Interface:
550                 if typ.NumMethod() == 0 {
551                         return s.evalEmptyInterface(dot, n)
552                 }
553         case reflect.String:
554                 return s.evalString(typ, n)
555         case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
556                 return s.evalUnsignedInteger(typ, n)
557         }
558         s.errorf("can't handle %s for arg of type %s", n, typ)
559         panic("not reached")
560 }
561
562 func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
563         if n, ok := n.(*parse.BoolNode); ok {
564                 value := reflect.New(typ).Elem()
565                 value.SetBool(n.True)
566                 return value
567         }
568         s.errorf("expected bool; found %s", n)
569         panic("not reached")
570 }
571
572 func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
573         if n, ok := n.(*parse.StringNode); ok {
574                 value := reflect.New(typ).Elem()
575                 value.SetString(n.Text)
576                 return value
577         }
578         s.errorf("expected string; found %s", n)
579         panic("not reached")
580 }
581
582 func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
583         if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
584                 value := reflect.New(typ).Elem()
585                 value.SetInt(n.Int64)
586                 return value
587         }
588         s.errorf("expected integer; found %s", n)
589         panic("not reached")
590 }
591
592 func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
593         if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
594                 value := reflect.New(typ).Elem()
595                 value.SetUint(n.Uint64)
596                 return value
597         }
598         s.errorf("expected unsigned integer; found %s", n)
599         panic("not reached")
600 }
601
602 func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
603         if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
604                 value := reflect.New(typ).Elem()
605                 value.SetFloat(n.Float64)
606                 return value
607         }
608         s.errorf("expected float; found %s", n)
609         panic("not reached")
610 }
611
612 func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
613         if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
614                 value := reflect.New(typ).Elem()
615                 value.SetComplex(n.Complex128)
616                 return value
617         }
618         s.errorf("expected complex; found %s", n)
619         panic("not reached")
620 }
621
622 func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
623         switch n := n.(type) {
624         case *parse.BoolNode:
625                 return reflect.ValueOf(n.True)
626         case *parse.DotNode:
627                 return dot
628         case *parse.FieldNode:
629                 return s.evalFieldNode(dot, n, nil, zero)
630         case *parse.IdentifierNode:
631                 return s.evalFunction(dot, n.Ident, nil, zero)
632         case *parse.NumberNode:
633                 return s.idealConstant(n)
634         case *parse.StringNode:
635                 return reflect.ValueOf(n.Text)
636         case *parse.VariableNode:
637                 return s.evalVariableNode(dot, n, nil, zero)
638         }
639         s.errorf("can't handle assignment of %s to empty interface argument", n)
640         panic("not reached")
641 }
642
643 // indirect returns the item at the end of indirection, and a bool to indicate if it's nil.
644 // We indirect through pointers and empty interfaces (only) because
645 // non-empty interfaces have methods we might need.
646 func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
647         for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
648                 if v.IsNil() {
649                         return v, true
650                 }
651                 if v.Kind() == reflect.Interface && v.NumMethod() > 0 {
652                         break
653                 }
654         }
655         return v, false
656 }
657
658 // printValue writes the textual representation of the value to the output of
659 // the template.
660 func (s *state) printValue(n parse.Node, v reflect.Value) {
661         if v.Kind() == reflect.Ptr {
662                 v, _ = indirect(v) // fmt.Fprint handles nil.
663         }
664         if !v.IsValid() {
665                 fmt.Fprint(s.wr, "<no value>")
666                 return
667         }
668
669         if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
670                 if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
671                         v = v.Addr()
672                 } else {
673                         switch v.Kind() {
674                         case reflect.Chan, reflect.Func:
675                                 s.errorf("can't print %s of type %s", n, v.Type())
676                         }
677                 }
678         }
679         fmt.Fprint(s.wr, v.Interface())
680 }
681
682 // Types to help sort the keys in a map for reproducible output.
683
684 type rvs []reflect.Value
685
686 func (x rvs) Len() int      { return len(x) }
687 func (x rvs) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
688
689 type rvInts struct{ rvs }
690
691 func (x rvInts) Less(i, j int) bool { return x.rvs[i].Int() < x.rvs[j].Int() }
692
693 type rvUints struct{ rvs }
694
695 func (x rvUints) Less(i, j int) bool { return x.rvs[i].Uint() < x.rvs[j].Uint() }
696
697 type rvFloats struct{ rvs }
698
699 func (x rvFloats) Less(i, j int) bool { return x.rvs[i].Float() < x.rvs[j].Float() }
700
701 type rvStrings struct{ rvs }
702
703 func (x rvStrings) Less(i, j int) bool { return x.rvs[i].String() < x.rvs[j].String() }
704
705 // sortKeys sorts (if it can) the slice of reflect.Values, which is a slice of map keys.
706 func sortKeys(v []reflect.Value) []reflect.Value {
707         if len(v) <= 1 {
708                 return v
709         }
710         switch v[0].Kind() {
711         case reflect.Float32, reflect.Float64:
712                 sort.Sort(rvFloats{v})
713         case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
714                 sort.Sort(rvInts{v})
715         case reflect.String:
716                 sort.Sort(rvStrings{v})
717         case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
718                 sort.Sort(rvUints{v})
719         }
720         return v
721 }