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.
17 // state represents the state of an execution. It's not part of the
18 // template so that multiple executions of the same template
19 // can execute in parallel.
23 line int // line number for errors
24 vars []variable // push-down stack of variable values.
27 // variable holds the dynamic value of a variable such as $, $x etc.
28 type variable struct {
33 // push pushes a new variable on the stack.
34 func (s *state) push(name string, value reflect.Value) {
35 s.vars = append(s.vars, variable{name, value})
38 // mark returns the length of the variable stack.
39 func (s *state) mark() int {
43 // pop pops the variable stack up to the mark.
44 func (s *state) pop(mark int) {
45 s.vars = s.vars[0:mark]
48 // setVar overwrites the top-nth variable on the stack. Used by range iterations.
49 func (s *state) setVar(n int, value reflect.Value) {
50 s.vars[len(s.vars)-n].value = value
53 // varValue returns the value of the named variable.
54 func (s *state) varValue(name string) reflect.Value {
55 for i := s.mark() - 1; i >= 0; i-- {
56 if s.vars[i].name == name {
57 return s.vars[i].value
60 s.errorf("undefined variable: %s", name)
64 var zero reflect.Value
66 // errorf formats the error and terminates processing.
67 func (s *state) errorf(format string, args ...interface{}) {
68 format = fmt.Sprintf("template: %s:%d: %s", s.tmpl.Name(), s.line, format)
69 panic(fmt.Errorf(format, args...))
72 // error terminates processing.
73 func (s *state) error(err error) {
77 // errRecover is the handler that turns panics into returns from the top
79 func errRecover(errp *error) {
82 switch err := e.(type) {
93 // ExecuteTemplate applies the template associated with t that has the given name
94 // to the specified data object and writes the output to wr.
95 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
98 return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
100 return tmpl.Execute(wr, data)
103 // Execute applies a parsed template to the specified data object,
104 // and writes the output to wr.
105 func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
106 defer errRecover(&err)
107 value := reflect.ValueOf(data)
112 vars: []variable{{"$", value}},
114 if t.Tree == nil || t.Root == nil {
115 state.errorf("%q is an incomplete or empty template", t.name)
117 state.walk(value, t.Root)
121 // Walk functions step through the major pieces of the template structure,
122 // generating output as they go.
123 func (s *state) walk(dot reflect.Value, n parse.Node) {
124 switch n := n.(type) {
125 case *parse.ActionNode:
127 // Do not pop variables so they persist until next end.
128 // Also, if the action declares variables, don't print the result.
129 val := s.evalPipeline(dot, n.Pipe)
130 if len(n.Pipe.Decl) == 0 {
135 s.walkIfOrWith(parse.NodeIf, dot, n.Pipe, n.List, n.ElseList)
136 case *parse.ListNode:
137 for _, node := range n.Nodes {
140 case *parse.RangeNode:
143 case *parse.TemplateNode:
145 s.walkTemplate(dot, n)
146 case *parse.TextNode:
147 if _, err := s.wr.Write(n.Text); err != nil {
150 case *parse.WithNode:
152 s.walkIfOrWith(parse.NodeWith, dot, n.Pipe, n.List, n.ElseList)
154 s.errorf("unknown node: %s", n)
158 // walkIfOrWith walks an 'if' or 'with' node. The two control structures
159 // are identical in behavior except that 'with' sets dot.
160 func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
161 defer s.pop(s.mark())
162 val := s.evalPipeline(dot, pipe)
163 truth, ok := isTrue(val)
165 s.errorf("if/with can't use %v", val)
168 if typ == parse.NodeWith {
173 } else if elseList != nil {
174 s.walk(dot, elseList)
178 // isTrue returns whether the value is 'true', in the sense of not the zero of its type,
179 // and whether the value has a meaningful truth value.
180 func isTrue(val reflect.Value) (truth, ok bool) {
182 // Something like var x interface{}, never set. It's a form of nil.
186 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
187 truth = val.Len() > 0
190 case reflect.Complex64, reflect.Complex128:
191 truth = val.Complex() != 0
192 case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
194 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
195 truth = val.Int() != 0
196 case reflect.Float32, reflect.Float64:
197 truth = val.Float() != 0
198 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
199 truth = val.Uint() != 0
201 truth = true // Struct values are always true.
208 func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
209 defer s.pop(s.mark())
210 val, _ := indirect(s.evalPipeline(dot, r.Pipe))
211 // mark top of stack before any variables in the body are pushed.
213 oneIteration := func(index, elem reflect.Value) {
214 // Set top var (lexically the second if there are two) to the element.
215 if len(r.Pipe.Decl) > 0 {
218 // Set next var (lexically the first if there are two) to the index.
219 if len(r.Pipe.Decl) > 1 {
226 case reflect.Array, reflect.Slice:
230 for i := 0; i < val.Len(); i++ {
231 oneIteration(reflect.ValueOf(i), val.Index(i))
238 for _, key := range sortKeys(val.MapKeys()) {
239 oneIteration(key, val.MapIndex(key))
248 elem, ok := val.Recv()
252 oneIteration(reflect.ValueOf(i), elem)
258 case reflect.Invalid:
259 break // An invalid value is likely a nil map, etc. and acts like an empty map.
261 s.errorf("range can't iterate over %v", val)
263 if r.ElseList != nil {
264 s.walk(dot, r.ElseList)
268 func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
269 tmpl := s.tmpl.tmpl[t.Name]
271 s.errorf("template %q not defined", t.Name)
273 // Variables declared by the pipeline persist.
274 dot = s.evalPipeline(dot, t.Pipe)
277 // No dynamic scoping: template invocations inherit no variables.
278 newState.vars = []variable{{"$", dot}}
279 newState.walk(dot, tmpl.Root)
282 // Eval functions evaluate pipelines, commands, and their elements and extract
283 // values from the data structure by examining fields, calling methods, and so on.
284 // The printing of those values happens only through walk functions.
286 // evalPipeline returns the value acquired by evaluating a pipeline. If the
287 // pipeline has a variable declaration, the variable will be pushed on the
288 // stack. Callers should therefore pop the stack after they are finished
289 // executing commands depending on the pipeline value.
290 func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
294 for _, cmd := range pipe.Cmds {
295 value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
296 // If the object has type interface{}, dig down one level to the thing inside.
297 if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
298 value = reflect.ValueOf(value.Interface()) // lovely!
301 for _, variable := range pipe.Decl {
302 s.push(variable.Ident[0], value)
307 func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
308 if len(args) > 1 || final.IsValid() {
309 s.errorf("can't give argument to non-function %s", args[0])
313 func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
314 firstWord := cmd.Args[0]
315 switch n := firstWord.(type) {
316 case *parse.FieldNode:
317 return s.evalFieldNode(dot, n, cmd.Args, final)
318 case *parse.IdentifierNode:
319 // Must be a function.
320 return s.evalFunction(dot, n.Ident, cmd.Args, final)
321 case *parse.VariableNode:
322 return s.evalVariableNode(dot, n, cmd.Args, final)
324 s.notAFunction(cmd.Args, final)
325 switch word := firstWord.(type) {
326 case *parse.BoolNode:
327 return reflect.ValueOf(word.True)
330 case *parse.NumberNode:
331 return s.idealConstant(word)
332 case *parse.StringNode:
333 return reflect.ValueOf(word.Text)
335 s.errorf("can't evaluate command %q", firstWord)
339 // idealConstant is called to return the value of a number in a context where
340 // we don't know the type. In that case, the syntax of the number tells us
341 // its type, and we use Go rules to resolve. Note there is no such thing as
342 // a uint ideal constant in this situation - the value must be of int type.
343 func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
344 // These are ideal constants but we don't know the type
345 // and we have no context. (If it was a method argument,
346 // we'd know what we need.) The syntax guides us to some extent.
348 case constant.IsComplex:
349 return reflect.ValueOf(constant.Complex128) // incontrovertible.
350 case constant.IsFloat && strings.IndexAny(constant.Text, ".eE") >= 0:
351 return reflect.ValueOf(constant.Float64)
353 n := int(constant.Int64)
354 if int64(n) != constant.Int64 {
355 s.errorf("%s overflows int", constant.Text)
357 return reflect.ValueOf(n)
358 case constant.IsUint:
359 s.errorf("%s overflows int", constant.Text)
364 func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
365 return s.evalFieldChain(dot, dot, field.Ident, args, final)
368 func (s *state) evalVariableNode(dot reflect.Value, v *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
369 // $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
370 value := s.varValue(v.Ident[0])
371 if len(v.Ident) == 1 {
374 return s.evalFieldChain(dot, value, v.Ident[1:], args, final)
377 // evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
378 // dot is the environment in which to evaluate arguments, while
379 // receiver is the value being walked along the chain.
380 func (s *state) evalFieldChain(dot, receiver reflect.Value, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
382 for i := 0; i < n-1; i++ {
383 receiver = s.evalField(dot, ident[i], nil, zero, receiver)
385 // Now if it's a method, it gets the arguments.
386 return s.evalField(dot, ident[n-1], args, final, receiver)
389 func (s *state) evalFunction(dot reflect.Value, name string, args []parse.Node, final reflect.Value) reflect.Value {
390 function, ok := findFunction(name, s.tmpl)
392 s.errorf("%q is not a defined function", name)
394 return s.evalCall(dot, function, name, args, final)
397 // evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
398 // The 'final' argument represents the return value from the preceding
399 // value of the pipeline, if any.
400 func (s *state) evalField(dot reflect.Value, fieldName string, args []parse.Node, final, receiver reflect.Value) reflect.Value {
401 if !receiver.IsValid() {
404 typ := receiver.Type()
405 receiver, _ = indirect(receiver)
406 // Unless it's an interface, need to get to a value of type *T to guarantee
407 // we see all methods of T and *T.
409 if ptr.Kind() != reflect.Interface && ptr.CanAddr() {
412 if method := ptr.MethodByName(fieldName); method.IsValid() {
413 return s.evalCall(dot, method, fieldName, args, final)
415 hasArgs := len(args) > 1 || final.IsValid()
416 // It's not a method; is it a field of a struct?
417 receiver, isNil := indirect(receiver)
418 if receiver.Kind() == reflect.Struct {
419 tField, ok := receiver.Type().FieldByName(fieldName)
421 field := receiver.FieldByIndex(tField.Index)
422 if tField.PkgPath == "" { // field is exported
423 // If it's a function, we must call it.
425 s.errorf("%s has arguments but cannot be invoked as function", fieldName)
431 // If it's a map, attempt to use the field name as a key.
432 if receiver.Kind() == reflect.Map {
433 nameVal := reflect.ValueOf(fieldName)
434 if nameVal.Type().AssignableTo(receiver.Type().Key()) {
436 s.errorf("%s is not a method but has arguments", fieldName)
438 return receiver.MapIndex(nameVal)
442 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
444 s.errorf("can't evaluate field %s in type %s", fieldName, typ)
449 errorType = reflect.TypeOf((*error)(nil)).Elem()
450 fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
453 // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
454 // it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
455 // as the function itself.
456 func (s *state) evalCall(dot, fun reflect.Value, name string, args []parse.Node, final reflect.Value) reflect.Value {
458 args = args[1:] // Zeroth arg is function name/node; not passed to function.
465 numFixed := len(args)
466 if typ.IsVariadic() {
467 numFixed = typ.NumIn() - 1 // last arg is the variadic one.
468 if numIn < numFixed {
469 s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
471 } else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() {
472 s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args))
475 s.errorf("can't handle multiple results from method/function %q", name)
477 // Build the arg list.
478 argv := make([]reflect.Value, numIn)
479 // Args must be evaluated. Fixed args first.
481 for ; i < numFixed; i++ {
482 argv[i] = s.evalArg(dot, typ.In(i), args[i])
485 if typ.IsVariadic() {
486 argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
487 for ; i < len(args); i++ {
488 argv[i] = s.evalArg(dot, argType, args[i])
491 // Add final value if necessary.
495 result := fun.Call(argv)
496 // If we have an error that is not nil, stop execution and return that error to the caller.
497 if len(result) == 2 && !result[1].IsNil() {
498 s.errorf("error calling %s: %s", name, result[1].Interface().(error))
503 // validateType guarantees that the value is valid and assignable to the type.
504 func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
505 if !value.IsValid() {
507 case reflect.Interface, reflect.Ptr, reflect.Chan, reflect.Map, reflect.Slice, reflect.Func:
508 // An untyped nil interface{}. Accept as a proper nil value.
509 value = reflect.Zero(typ)
511 s.errorf("invalid value; expected %s", typ)
514 if !value.Type().AssignableTo(typ) {
515 // Does one dereference or indirection work? We could do more, as we
516 // do with method receivers, but that gets messy and method receivers
517 // are much more constrained, so it makes more sense there than here.
518 // Besides, one is almost always all you need.
520 case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
522 case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
525 s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
531 func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
532 switch arg := n.(type) {
534 return s.validateType(dot, typ)
535 case *parse.FieldNode:
536 return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, zero), typ)
537 case *parse.VariableNode:
538 return s.validateType(s.evalVariableNode(dot, arg, nil, zero), typ)
542 return s.evalBool(typ, n)
543 case reflect.Complex64, reflect.Complex128:
544 return s.evalComplex(typ, n)
545 case reflect.Float32, reflect.Float64:
546 return s.evalFloat(typ, n)
547 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
548 return s.evalInteger(typ, n)
549 case reflect.Interface:
550 if typ.NumMethod() == 0 {
551 return s.evalEmptyInterface(dot, n)
554 return s.evalString(typ, n)
555 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
556 return s.evalUnsignedInteger(typ, n)
558 s.errorf("can't handle %s for arg of type %s", n, typ)
562 func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
563 if n, ok := n.(*parse.BoolNode); ok {
564 value := reflect.New(typ).Elem()
565 value.SetBool(n.True)
568 s.errorf("expected bool; found %s", n)
572 func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
573 if n, ok := n.(*parse.StringNode); ok {
574 value := reflect.New(typ).Elem()
575 value.SetString(n.Text)
578 s.errorf("expected string; found %s", n)
582 func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
583 if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
584 value := reflect.New(typ).Elem()
585 value.SetInt(n.Int64)
588 s.errorf("expected integer; found %s", n)
592 func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
593 if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
594 value := reflect.New(typ).Elem()
595 value.SetUint(n.Uint64)
598 s.errorf("expected unsigned integer; found %s", n)
602 func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
603 if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
604 value := reflect.New(typ).Elem()
605 value.SetFloat(n.Float64)
608 s.errorf("expected float; found %s", n)
612 func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
613 if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
614 value := reflect.New(typ).Elem()
615 value.SetComplex(n.Complex128)
618 s.errorf("expected complex; found %s", n)
622 func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
623 switch n := n.(type) {
624 case *parse.BoolNode:
625 return reflect.ValueOf(n.True)
628 case *parse.FieldNode:
629 return s.evalFieldNode(dot, n, nil, zero)
630 case *parse.IdentifierNode:
631 return s.evalFunction(dot, n.Ident, nil, zero)
632 case *parse.NumberNode:
633 return s.idealConstant(n)
634 case *parse.StringNode:
635 return reflect.ValueOf(n.Text)
636 case *parse.VariableNode:
637 return s.evalVariableNode(dot, n, nil, zero)
639 s.errorf("can't handle assignment of %s to empty interface argument", n)
643 // indirect returns the item at the end of indirection, and a bool to indicate if it's nil.
644 // We indirect through pointers and empty interfaces (only) because
645 // non-empty interfaces have methods we might need.
646 func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
647 for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
651 if v.Kind() == reflect.Interface && v.NumMethod() > 0 {
658 // printValue writes the textual representation of the value to the output of
660 func (s *state) printValue(n parse.Node, v reflect.Value) {
661 if v.Kind() == reflect.Ptr {
662 v, _ = indirect(v) // fmt.Fprint handles nil.
665 fmt.Fprint(s.wr, "<no value>")
669 if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
670 if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
674 case reflect.Chan, reflect.Func:
675 s.errorf("can't print %s of type %s", n, v.Type())
679 fmt.Fprint(s.wr, v.Interface())
682 // Types to help sort the keys in a map for reproducible output.
684 type rvs []reflect.Value
686 func (x rvs) Len() int { return len(x) }
687 func (x rvs) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
689 type rvInts struct{ rvs }
691 func (x rvInts) Less(i, j int) bool { return x.rvs[i].Int() < x.rvs[j].Int() }
693 type rvUints struct{ rvs }
695 func (x rvUints) Less(i, j int) bool { return x.rvs[i].Uint() < x.rvs[j].Uint() }
697 type rvFloats struct{ rvs }
699 func (x rvFloats) Less(i, j int) bool { return x.rvs[i].Float() < x.rvs[j].Float() }
701 type rvStrings struct{ rvs }
703 func (x rvStrings) Less(i, j int) bool { return x.rvs[i].String() < x.rvs[j].String() }
705 // sortKeys sorts (if it can) the slice of reflect.Values, which is a slice of map keys.
706 func sortKeys(v []reflect.Value) []reflect.Value {
711 case reflect.Float32, reflect.Float64:
712 sort.Sort(rvFloats{v})
713 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
716 sort.Sort(rvStrings{v})
717 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
718 sort.Sort(rvUints{v})