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