1
2
3
4
5 package template
6
7 import (
8 "fmt"
9 "internal/fmtsort"
10 "io"
11 "reflect"
12 "runtime"
13 "strings"
14 "text/template/parse"
15 )
16
17
18
19
20
21 var maxExecDepth = initMaxExecDepth()
22
23 func initMaxExecDepth() int {
24 if runtime.GOARCH == "wasm" {
25 return 1000
26 }
27 return 100000
28 }
29
30
31
32
33 type state struct {
34 tmpl *Template
35 wr io.Writer
36 node parse.Node
37 vars []variable
38 depth int
39 }
40
41
42 type variable struct {
43 name string
44 value reflect.Value
45 }
46
47
48 func (s *state) push(name string, value reflect.Value) {
49 s.vars = append(s.vars, variable{name, value})
50 }
51
52
53 func (s *state) mark() int {
54 return len(s.vars)
55 }
56
57
58 func (s *state) pop(mark int) {
59 s.vars = s.vars[0:mark]
60 }
61
62
63
64 func (s *state) setVar(name string, value reflect.Value) {
65 for i := s.mark() - 1; i >= 0; i-- {
66 if s.vars[i].name == name {
67 s.vars[i].value = value
68 return
69 }
70 }
71 s.errorf("undefined variable: %s", name)
72 }
73
74
75 func (s *state) setTopVar(n int, value reflect.Value) {
76 s.vars[len(s.vars)-n].value = value
77 }
78
79
80 func (s *state) varValue(name string) reflect.Value {
81 for i := s.mark() - 1; i >= 0; i-- {
82 if s.vars[i].name == name {
83 return s.vars[i].value
84 }
85 }
86 s.errorf("undefined variable: %s", name)
87 return zero
88 }
89
90 var zero reflect.Value
91
92 type missingValType struct{}
93
94 var missingVal = reflect.ValueOf(missingValType{})
95
96
97 func (s *state) at(node parse.Node) {
98 s.node = node
99 }
100
101
102
103 func doublePercent(str string) string {
104 return strings.ReplaceAll(str, "%", "%%")
105 }
106
107
108
109
110
111
112
113
114 type ExecError struct {
115 Name string
116 Err error
117 }
118
119 func (e ExecError) Error() string {
120 return e.Err.Error()
121 }
122
123 func (e ExecError) Unwrap() error {
124 return e.Err
125 }
126
127
128 func (s *state) errorf(format string, args ...interface{}) {
129 name := doublePercent(s.tmpl.Name())
130 if s.node == nil {
131 format = fmt.Sprintf("template: %s: %s", name, format)
132 } else {
133 location, context := s.tmpl.ErrorContext(s.node)
134 format = fmt.Sprintf("template: %s: executing %q at <%s>: %s", location, name, doublePercent(context), format)
135 }
136 panic(ExecError{
137 Name: s.tmpl.Name(),
138 Err: fmt.Errorf(format, args...),
139 })
140 }
141
142
143
144
145
146 type writeError struct {
147 Err error
148 }
149
150 func (s *state) writeError(err error) {
151 panic(writeError{
152 Err: err,
153 })
154 }
155
156
157
158 func errRecover(errp *error) {
159 e := recover()
160 if e != nil {
161 switch err := e.(type) {
162 case runtime.Error:
163 panic(e)
164 case writeError:
165 *errp = err.Err
166 case ExecError:
167 *errp = err
168 default:
169 panic(e)
170 }
171 }
172 }
173
174
175
176
177
178
179
180
181 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
182 tmpl := t.Lookup(name)
183 if tmpl == nil {
184 return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
185 }
186 return tmpl.Execute(wr, data)
187 }
188
189
190
191
192
193
194
195
196
197
198
199 func (t *Template) Execute(wr io.Writer, data interface{}) error {
200 return t.execute(wr, data)
201 }
202
203 func (t *Template) execute(wr io.Writer, data interface{}) (err error) {
204 defer errRecover(&err)
205 value, ok := data.(reflect.Value)
206 if !ok {
207 value = reflect.ValueOf(data)
208 }
209 state := &state{
210 tmpl: t,
211 wr: wr,
212 vars: []variable{{"$", value}},
213 }
214 if t.Tree == nil || t.Root == nil {
215 state.errorf("%q is an incomplete or empty template", t.Name())
216 }
217 state.walk(value, t.Root)
218 return
219 }
220
221
222
223
224
225 func (t *Template) DefinedTemplates() string {
226 if t.common == nil {
227 return ""
228 }
229 var b strings.Builder
230 t.muTmpl.RLock()
231 defer t.muTmpl.RUnlock()
232 for name, tmpl := range t.tmpl {
233 if tmpl.Tree == nil || tmpl.Root == nil {
234 continue
235 }
236 if b.Len() == 0 {
237 b.WriteString("; defined templates are: ")
238 } else {
239 b.WriteString(", ")
240 }
241 fmt.Fprintf(&b, "%q", name)
242 }
243 return b.String()
244 }
245
246
247
248 func (s *state) walk(dot reflect.Value, node parse.Node) {
249 s.at(node)
250 switch node := node.(type) {
251 case *parse.ActionNode:
252
253
254 val := s.evalPipeline(dot, node.Pipe)
255 if len(node.Pipe.Decl) == 0 {
256 s.printValue(node, val)
257 }
258 case *parse.CommentNode:
259 case *parse.IfNode:
260 s.walkIfOrWith(parse.NodeIf, dot, node.Pipe, node.List, node.ElseList)
261 case *parse.ListNode:
262 for _, node := range node.Nodes {
263 s.walk(dot, node)
264 }
265 case *parse.RangeNode:
266 s.walkRange(dot, node)
267 case *parse.TemplateNode:
268 s.walkTemplate(dot, node)
269 case *parse.TextNode:
270 if _, err := s.wr.Write(node.Text); err != nil {
271 s.writeError(err)
272 }
273 case *parse.WithNode:
274 s.walkIfOrWith(parse.NodeWith, dot, node.Pipe, node.List, node.ElseList)
275 default:
276 s.errorf("unknown node: %s", node)
277 }
278 }
279
280
281
282 func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
283 defer s.pop(s.mark())
284 val := s.evalPipeline(dot, pipe)
285 truth, ok := isTrue(indirectInterface(val))
286 if !ok {
287 s.errorf("if/with can't use %v", val)
288 }
289 if truth {
290 if typ == parse.NodeWith {
291 s.walk(val, list)
292 } else {
293 s.walk(dot, list)
294 }
295 } else if elseList != nil {
296 s.walk(dot, elseList)
297 }
298 }
299
300
301
302
303 func IsTrue(val interface{}) (truth, ok bool) {
304 return isTrue(reflect.ValueOf(val))
305 }
306
307 func isTrue(val reflect.Value) (truth, ok bool) {
308 if !val.IsValid() {
309
310 return false, true
311 }
312 switch val.Kind() {
313 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
314 truth = val.Len() > 0
315 case reflect.Bool:
316 truth = val.Bool()
317 case reflect.Complex64, reflect.Complex128:
318 truth = val.Complex() != 0
319 case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
320 truth = !val.IsNil()
321 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
322 truth = val.Int() != 0
323 case reflect.Float32, reflect.Float64:
324 truth = val.Float() != 0
325 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
326 truth = val.Uint() != 0
327 case reflect.Struct:
328 truth = true
329 default:
330 return
331 }
332 return truth, true
333 }
334
335 func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
336 s.at(r)
337 defer s.pop(s.mark())
338 val, _ := indirect(s.evalPipeline(dot, r.Pipe))
339
340 mark := s.mark()
341 oneIteration := func(index, elem reflect.Value) {
342
343 if len(r.Pipe.Decl) > 0 {
344 s.setTopVar(1, elem)
345 }
346
347 if len(r.Pipe.Decl) > 1 {
348 s.setTopVar(2, index)
349 }
350 s.walk(elem, r.List)
351 s.pop(mark)
352 }
353 switch val.Kind() {
354 case reflect.Array, reflect.Slice:
355 if val.Len() == 0 {
356 break
357 }
358 for i := 0; i < val.Len(); i++ {
359 oneIteration(reflect.ValueOf(i), val.Index(i))
360 }
361 return
362 case reflect.Map:
363 if val.Len() == 0 {
364 break
365 }
366 om := fmtsort.Sort(val)
367 for i, key := range om.Key {
368 oneIteration(key, om.Value[i])
369 }
370 return
371 case reflect.Chan:
372 if val.IsNil() {
373 break
374 }
375 if val.Type().ChanDir() == reflect.SendDir {
376 s.errorf("range over send-only channel %v", val)
377 break
378 }
379 i := 0
380 for ; ; i++ {
381 elem, ok := val.Recv()
382 if !ok {
383 break
384 }
385 oneIteration(reflect.ValueOf(i), elem)
386 }
387 if i == 0 {
388 break
389 }
390 return
391 case reflect.Invalid:
392 break
393 default:
394 s.errorf("range can't iterate over %v", val)
395 }
396 if r.ElseList != nil {
397 s.walk(dot, r.ElseList)
398 }
399 }
400
401 func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
402 s.at(t)
403 tmpl := s.tmpl.Lookup(t.Name)
404 if tmpl == nil {
405 s.errorf("template %q not defined", t.Name)
406 }
407 if s.depth == maxExecDepth {
408 s.errorf("exceeded maximum template depth (%v)", maxExecDepth)
409 }
410
411 dot = s.evalPipeline(dot, t.Pipe)
412 newState := *s
413 newState.depth++
414 newState.tmpl = tmpl
415
416 newState.vars = []variable{{"$", dot}}
417 newState.walk(dot, tmpl.Root)
418 }
419
420
421
422
423
424
425
426
427
428 func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
429 if pipe == nil {
430 return
431 }
432 s.at(pipe)
433 value = missingVal
434 for _, cmd := range pipe.Cmds {
435 value = s.evalCommand(dot, cmd, value)
436
437 if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
438 value = reflect.ValueOf(value.Interface())
439 }
440 }
441 for _, variable := range pipe.Decl {
442 if pipe.IsAssign {
443 s.setVar(variable.Ident[0], value)
444 } else {
445 s.push(variable.Ident[0], value)
446 }
447 }
448 return value
449 }
450
451 func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
452 if len(args) > 1 || final != missingVal {
453 s.errorf("can't give argument to non-function %s", args[0])
454 }
455 }
456
457 func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
458 firstWord := cmd.Args[0]
459 switch n := firstWord.(type) {
460 case *parse.FieldNode:
461 return s.evalFieldNode(dot, n, cmd.Args, final)
462 case *parse.ChainNode:
463 return s.evalChainNode(dot, n, cmd.Args, final)
464 case *parse.IdentifierNode:
465
466 return s.evalFunction(dot, n, cmd, cmd.Args, final)
467 case *parse.PipeNode:
468
469 s.notAFunction(cmd.Args, final)
470 return s.evalPipeline(dot, n)
471 case *parse.VariableNode:
472 return s.evalVariableNode(dot, n, cmd.Args, final)
473 }
474 s.at(firstWord)
475 s.notAFunction(cmd.Args, final)
476 switch word := firstWord.(type) {
477 case *parse.BoolNode:
478 return reflect.ValueOf(word.True)
479 case *parse.DotNode:
480 return dot
481 case *parse.NilNode:
482 s.errorf("nil is not a command")
483 case *parse.NumberNode:
484 return s.idealConstant(word)
485 case *parse.StringNode:
486 return reflect.ValueOf(word.Text)
487 }
488 s.errorf("can't evaluate command %q", firstWord)
489 panic("not reached")
490 }
491
492
493
494
495
496 func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
497
498
499
500 s.at(constant)
501 switch {
502 case constant.IsComplex:
503 return reflect.ValueOf(constant.Complex128)
504
505 case constant.IsFloat &&
506 !isHexInt(constant.Text) && !isRuneInt(constant.Text) &&
507 strings.ContainsAny(constant.Text, ".eEpP"):
508 return reflect.ValueOf(constant.Float64)
509
510 case constant.IsInt:
511 n := int(constant.Int64)
512 if int64(n) != constant.Int64 {
513 s.errorf("%s overflows int", constant.Text)
514 }
515 return reflect.ValueOf(n)
516
517 case constant.IsUint:
518 s.errorf("%s overflows int", constant.Text)
519 }
520 return zero
521 }
522
523 func isRuneInt(s string) bool {
524 return len(s) > 0 && s[0] == '\''
525 }
526
527 func isHexInt(s string) bool {
528 return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') && !strings.ContainsAny(s, "pP")
529 }
530
531 func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
532 s.at(field)
533 return s.evalFieldChain(dot, dot, field, field.Ident, args, final)
534 }
535
536 func (s *state) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value {
537 s.at(chain)
538 if len(chain.Field) == 0 {
539 s.errorf("internal error: no fields in evalChainNode")
540 }
541 if chain.Node.Type() == parse.NodeNil {
542 s.errorf("indirection through explicit nil in %s", chain)
543 }
544
545 pipe := s.evalArg(dot, nil, chain.Node)
546 return s.evalFieldChain(dot, pipe, chain, chain.Field, args, final)
547 }
548
549 func (s *state) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
550
551 s.at(variable)
552 value := s.varValue(variable.Ident[0])
553 if len(variable.Ident) == 1 {
554 s.notAFunction(args, final)
555 return value
556 }
557 return s.evalFieldChain(dot, value, variable, variable.Ident[1:], args, final)
558 }
559
560
561
562
563 func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
564 n := len(ident)
565 for i := 0; i < n-1; i++ {
566 receiver = s.evalField(dot, ident[i], node, nil, missingVal, receiver)
567 }
568
569 return s.evalField(dot, ident[n-1], node, args, final, receiver)
570 }
571
572 func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
573 s.at(node)
574 name := node.Ident
575 function, ok := findFunction(name, s.tmpl)
576 if !ok {
577 s.errorf("%q is not a defined function", name)
578 }
579 return s.evalCall(dot, function, cmd, name, args, final)
580 }
581
582
583
584
585 func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
586 if !receiver.IsValid() {
587 if s.tmpl.option.missingKey == mapError {
588 s.errorf("nil data; no entry for key %q", fieldName)
589 }
590 return zero
591 }
592 typ := receiver.Type()
593 receiver, isNil := indirect(receiver)
594 if receiver.Kind() == reflect.Interface && isNil {
595
596
597 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
598 return zero
599 }
600
601
602
603 ptr := receiver
604 if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Ptr && ptr.CanAddr() {
605 ptr = ptr.Addr()
606 }
607 if method := ptr.MethodByName(fieldName); method.IsValid() {
608 return s.evalCall(dot, method, node, fieldName, args, final)
609 }
610 hasArgs := len(args) > 1 || final != missingVal
611
612 switch receiver.Kind() {
613 case reflect.Struct:
614 tField, ok := receiver.Type().FieldByName(fieldName)
615 if ok {
616 field := receiver.FieldByIndex(tField.Index)
617 if !tField.IsExported() {
618 s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
619 }
620
621 if hasArgs {
622 s.errorf("%s has arguments but cannot be invoked as function", fieldName)
623 }
624 return field
625 }
626 case reflect.Map:
627
628 nameVal := reflect.ValueOf(fieldName)
629 if nameVal.Type().AssignableTo(receiver.Type().Key()) {
630 if hasArgs {
631 s.errorf("%s is not a method but has arguments", fieldName)
632 }
633 result := receiver.MapIndex(nameVal)
634 if !result.IsValid() {
635 switch s.tmpl.option.missingKey {
636 case mapInvalid:
637
638 case mapZeroValue:
639 result = reflect.Zero(receiver.Type().Elem())
640 case mapError:
641 s.errorf("map has no entry for key %q", fieldName)
642 }
643 }
644 return result
645 }
646 case reflect.Ptr:
647 etyp := receiver.Type().Elem()
648 if etyp.Kind() == reflect.Struct {
649 if _, ok := etyp.FieldByName(fieldName); !ok {
650
651
652 break
653 }
654 }
655 if isNil {
656 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
657 }
658 }
659 s.errorf("can't evaluate field %s in type %s", fieldName, typ)
660 panic("not reached")
661 }
662
663 var (
664 errorType = reflect.TypeOf((*error)(nil)).Elem()
665 fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
666 reflectValueType = reflect.TypeOf((*reflect.Value)(nil)).Elem()
667 )
668
669
670
671
672 func (s *state) evalCall(dot, fun reflect.Value, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value {
673 if args != nil {
674 args = args[1:]
675 }
676 typ := fun.Type()
677 numIn := len(args)
678 if final != missingVal {
679 numIn++
680 }
681 numFixed := len(args)
682 if typ.IsVariadic() {
683 numFixed = typ.NumIn() - 1
684 if numIn < numFixed {
685 s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
686 }
687 } else if numIn != typ.NumIn() {
688 s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), numIn)
689 }
690 if !goodFunc(typ) {
691
692 s.errorf("can't call method/function %q with %d results", name, typ.NumOut())
693 }
694
695 argv := make([]reflect.Value, numIn)
696
697 i := 0
698 for ; i < numFixed && i < len(args); i++ {
699 argv[i] = s.evalArg(dot, typ.In(i), args[i])
700 }
701
702 if typ.IsVariadic() {
703 argType := typ.In(typ.NumIn() - 1).Elem()
704 for ; i < len(args); i++ {
705 argv[i] = s.evalArg(dot, argType, args[i])
706 }
707 }
708
709 if final != missingVal {
710 t := typ.In(typ.NumIn() - 1)
711 if typ.IsVariadic() {
712 if numIn-1 < numFixed {
713
714
715 t = typ.In(numIn - 1)
716 } else {
717
718
719 t = t.Elem()
720 }
721 }
722 argv[i] = s.validateType(final, t)
723 }
724 v, err := safeCall(fun, argv)
725
726
727 if err != nil {
728 s.at(node)
729 s.errorf("error calling %s: %w", name, err)
730 }
731 if v.Type() == reflectValueType {
732 v = v.Interface().(reflect.Value)
733 }
734 return v
735 }
736
737
738 func canBeNil(typ reflect.Type) bool {
739 switch typ.Kind() {
740 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
741 return true
742 case reflect.Struct:
743 return typ == reflectValueType
744 }
745 return false
746 }
747
748
749 func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
750 if !value.IsValid() {
751 if typ == nil {
752
753 return reflect.ValueOf(nil)
754 }
755 if canBeNil(typ) {
756
757 return reflect.Zero(typ)
758 }
759 s.errorf("invalid value; expected %s", typ)
760 }
761 if typ == reflectValueType && value.Type() != typ {
762 return reflect.ValueOf(value)
763 }
764 if typ != nil && !value.Type().AssignableTo(typ) {
765 if value.Kind() == reflect.Interface && !value.IsNil() {
766 value = value.Elem()
767 if value.Type().AssignableTo(typ) {
768 return value
769 }
770
771 }
772
773
774
775
776 switch {
777 case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
778 value = value.Elem()
779 if !value.IsValid() {
780 s.errorf("dereference of nil pointer of type %s", typ)
781 }
782 case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
783 value = value.Addr()
784 default:
785 s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
786 }
787 }
788 return value
789 }
790
791 func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
792 s.at(n)
793 switch arg := n.(type) {
794 case *parse.DotNode:
795 return s.validateType(dot, typ)
796 case *parse.NilNode:
797 if canBeNil(typ) {
798 return reflect.Zero(typ)
799 }
800 s.errorf("cannot assign nil to %s", typ)
801 case *parse.FieldNode:
802 return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, missingVal), typ)
803 case *parse.VariableNode:
804 return s.validateType(s.evalVariableNode(dot, arg, nil, missingVal), typ)
805 case *parse.PipeNode:
806 return s.validateType(s.evalPipeline(dot, arg), typ)
807 case *parse.IdentifierNode:
808 return s.validateType(s.evalFunction(dot, arg, arg, nil, missingVal), typ)
809 case *parse.ChainNode:
810 return s.validateType(s.evalChainNode(dot, arg, nil, missingVal), typ)
811 }
812 switch typ.Kind() {
813 case reflect.Bool:
814 return s.evalBool(typ, n)
815 case reflect.Complex64, reflect.Complex128:
816 return s.evalComplex(typ, n)
817 case reflect.Float32, reflect.Float64:
818 return s.evalFloat(typ, n)
819 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
820 return s.evalInteger(typ, n)
821 case reflect.Interface:
822 if typ.NumMethod() == 0 {
823 return s.evalEmptyInterface(dot, n)
824 }
825 case reflect.Struct:
826 if typ == reflectValueType {
827 return reflect.ValueOf(s.evalEmptyInterface(dot, n))
828 }
829 case reflect.String:
830 return s.evalString(typ, n)
831 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
832 return s.evalUnsignedInteger(typ, n)
833 }
834 s.errorf("can't handle %s for arg of type %s", n, typ)
835 panic("not reached")
836 }
837
838 func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
839 s.at(n)
840 if n, ok := n.(*parse.BoolNode); ok {
841 value := reflect.New(typ).Elem()
842 value.SetBool(n.True)
843 return value
844 }
845 s.errorf("expected bool; found %s", n)
846 panic("not reached")
847 }
848
849 func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
850 s.at(n)
851 if n, ok := n.(*parse.StringNode); ok {
852 value := reflect.New(typ).Elem()
853 value.SetString(n.Text)
854 return value
855 }
856 s.errorf("expected string; found %s", n)
857 panic("not reached")
858 }
859
860 func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
861 s.at(n)
862 if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
863 value := reflect.New(typ).Elem()
864 value.SetInt(n.Int64)
865 return value
866 }
867 s.errorf("expected integer; found %s", n)
868 panic("not reached")
869 }
870
871 func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
872 s.at(n)
873 if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
874 value := reflect.New(typ).Elem()
875 value.SetUint(n.Uint64)
876 return value
877 }
878 s.errorf("expected unsigned integer; found %s", n)
879 panic("not reached")
880 }
881
882 func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
883 s.at(n)
884 if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
885 value := reflect.New(typ).Elem()
886 value.SetFloat(n.Float64)
887 return value
888 }
889 s.errorf("expected float; found %s", n)
890 panic("not reached")
891 }
892
893 func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
894 if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
895 value := reflect.New(typ).Elem()
896 value.SetComplex(n.Complex128)
897 return value
898 }
899 s.errorf("expected complex; found %s", n)
900 panic("not reached")
901 }
902
903 func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
904 s.at(n)
905 switch n := n.(type) {
906 case *parse.BoolNode:
907 return reflect.ValueOf(n.True)
908 case *parse.DotNode:
909 return dot
910 case *parse.FieldNode:
911 return s.evalFieldNode(dot, n, nil, missingVal)
912 case *parse.IdentifierNode:
913 return s.evalFunction(dot, n, n, nil, missingVal)
914 case *parse.NilNode:
915
916 s.errorf("evalEmptyInterface: nil (can't happen)")
917 case *parse.NumberNode:
918 return s.idealConstant(n)
919 case *parse.StringNode:
920 return reflect.ValueOf(n.Text)
921 case *parse.VariableNode:
922 return s.evalVariableNode(dot, n, nil, missingVal)
923 case *parse.PipeNode:
924 return s.evalPipeline(dot, n)
925 }
926 s.errorf("can't handle assignment of %s to empty interface argument", n)
927 panic("not reached")
928 }
929
930
931
932
933 func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
934 for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
935 if v.IsNil() {
936 return v, true
937 }
938 }
939 return v, false
940 }
941
942
943
944
945
946 func indirectInterface(v reflect.Value) reflect.Value {
947 if v.Kind() != reflect.Interface {
948 return v
949 }
950 if v.IsNil() {
951 return reflect.Value{}
952 }
953 return v.Elem()
954 }
955
956
957
958 func (s *state) printValue(n parse.Node, v reflect.Value) {
959 s.at(n)
960 iface, ok := printableValue(v)
961 if !ok {
962 s.errorf("can't print %s of type %s", n, v.Type())
963 }
964 _, err := fmt.Fprint(s.wr, iface)
965 if err != nil {
966 s.writeError(err)
967 }
968 }
969
970
971
972 func printableValue(v reflect.Value) (interface{}, bool) {
973 if v.Kind() == reflect.Ptr {
974 v, _ = indirect(v)
975 }
976 if !v.IsValid() {
977 return "<no value>", true
978 }
979
980 if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
981 if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
982 v = v.Addr()
983 } else {
984 switch v.Kind() {
985 case reflect.Chan, reflect.Func:
986 return nil, false
987 }
988 }
989 }
990 return v.Interface(), true
991 }
992
View as plain text