OSDN Git Service

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