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