Debian Codegraph @

template/gotext/exec.go

raw
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 gotext
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "io"
12 "reflect"
13 "runtime"
14 "strings"
15 "sync/atomic"
16 "text/template/parse"
17
18 "heckel.io/ntfy/v2/template/gotext/fmtsort"
19 )
20
21 // maxExecDepth specifies the maximum stack depth of templates within
22 // templates. This limit is only practically reached by accidentally
23 // recursive template invocations. This limit allows us to return
24 // an error instead of triggering a stack overflow.
25 var maxExecDepth = initMaxExecDepth()
26
27 func initMaxExecDepth() int {
28 if runtime.GOARCH == "wasm" {
29 return 1000
30 }
31 return 100000
32 }
33
34 // state represents the state of an execution. It's not part of the
35 // template so that multiple executions of the same template
36 // can execute in parallel.
37 type state struct {
38 tmpl *Template
39 ctx context.Context // ctx-ex: execution context; Execute uses context.Background.
40 wr io.Writer
41 node parse.Node // current node, for errors
42 vars []variable // push-down stack of variable values.
43 depth int // the height of the stack of executing templates.
44 cancelled *atomic.Bool // ctx-ex: shared flag set by the context.AfterFunc watcher; nil if ctx cannot be canceled
45 }
46
47 // variable holds the dynamic value of a variable such as $, $x etc.
48 type variable struct {
49 name string
50 value reflect.Value
51 }
52
53 // push pushes a new variable on the stack.
54 func (s *state) push(name string, value reflect.Value) {
55 s.vars = append(s.vars, variable{name, value})
56 }
57
58 // mark returns the length of the variable stack.
59 func (s *state) mark() int {
60 return len(s.vars)
61 }
62
63 // pop pops the variable stack up to the mark.
64 func (s *state) pop(mark int) {
65 s.vars = s.vars[0:mark]
66 }
67
68 // setVar overwrites the last declared variable with the given name.
69 // Used by variable assignments.
70 func (s *state) setVar(name string, value reflect.Value) {
71 for i := s.mark() - 1; i >= 0; i-- {
72 if s.vars[i].name == name {
73 s.vars[i].value = value
74 return
75 }
76 }
77 s.errorf("undefined variable: %s", name)
78 }
79
80 // setTopVar overwrites the top-nth variable on the stack. Used by range iterations.
81 func (s *state) setTopVar(n int, value reflect.Value) {
82 s.vars[len(s.vars)-n].value = value
83 }
84
85 // varValue returns the value of the named variable.
86 func (s *state) varValue(name string) reflect.Value {
87 for i := s.mark() - 1; i >= 0; i-- {
88 if s.vars[i].name == name {
89 return s.vars[i].value
90 }
91 }
92 s.errorf("undefined variable: %s", name)
93 return zero
94 }
95
96 var zero reflect.Value
97
98 type missingValType struct{}
99
100 var missingVal = reflect.ValueOf(missingValType{})
101
102 var missingValReflectType = reflect.TypeFor[missingValType]()
103
104 func isMissing(v reflect.Value) bool {
105 return v.IsValid() && v.Type() == missingValReflectType
106 }
107
108 // at marks the state to be on node n, for error reporting.
109 func (s *state) at(node parse.Node) {
110 s.node = node
111 }
112
113 // doublePercent returns the string with %'s replaced by %%, if necessary,
114 // so it can be used safely inside a Printf format string.
115 func doublePercent(str string) string {
116 return strings.ReplaceAll(str, "%", "%%")
117 }
118
119 // TODO: It would be nice if ExecError was more broken down, but
120 // the way ErrorContext embeds the template name makes the
121 // processing too clumsy.
122
123 // ExecError is the custom error type returned when Execute has an
124 // error evaluating its template. (If a write error occurs, the actual
125 // error is returned; it will not be of type ExecError.)
126 type ExecError struct {
127 Name string // Name of template.
128 Err error // Pre-formatted error.
129 }
130
131 func (e ExecError) Error() string {
132 return e.Err.Error()
133 }
134
135 func (e ExecError) Unwrap() error {
136 return e.Err
137 }
138
139 // errorf records an ExecError and terminates processing.
140 func (s *state) errorf(format string, args ...any) {
141 name := doublePercent(s.tmpl.Name())
142 if s.node == nil {
143 format = fmt.Sprintf("template: %s: %s", name, format)
144 } else {
145 location, context := s.tmpl.ErrorContext(s.node)
146 format = fmt.Sprintf("template: %s: executing %q at <%s>: %s", location, name, doublePercent(context), format)
147 }
148 panic(ExecError{
149 Name: s.tmpl.Name(),
150 Err: fmt.Errorf(format, args...),
151 })
152 }
153
154 // writeError is the wrapper type used internally when Execute has an
155 // error writing to its output. We strip the wrapper in errRecover.
156 // Note that this is not an implementation of error, so it cannot escape
157 // from the package as an error value.
158 type writeError struct {
159 Err error // Original error.
160 }
161
162 func (s *state) writeError(err error) {
163 panic(writeError{
164 Err: err,
165 })
166 }
167
168 // cancelError is the wrapper type used internally when execution is aborted
169 // because the context is done. Like writeError, it is stripped in errRecover
170 // so the caller receives the original ctx.Err(). It is not an implementation
171 // of error, so it cannot escape from the package as an error value.
172 type cancelError struct {
173 Err error // Original context error.
174 }
175
176 // errRecover is the handler that turns panics into returns from the top
177 // level of Parse.
178 func errRecover(errp *error) {
179 e := recover()
180 if e != nil {
181 switch err := e.(type) {
182 case runtime.Error:
183 panic(e)
184 case writeError:
185 *errp = err.Err // Strip the wrapper.
186 case cancelError:
187 *errp = err.Err // Strip the wrapper; return the context error.
188 case ExecError:
189 *errp = err // Keep the wrapper.
190 default:
191 panic(e)
192 }
193 }
194 }
195
196 // ExecuteTemplate applies the template associated with t that has the given name
197 // to the specified data object and writes the output to wr.
198 // If an error occurs executing the template or writing its output,
199 // execution stops, but partial results may already have been written to
200 // the output writer.
201 // A template may be executed safely in parallel, although if parallel
202 // executions share a Writer the output may be interleaved.
203 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error {
204 return t.ExecuteTemplateContext(context.Background(), wr, name, data)
205 }
206
207 // ExecuteTemplateContext is like [Template.ExecuteTemplate], but aborts and
208 // returns ctx.Err() if ctx is canceled or its deadline is exceeded before
209 // execution completes. See [Template.ExecuteContext] for the cancellation
210 // semantics.
211 func (t *Template) ExecuteTemplateContext(ctx context.Context, wr io.Writer, name string, data any) error {
212 tmpl := t.Lookup(name)
213 if tmpl == nil {
214 return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
215 }
216 return tmpl.ExecuteContext(ctx, wr, data)
217 }
218
219 // Execute applies a parsed template to the specified data object,
220 // and writes the output to wr.
221 // If an error occurs executing the template or writing its output,
222 // execution stops, but partial results may already have been written to
223 // the output writer.
224 // A template may be executed safely in parallel, although if parallel
225 // executions share a Writer the output may be interleaved.
226 //
227 // If data is a [reflect.Value], the template applies to the concrete
228 // value that the reflect.Value holds, as in [fmt.Print].
229 func (t *Template) Execute(wr io.Writer, data any) error {
230 return t.executeContext(context.Background(), wr, data)
231 }
232
233 // ExecuteContext is like [Template.Execute], but aborts and returns ctx.Err()
234 // (either [context.Canceled] or [context.DeadlineExceeded], retrievable with
235 // [errors.Is]) if ctx is canceled or its deadline is exceeded before execution
236 // completes.
237 //
238 // Cancellation is observed between node evaluations as the template is walked,
239 // so long-running renders -- including tight or nested {{range}} loops that
240 // write no output -- are aborted promptly. A template blocked inside a single
241 // function call is not interrupted until that call returns. Partial results may
242 // already have been written to wr.
243 func (t *Template) ExecuteContext(ctx context.Context, wr io.Writer, data any) error {
244 if err := ctx.Err(); err != nil {
245 return err
246 }
247 return t.executeContext(ctx, wr, data)
248 }
249
250 func (t *Template) executeContext(ctx context.Context, wr io.Writer, data any) (err error) {
251 defer errRecover(&err)
252 value, ok := data.(reflect.Value)
253 if !ok {
254 value = reflect.ValueOf(data)
255 }
256 state := &state{
257 tmpl: t,
258 ctx: ctx,
259 wr: wr,
260 vars: []variable{{"$", value}},
261 }
262 // If the context can be canceled, watch it with a single context.AfterFunc
263 // callback that flips an atomic flag; walk polls that flag per node (a cheap
264 // monomorphic atomic load) instead of calling ctx.Err() every node.
265 // Contexts that can never be canceled (Background, TODO) have a nil Done
266 // channel, so the default Execute path installs nothing and pays nothing.
267 if ctx.Done() != nil {
268 state.cancelled = new(atomic.Bool)
269 stop := context.AfterFunc(ctx, func() { state.cancelled.Store(true) })
270 defer stop()
271 }
272 if t.Tree == nil || t.Root == nil {
273 state.errorf("%q is an incomplete or empty template", t.Name())
274 }
275 state.walk(value, t.Root)
276 return
277 }
278
279 // DefinedTemplates returns a string listing the defined templates,
280 // prefixed by the string "; defined templates are: ". If there are none,
281 // it returns the empty string. For generating an error message here
282 // and in [html/template].
283 func (t *Template) DefinedTemplates() string {
284 if t.common == nil {
285 return ""
286 }
287 var b strings.Builder
288 t.muTmpl.RLock()
289 defer t.muTmpl.RUnlock()
290 for name, tmpl := range t.tmpl {
291 if tmpl.Tree == nil || tmpl.Root == nil {
292 continue
293 }
294 if b.Len() == 0 {
295 b.WriteString("; defined templates are: ")
296 } else {
297 b.WriteString(", ")
298 }
299 fmt.Fprintf(&b, "%q", name)
300 }
301 return b.String()
302 }
303
304 // Sentinel errors for use with panic to signal early exits from range loops.
305 var (
306 walkBreak = errors.New("break")
307 walkContinue = errors.New("continue")
308 )
309
310 // Walk functions step through the major pieces of the template structure,
311 // generating output as they go.
312 func (s *state) walk(dot reflect.Value, node parse.Node) {
313 s.at(node)
314 // Abort if the context has been canceled or its deadline has passed. The
315 // flag is set by the watcher installed in executeContext; observing it here
316 // interrupts any template shape, including loops that write no output.
317 if s.cancelled != nil && s.cancelled.Load() {
318 panic(cancelError{s.ctx.Err()})
319 }
320 switch node := node.(type) {
321 case *parse.ActionNode:
322 // Do not pop variables so they persist until next end.
323 // Also, if the action declares variables, don't print the result.
324 val := s.evalPipeline(dot, node.Pipe)
325 if len(node.Pipe.Decl) == 0 {
326 s.printValue(node, val)
327 }
328 case *parse.BreakNode:
329 panic(walkBreak)
330 case *parse.CommentNode:
331 case *parse.ContinueNode:
332 panic(walkContinue)
333 case *parse.IfNode:
334 s.walkIfOrWith(parse.NodeIf, dot, node.Pipe, node.List, node.ElseList)
335 case *parse.ListNode:
336 for _, node := range node.Nodes {
337 s.walk(dot, node)
338 }
339 case *parse.RangeNode:
340 s.walkRange(dot, node)
341 case *parse.TemplateNode:
342 s.walkTemplate(dot, node)
343 case *parse.TextNode:
344 if _, err := s.wr.Write(node.Text); err != nil {
345 s.writeError(err)
346 }
347 case *parse.WithNode:
348 s.walkIfOrWith(parse.NodeWith, dot, node.Pipe, node.List, node.ElseList)
349 default:
350 s.errorf("unknown node: %s", node)
351 }
352 }
353
354 // walkIfOrWith walks an 'if' or 'with' node. The two control structures
355 // are identical in behavior except that 'with' sets dot.
356 func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
357 defer s.pop(s.mark())
358 val := s.evalPipeline(dot, pipe)
359 truth, ok := isTrue(indirectInterface(val))
360 if !ok {
361 s.errorf("if/with can't use %v", val)
362 }
363 if truth {
364 if typ == parse.NodeWith {
365 s.walk(val, list)
366 } else {
367 s.walk(dot, list)
368 }
369 } else if elseList != nil {
370 s.walk(dot, elseList)
371 }
372 }
373
374 // IsTrue reports whether the value is 'true', in the sense of not the zero of its type,
375 // and whether the value has a meaningful truth value. This is the definition of
376 // truth used by if and other such actions.
377 func IsTrue(val any) (truth, ok bool) {
378 return isTrue(reflect.ValueOf(val))
379 }
380
381 func isTrue(val reflect.Value) (truth, ok bool) {
382 if !val.IsValid() {
383 // Something like var x interface{}, never set. It's a form of nil.
384 return false, true
385 }
386 switch val.Kind() {
387 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
388 truth = val.Len() > 0
389 case reflect.Bool:
390 truth = val.Bool()
391 case reflect.Complex64, reflect.Complex128:
392 truth = val.Complex() != 0
393 case reflect.Chan, reflect.Func, reflect.Pointer, reflect.UnsafePointer, reflect.Interface:
394 truth = !val.IsNil()
395 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
396 truth = val.Int() != 0
397 case reflect.Float32, reflect.Float64:
398 truth = val.Float() != 0
399 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
400 truth = val.Uint() != 0
401 case reflect.Struct:
402 truth = true // Struct values are always true.
403 default:
404 return
405 }
406 return truth, true
407 }
408
409 func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
410 s.at(r)
411 defer func() {
412 if r := recover(); r != nil && r != walkBreak {
413 panic(r)
414 }
415 }()
416 defer s.pop(s.mark())
417 val, _ := indirect(s.evalPipeline(dot, r.Pipe))
418 // mark top of stack before any variables in the body are pushed.
419 mark := s.mark()
420 oneIteration := func(index, elem reflect.Value) {
421 if len(r.Pipe.Decl) > 0 {
422 if r.Pipe.IsAssign {
423 // With two variables, index comes first.
424 // With one, we use the element.
425 if len(r.Pipe.Decl) > 1 {
426 s.setVar(r.Pipe.Decl[0].Ident[0], index)
427 } else {
428 s.setVar(r.Pipe.Decl[0].Ident[0], elem)
429 }
430 } else {
431 // Set top var (lexically the second if there
432 // are two) to the element.
433 s.setTopVar(1, elem)
434 }
435 }
436 if len(r.Pipe.Decl) > 1 {
437 if r.Pipe.IsAssign {
438 s.setVar(r.Pipe.Decl[1].Ident[0], elem)
439 } else {
440 // Set next var (lexically the first if there
441 // are two) to the index.
442 s.setTopVar(2, index)
443 }
444 }
445 defer s.pop(mark)
446 defer func() {
447 // Consume panic(walkContinue)
448 if r := recover(); r != nil && r != walkContinue {
449 panic(r)
450 }
451 }()
452 s.walk(elem, r.List)
453 }
454 switch val.Kind() {
455 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
456 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
457 if len(r.Pipe.Decl) > 1 {
458 s.errorf("can't use %v to iterate over more than one variable", val)
459 break
460 }
461 run := false
462 for v := range val.Seq() {
463 run = true
464 // Pass element as second value, as we do for channels.
465 oneIteration(reflect.Value{}, v)
466 }
467 if !run {
468 break
469 }
470 return
471 case reflect.Array, reflect.Slice:
472 if val.Len() == 0 {
473 break
474 }
475 for i := 0; i < val.Len(); i++ {
476 oneIteration(reflect.ValueOf(i), val.Index(i))
477 }
478 return
479 case reflect.Map:
480 if val.Len() == 0 {
481 break
482 }
483 om := fmtsort.Sort(val)
484 for _, m := range om {
485 oneIteration(m.Key, m.Value)
486 }
487 return
488 case reflect.Chan:
489 if val.IsNil() {
490 break
491 }
492 if val.Type().ChanDir() == reflect.SendDir {
493 s.errorf("range over send-only channel %v", val)
494 break
495 }
496 i := 0
497 for ; ; i++ {
498 elem, ok := val.Recv()
499 if !ok {
500 break
501 }
502 oneIteration(reflect.ValueOf(i), elem)
503 }
504 if i == 0 {
505 break
506 }
507 return
508 case reflect.Invalid:
509 break // An invalid value is likely a nil map, etc. and acts like an empty map.
510 case reflect.Func:
511 if val.Type().CanSeq() {
512 if len(r.Pipe.Decl) > 1 {
513 s.errorf("can't use %v iterate over more than one variable", val)
514 break
515 }
516 run := false
517 for v := range val.Seq() {
518 run = true
519 // Pass element as second value,
520 // as we do for channels.
521 oneIteration(reflect.Value{}, v)
522 }
523 if !run {
524 break
525 }
526 return
527 }
528 if val.Type().CanSeq2() {
529 run := false
530 for i, v := range val.Seq2() {
531 run = true
532 if len(r.Pipe.Decl) > 1 {
533 oneIteration(i, v)
534 } else {
535 // If there is only one range variable,
536 // oneIteration will use the
537 // second value.
538 oneIteration(reflect.Value{}, i)
539 }
540 }
541 if !run {
542 break
543 }
544 return
545 }
546 fallthrough
547 default:
548 s.errorf("range can't iterate over %v", val)
549 }
550 if r.ElseList != nil {
551 s.walk(dot, r.ElseList)
552 }
553 }
554
555 func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
556 s.at(t)
557 tmpl := s.tmpl.Lookup(t.Name)
558 if tmpl == nil {
559 s.errorf("template %q not defined", t.Name)
560 }
561 if s.depth == maxExecDepth {
562 s.errorf("exceeded maximum template depth (%v)", maxExecDepth)
563 }
564 // Variables declared by the pipeline persist.
565 dot = s.evalPipeline(dot, t.Pipe)
566 newState := *s
567 newState.depth++
568 newState.tmpl = tmpl
569 // No dynamic scoping: template invocations inherit no variables.
570 newState.vars = []variable{{"$", dot}}
571 newState.walk(dot, tmpl.Root)
572 }
573
574 // Eval functions evaluate pipelines, commands, and their elements and extract
575 // values from the data structure by examining fields, calling methods, and so on.
576 // The printing of those values happens only through walk functions.
577
578 // evalPipeline returns the value acquired by evaluating a pipeline. If the
579 // pipeline has a variable declaration, the variable will be pushed on the
580 // stack. Callers should therefore pop the stack after they are finished
581 // executing commands depending on the pipeline value.
582 func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
583 if pipe == nil {
584 return
585 }
586 s.at(pipe)
587 value = missingVal
588 for _, cmd := range pipe.Cmds {
589 value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
590 // If the object has type interface{}, dig down one level to the thing inside.
591 if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
592 value = value.Elem()
593 }
594 }
595 for _, variable := range pipe.Decl {
596 if pipe.IsAssign {
597 s.setVar(variable.Ident[0], value)
598 } else {
599 s.push(variable.Ident[0], value)
600 }
601 }
602 return value
603 }
604
605 func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
606 if len(args) > 1 || !isMissing(final) {
607 s.errorf("can't give argument to non-function %s", args[0])
608 }
609 }
610
611 func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
612 firstWord := cmd.Args[0]
613 switch n := firstWord.(type) {
614 case *parse.FieldNode:
615 return s.evalFieldNode(dot, n, cmd.Args, final)
616 case *parse.ChainNode:
617 return s.evalChainNode(dot, n, cmd.Args, final)
618 case *parse.IdentifierNode:
619 // Must be a function.
620 return s.evalFunction(dot, n, cmd, cmd.Args, final)
621 case *parse.PipeNode:
622 // Parenthesized pipeline. The arguments are all inside the pipeline; final must be absent.
623 s.notAFunction(cmd.Args, final)
624 return s.evalPipeline(dot, n)
625 case *parse.VariableNode:
626 return s.evalVariableNode(dot, n, cmd.Args, final)
627 }
628 s.at(firstWord)
629 s.notAFunction(cmd.Args, final)
630 switch word := firstWord.(type) {
631 case *parse.BoolNode:
632 return reflect.ValueOf(word.True)
633 case *parse.DotNode:
634 return dot
635 case *parse.NilNode:
636 s.errorf("nil is not a command")
637 case *parse.NumberNode:
638 return s.idealConstant(word)
639 case *parse.StringNode:
640 return reflect.ValueOf(word.Text)
641 }
642 s.errorf("can't evaluate command %q", firstWord)
643 panic("not reached")
644 }
645
646 // idealConstant is called to return the value of a number in a context where
647 // we don't know the type. In that case, the syntax of the number tells us
648 // its type, and we use Go rules to resolve. Note there is no such thing as
649 // a uint ideal constant in this situation - the value must be of int type.
650 func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
651 // These are ideal constants but we don't know the type
652 // and we have no context. (If it was a method argument,
653 // we'd know what we need.) The syntax guides us to some extent.
654 s.at(constant)
655 switch {
656 case constant.IsComplex:
657 return reflect.ValueOf(constant.Complex128) // incontrovertible.
658
659 case constant.IsFloat &&
660 !isHexInt(constant.Text) && !isRuneInt(constant.Text) &&
661 strings.ContainsAny(constant.Text, ".eEpP"):
662 return reflect.ValueOf(constant.Float64)
663
664 case constant.IsInt:
665 n := int(constant.Int64)
666 if int64(n) != constant.Int64 {
667 s.errorf("%s overflows int", constant.Text)
668 }
669 return reflect.ValueOf(n)
670
671 case constant.IsUint:
672 s.errorf("%s overflows int", constant.Text)
673 }
674 return zero
675 }
676
677 func isRuneInt(s string) bool {
678 return len(s) > 0 && s[0] == '\''
679 }
680
681 func isHexInt(s string) bool {
682 return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') && !strings.ContainsAny(s, "pP")
683 }
684
685 func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
686 s.at(field)
687 return s.evalFieldChain(dot, dot, field, field.Ident, args, final)
688 }
689
690 func (s *state) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value {
691 s.at(chain)
692 if len(chain.Field) == 0 {
693 s.errorf("internal error: no fields in evalChainNode")
694 }
695 if chain.Node.Type() == parse.NodeNil {
696 s.errorf("indirection through explicit nil in %s", chain)
697 }
698 // (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields.
699 pipe := s.evalArg(dot, nil, chain.Node)
700 return s.evalFieldChain(dot, pipe, chain, chain.Field, args, final)
701 }
702
703 func (s *state) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
704 // $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
705 s.at(variable)
706 value := s.varValue(variable.Ident[0])
707 if len(variable.Ident) == 1 {
708 s.notAFunction(args, final)
709 return value
710 }
711 return s.evalFieldChain(dot, value, variable, variable.Ident[1:], args, final)
712 }
713
714 // evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
715 // dot is the environment in which to evaluate arguments, while
716 // receiver is the value being walked along the chain.
717 func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
718 n := len(ident)
719 for i := 0; i < n-1; i++ {
720 receiver = s.evalField(dot, ident[i], node, nil, missingVal, receiver)
721 }
722 // Now if it's a method, it gets the arguments.
723 return s.evalField(dot, ident[n-1], node, args, final, receiver)
724 }
725
726 func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
727 s.at(node)
728 name := node.Ident
729 function, isBuiltin, ok := findFunction(name, s.tmpl)
730 if !ok {
731 s.errorf("%q is not a defined function", name)
732 }
733 return s.evalCall(dot, function, isBuiltin, cmd, name, args, final)
734 }
735
736 // evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
737 // The 'final' argument represents the return value from the preceding
738 // value of the pipeline, if any.
739 func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
740 if !receiver.IsValid() {
741 if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key.
742 s.errorf("nil data; no entry for key %q", fieldName)
743 }
744 return zero
745 }
746 typ := receiver.Type()
747 receiver, isNil := indirect(receiver)
748 if receiver.Kind() == reflect.Interface && isNil {
749 // Calling a method on a nil interface can't work. The
750 // MethodByName method call below would panic.
751 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
752 return zero
753 }
754
755 // Unless it's an interface, need to get to a value of type *T to guarantee
756 // we see all methods of T and *T.
757 ptr := receiver
758 if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Pointer && ptr.CanAddr() {
759 ptr = ptr.Addr()
760 }
761 if method := ptr.MethodByName(fieldName); method.IsValid() {
762 return s.evalCall(dot, method, false, node, fieldName, args, final)
763 }
764 hasArgs := len(args) > 1 || !isMissing(final)
765 // It's not a method; must be a field of a struct or an element of a map.
766 switch receiver.Kind() {
767 case reflect.Struct:
768 tField, ok := receiver.Type().FieldByName(fieldName)
769 if ok {
770 field, err := receiver.FieldByIndexErr(tField.Index)
771 if !tField.IsExported() {
772 s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
773 }
774 if err != nil {
775 s.errorf("%v", err)
776 }
777 // If it's a function, we must call it.
778 if hasArgs {
779 s.errorf("%s has arguments but cannot be invoked as function", fieldName)
780 }
781 return field
782 }
783 case reflect.Map:
784 // If it's a map, attempt to use the field name as a key.
785 nameVal := reflect.ValueOf(fieldName)
786 if nameVal.Type().AssignableTo(receiver.Type().Key()) {
787 if hasArgs {
788 s.errorf("%s is not a method but has arguments", fieldName)
789 }
790 result := receiver.MapIndex(nameVal)
791 if !result.IsValid() {
792 switch s.tmpl.option.missingKey {
793 case mapInvalid:
794 // Just use the invalid value.
795 case mapZeroValue:
796 result = reflect.Zero(receiver.Type().Elem())
797 case mapError:
798 s.errorf("map has no entry for key %q", fieldName)
799 }
800 }
801 return result
802 }
803 case reflect.Pointer:
804 etyp := receiver.Type().Elem()
805 if etyp.Kind() == reflect.Struct {
806 if _, ok := etyp.FieldByName(fieldName); !ok {
807 // If there's no such field, say "can't evaluate"
808 // instead of "nil pointer evaluating".
809 break
810 }
811 }
812 if isNil {
813 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
814 }
815 }
816 s.errorf("can't evaluate field %s in type %s", fieldName, typ)
817 panic("not reached")
818 }
819
820 var (
821 errorType = reflect.TypeFor[error]()
822 fmtStringerType = reflect.TypeFor[fmt.Stringer]()
823 reflectValueType = reflect.TypeFor[reflect.Value]()
824 )
825
826 // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
827 // it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
828 // as the function itself.
829 func (s *state) evalCall(dot, fun reflect.Value, isBuiltin bool, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value {
830 if args != nil {
831 args = args[1:] // Zeroth arg is function name/node; not passed to function.
832 }
833 typ := fun.Type()
834 numIn := len(args)
835 if !isMissing(final) {
836 numIn++
837 }
838 numFixed := len(args)
839 if typ.IsVariadic() {
840 numFixed = typ.NumIn() - 1 // last arg is the variadic one.
841 if numIn < numFixed {
842 s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
843 }
844 } else if numIn != typ.NumIn() {
845 s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), numIn)
846 }
847 if err := goodFunc(name, typ); err != nil {
848 s.errorf("%v", err)
849 }
850
851 unwrap := func(v reflect.Value) reflect.Value {
852 if v.Type() == reflectValueType {
853 v = v.Interface().(reflect.Value)
854 }
855 return v
856 }
857
858 // Special case for builtin and/or, which short-circuit.
859 if isBuiltin && (name == "and" || name == "or") {
860 argType := typ.In(0)
861 var v reflect.Value
862 for _, arg := range args {
863 v = s.evalArg(dot, argType, arg).Interface().(reflect.Value)
864 if truth(v) == (name == "or") {
865 // This value was already unwrapped
866 // by the .Interface().(reflect.Value).
867 return v
868 }
869 }
870 if !final.Equal(missingVal) {
871 // The last argument to and/or is coming from
872 // the pipeline. We didn't short circuit on an earlier
873 // argument, so we are going to return this one.
874 // We don't have to evaluate final, but we do
875 // have to check its type. Then, since we are
876 // going to return it, we have to unwrap it.
877 v = unwrap(s.validateType(final, argType))
878 }
879 return v
880 }
881
882 // Build the arg list.
883 argv := make([]reflect.Value, numIn)
884 // Args must be evaluated. Fixed args first.
885 i := 0
886 for ; i < numFixed && i < len(args); i++ {
887 argv[i] = s.evalArg(dot, typ.In(i), args[i])
888 }
889 // Now the ... args.
890 if typ.IsVariadic() {
891 argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
892 for ; i < len(args); i++ {
893 argv[i] = s.evalArg(dot, argType, args[i])
894 }
895 }
896 // Add final value if necessary.
897 if !isMissing(final) {
898 t := typ.In(typ.NumIn() - 1)
899 if typ.IsVariadic() {
900 if numIn-1 < numFixed {
901 // The added final argument corresponds to a fixed parameter of the function.
902 // Validate against the type of the actual parameter.
903 t = typ.In(numIn - 1)
904 } else {
905 // The added final argument corresponds to the variadic part.
906 // Validate against the type of the elements of the variadic slice.
907 t = t.Elem()
908 }
909 }
910 argv[i] = s.validateType(final, t)
911 }
912
913 // Special case for the "call" builtin.
914 // Insert the name of the callee function as the first argument.
915 if isBuiltin && name == "call" {
916 var calleeName string
917 if len(args) == 0 {
918 // final must be present or we would have errored out above.
919 calleeName = final.String()
920 } else {
921 calleeName = args[0].String()
922 }
923 argv = append([]reflect.Value{reflect.ValueOf(calleeName)}, argv...)
924 fun = reflect.ValueOf(call)
925 }
926
927 v, err := safeCall(fun, argv)
928 // If we have an error that is not nil, stop execution and return that
929 // error to the caller.
930 if err != nil {
931 s.at(node)
932 s.errorf("error calling %s: %w", name, err)
933 }
934 return unwrap(v)
935 }
936
937 // canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero.
938 func canBeNil(typ reflect.Type) bool {
939 switch typ.Kind() {
940 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
941 return true
942 case reflect.Struct:
943 return typ == reflectValueType
944 }
945 return false
946 }
947
948 // validateType guarantees that the value is valid and assignable to the type.
949 func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
950 if !value.IsValid() {
951 if typ == nil {
952 // An untyped nil interface{}. Accept as a proper nil value.
953 return reflect.ValueOf(nil)
954 }
955 if canBeNil(typ) {
956 // Like above, but use the zero value of the non-nil type.
957 return reflect.Zero(typ)
958 }
959 s.errorf("invalid value; expected %s", typ)
960 }
961 if typ == reflectValueType && value.Type() != typ {
962 return reflect.ValueOf(value)
963 }
964 if typ != nil && !value.Type().AssignableTo(typ) {
965 if value.Kind() == reflect.Interface && !value.IsNil() {
966 value = value.Elem()
967 if value.Type().AssignableTo(typ) {
968 return value
969 }
970 // fallthrough
971 }
972 // Does one dereference or indirection work? We could do more, as we
973 // do with method receivers, but that gets messy and method receivers
974 // are much more constrained, so it makes more sense there than here.
975 // Besides, one is almost always all you need.
976 switch {
977 case value.Kind() == reflect.Pointer && value.Type().Elem().AssignableTo(typ):
978 value = value.Elem()
979 if !value.IsValid() {
980 s.errorf("dereference of nil pointer of type %s", typ)
981 }
982 case reflect.PointerTo(value.Type()).AssignableTo(typ) && value.CanAddr():
983 value = value.Addr()
984 default:
985 s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
986 }
987 }
988 return value
989 }
990
991 func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
992 s.at(n)
993 switch arg := n.(type) {
994 case *parse.DotNode:
995 return s.validateType(dot, typ)
996 case *parse.NilNode:
997 if canBeNil(typ) {
998 return reflect.Zero(typ)
999 }
1000 s.errorf("cannot assign nil to %s", typ)
1001 case *parse.FieldNode:
1002 return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, missingVal), typ)
1003 case *parse.VariableNode:
1004 return s.validateType(s.evalVariableNode(dot, arg, nil, missingVal), typ)
1005 case *parse.PipeNode:
1006 return s.validateType(s.evalPipeline(dot, arg), typ)
1007 case *parse.IdentifierNode:
1008 return s.validateType(s.evalFunction(dot, arg, arg, nil, missingVal), typ)
1009 case *parse.ChainNode:
1010 return s.validateType(s.evalChainNode(dot, arg, nil, missingVal), typ)
1011 }
1012 switch typ.Kind() {
1013 case reflect.Bool:
1014 return s.evalBool(typ, n)
1015 case reflect.Complex64, reflect.Complex128:
1016 return s.evalComplex(typ, n)
1017 case reflect.Float32, reflect.Float64:
1018 return s.evalFloat(typ, n)
1019 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1020 return s.evalInteger(typ, n)
1021 case reflect.Interface:
1022 if typ.NumMethod() == 0 {
1023 return s.evalEmptyInterface(dot, n)
1024 }
1025 case reflect.Struct:
1026 if typ == reflectValueType {
1027 return reflect.ValueOf(s.evalEmptyInterface(dot, n))
1028 }
1029 case reflect.String:
1030 return s.evalString(typ, n)
1031 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
1032 return s.evalUnsignedInteger(typ, n)
1033 }
1034 s.errorf("can't handle %s for arg of type %s", n, typ)
1035 panic("not reached")
1036 }
1037
1038 func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
1039 s.at(n)
1040 if n, ok := n.(*parse.BoolNode); ok {
1041 value := reflect.New(typ).Elem()
1042 value.SetBool(n.True)
1043 return value
1044 }
1045 s.errorf("expected bool; found %s", n)
1046 panic("not reached")
1047 }
1048
1049 func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
1050 s.at(n)
1051 if n, ok := n.(*parse.StringNode); ok {
1052 value := reflect.New(typ).Elem()
1053 value.SetString(n.Text)
1054 return value
1055 }
1056 s.errorf("expected string; found %s", n)
1057 panic("not reached")
1058 }
1059
1060 func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
1061 s.at(n)
1062 if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
1063 value := reflect.New(typ).Elem()
1064 value.SetInt(n.Int64)
1065 return value
1066 }
1067 s.errorf("expected integer; found %s", n)
1068 panic("not reached")
1069 }
1070
1071 func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
1072 s.at(n)
1073 if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
1074 value := reflect.New(typ).Elem()
1075 value.SetUint(n.Uint64)
1076 return value
1077 }
1078 s.errorf("expected unsigned integer; found %s", n)
1079 panic("not reached")
1080 }
1081
1082 func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
1083 s.at(n)
1084 if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
1085 value := reflect.New(typ).Elem()
1086 value.SetFloat(n.Float64)
1087 return value
1088 }
1089 s.errorf("expected float; found %s", n)
1090 panic("not reached")
1091 }
1092
1093 func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
1094 if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
1095 value := reflect.New(typ).Elem()
1096 value.SetComplex(n.Complex128)
1097 return value
1098 }
1099 s.errorf("expected complex; found %s", n)
1100 panic("not reached")
1101 }
1102
1103 func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
1104 s.at(n)
1105 switch n := n.(type) {
1106 case *parse.BoolNode:
1107 return reflect.ValueOf(n.True)
1108 case *parse.DotNode:
1109 return dot
1110 case *parse.FieldNode:
1111 return s.evalFieldNode(dot, n, nil, missingVal)
1112 case *parse.IdentifierNode:
1113 return s.evalFunction(dot, n, n, nil, missingVal)
1114 case *parse.NilNode:
1115 // NilNode is handled in evalArg, the only place that calls here.
1116 s.errorf("evalEmptyInterface: nil (can't happen)")
1117 case *parse.NumberNode:
1118 return s.idealConstant(n)
1119 case *parse.StringNode:
1120 return reflect.ValueOf(n.Text)
1121 case *parse.VariableNode:
1122 return s.evalVariableNode(dot, n, nil, missingVal)
1123 case *parse.PipeNode:
1124 return s.evalPipeline(dot, n)
1125 }
1126 s.errorf("can't handle assignment of %s to empty interface argument", n)
1127 panic("not reached")
1128 }
1129
1130 // indirect returns the item at the end of indirection, and a bool to indicate
1131 // if it's nil. If the returned bool is true, the returned value's kind will be
1132 // either a pointer or interface.
1133 func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
1134 for ; v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface; v = v.Elem() {
1135 if v.IsNil() {
1136 return v, true
1137 }
1138 }
1139 return v, false
1140 }
1141
1142 // indirectInterface returns the concrete value in an interface value,
1143 // or else the zero reflect.Value.
1144 // That is, if v represents the interface value x, the result is the same as reflect.ValueOf(x):
1145 // the fact that x was an interface value is forgotten.
1146 func indirectInterface(v reflect.Value) reflect.Value {
1147 if v.Kind() != reflect.Interface {
1148 return v
1149 }
1150 if v.IsNil() {
1151 return reflect.Value{}
1152 }
1153 return v.Elem()
1154 }
1155
1156 // printValue writes the textual representation of the value to the output of
1157 // the template.
1158 func (s *state) printValue(n parse.Node, v reflect.Value) {
1159 s.at(n)
1160 iface, ok := printableValue(v)
1161 if !ok {
1162 s.errorf("can't print %s of type %s", n, v.Type())
1163 }
1164 _, err := fmt.Fprint(s.wr, iface)
1165 if err != nil {
1166 s.writeError(err)
1167 }
1168 }
1169
1170 // printableValue returns the, possibly indirected, interface value inside v that
1171 // is best for a call to formatted printer.
1172 func printableValue(v reflect.Value) (any, bool) {
1173 if v.Kind() == reflect.Pointer {
1174 v, _ = indirect(v) // fmt.Fprint handles nil.
1175 }
1176 if !v.IsValid() {
1177 return "<no value>", true
1178 }
1179
1180 if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
1181 if v.CanAddr() && (reflect.PointerTo(v.Type()).Implements(errorType) || reflect.PointerTo(v.Type()).Implements(fmtStringerType)) {
1182 v = v.Addr()
1183 } else {
1184 switch v.Kind() {
1185 case reflect.Chan, reflect.Func:
1186 return nil, false
1187 }
1188 }
1189 }
1190 return v.Interface(), true
1191 }