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.
16 // state represents the state of an execution. It's not part of the
17 // template so that multiple executions of the same template
18 // can execute in parallel.
22 line int // line number for errors
23 vars []variable // push-down stack of variable values.
26 // variable holds the dynamic value of a variable such as $, $x etc.
27 type variable struct {
32 // push pushes a new variable on the stack.
33 func (s *state) push(name string, value reflect.Value) {
34 s.vars = append(s.vars, variable{name, value})
37 // mark returns the length of the variable stack.
38 func (s *state) mark() int {
42 // pop pops the variable stack up to the mark.
43 func (s *state) pop(mark int) {
44 s.vars = s.vars[0:mark]
47 // setVar overwrites the top-nth variable on the stack. Used by range iterations.
48 func (s *state) setVar(n int, value reflect.Value) {
49 s.vars[len(s.vars)-n].value = value
52 // varValue returns the value of the named variable.
53 func (s *state) varValue(name string) reflect.Value {
54 for i := s.mark() - 1; i >= 0; i-- {
55 if s.vars[i].name == name {
56 return s.vars[i].value
59 s.errorf("undefined variable: %s", name)
63 var zero reflect.Value
65 // errorf formats the error and terminates processing.
66 func (s *state) errorf(format string, args ...interface{}) {
67 format = fmt.Sprintf("template: %s:%d: %s", s.tmpl.Name(), s.line, format)
68 panic(fmt.Errorf(format, args...))
71 // error terminates processing.
72 func (s *state) error(err error) {
76 // errRecover is the handler that turns panics into returns from the top
78 func errRecover(errp *error) {
81 if _, ok := e.(runtime.Error); ok {
88 // ExecuteTemplate applies the template associated with t that has the given name
89 // to the specified data object and writes the output to wr.
90 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
93 return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
95 return tmpl.Execute(wr, data)
98 // Execute applies a parsed template to the specified data object,
99 // and writes the output to wr.
100 func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
101 defer errRecover(&err)
102 value := reflect.ValueOf(data)
107 vars: []variable{{"$", value}},
109 if t.Tree == nil || t.Root == nil {
110 state.errorf("%q is an incomplete or empty template", t.name)
112 state.walk(value, t.Root)
116 // Walk functions step through the major pieces of the template structure,
117 // generating output as they go.
118 func (s *state) walk(dot reflect.Value, n parse.Node) {
119 switch n := n.(type) {
120 case *parse.ActionNode:
122 // Do not pop variables so they persist until next end.
123 // Also, if the action declares variables, don't print the result.
124 val := s.evalPipeline(dot, n.Pipe)
125 if len(n.Pipe.Decl) == 0 {
130 s.walkIfOrWith(parse.NodeIf, dot, n.Pipe, n.List, n.ElseList)
131 case *parse.ListNode:
132 for _, node := range n.Nodes {
135 case *parse.RangeNode:
138 case *parse.TemplateNode:
140 s.walkTemplate(dot, n)
141 case *parse.TextNode:
142 if _, err := s.wr.Write(n.Text); err != nil {
145 case *parse.WithNode:
147 s.walkIfOrWith(parse.NodeWith, dot, n.Pipe, n.List, n.ElseList)
149 s.errorf("unknown node: %s", n)
153 // walkIfOrWith walks an 'if' or 'with' node. The two control structures
154 // are identical in behavior except that 'with' sets dot.
155 func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
156 defer s.pop(s.mark())
157 val := s.evalPipeline(dot, pipe)
158 truth, ok := isTrue(val)
160 s.errorf("if/with can't use %v", val)
163 if typ == parse.NodeWith {
168 } else if elseList != nil {
169 s.walk(dot, elseList)
173 // isTrue returns whether the value is 'true', in the sense of not the zero of its type,
174 // and whether the value has a meaningful truth value.
175 func isTrue(val reflect.Value) (truth, ok bool) {
177 // Something like var x interface{}, never set. It's a form of nil.
181 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
182 truth = val.Len() > 0
185 case reflect.Complex64, reflect.Complex128:
186 truth = val.Complex() != 0
187 case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
189 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
190 truth = val.Int() != 0
191 case reflect.Float32, reflect.Float64:
192 truth = val.Float() != 0
193 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
194 truth = val.Uint() != 0
196 truth = true // Struct values are always true.
203 func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
204 defer s.pop(s.mark())
205 val, _ := indirect(s.evalPipeline(dot, r.Pipe))
206 // mark top of stack before any variables in the body are pushed.
208 oneIteration := func(index, elem reflect.Value) {
209 // Set top var (lexically the second if there are two) to the element.
210 if len(r.Pipe.Decl) > 0 {
213 // Set next var (lexically the first if there are two) to the index.
214 if len(r.Pipe.Decl) > 1 {
221 case reflect.Array, reflect.Slice:
225 for i := 0; i < val.Len(); i++ {
226 oneIteration(reflect.ValueOf(i), val.Index(i))
233 for _, key := range val.MapKeys() {
234 oneIteration(key, val.MapIndex(key))
243 elem, ok := val.Recv()
247 oneIteration(reflect.ValueOf(i), elem)
253 case reflect.Invalid:
254 break // An invalid value is likely a nil map, etc. and acts like an empty map.
256 s.errorf("range can't iterate over %v", val)
258 if r.ElseList != nil {
259 s.walk(dot, r.ElseList)
263 func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
264 tmpl := s.tmpl.tmpl[t.Name]
266 s.errorf("template %q not defined", t.Name)
268 // Variables declared by the pipeline persist.
269 dot = s.evalPipeline(dot, t.Pipe)
272 // No dynamic scoping: template invocations inherit no variables.
273 newState.vars = []variable{{"$", dot}}
274 newState.walk(dot, tmpl.Root)
277 // Eval functions evaluate pipelines, commands, and their elements and extract
278 // values from the data structure by examining fields, calling methods, and so on.
279 // The printing of those values happens only through walk functions.
281 // evalPipeline returns the value acquired by evaluating a pipeline. If the
282 // pipeline has a variable declaration, the variable will be pushed on the
283 // stack. Callers should therefore pop the stack after they are finished
284 // executing commands depending on the pipeline value.
285 func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
289 for _, cmd := range pipe.Cmds {
290 value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
291 // If the object has type interface{}, dig down one level to the thing inside.
292 if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
293 value = reflect.ValueOf(value.Interface()) // lovely!
296 for _, variable := range pipe.Decl {
297 s.push(variable.Ident[0], value)
302 func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
303 if len(args) > 1 || final.IsValid() {
304 s.errorf("can't give argument to non-function %s", args[0])
308 func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
309 firstWord := cmd.Args[0]
310 switch n := firstWord.(type) {
311 case *parse.FieldNode:
312 return s.evalFieldNode(dot, n, cmd.Args, final)
313 case *parse.IdentifierNode:
314 // Must be a function.
315 return s.evalFunction(dot, n.Ident, cmd.Args, final)
316 case *parse.VariableNode:
317 return s.evalVariableNode(dot, n, cmd.Args, final)
319 s.notAFunction(cmd.Args, final)
320 switch word := firstWord.(type) {
321 case *parse.BoolNode:
322 return reflect.ValueOf(word.True)
325 case *parse.NumberNode:
326 return s.idealConstant(word)
327 case *parse.StringNode:
328 return reflect.ValueOf(word.Text)
330 s.errorf("can't evaluate command %q", firstWord)
334 // idealConstant is called to return the value of a number in a context where
335 // we don't know the type. In that case, the syntax of the number tells us
336 // its type, and we use Go rules to resolve. Note there is no such thing as
337 // a uint ideal constant in this situation - the value must be of int type.
338 func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
339 // These are ideal constants but we don't know the type
340 // and we have no context. (If it was a method argument,
341 // we'd know what we need.) The syntax guides us to some extent.
343 case constant.IsComplex:
344 return reflect.ValueOf(constant.Complex128) // incontrovertible.
345 case constant.IsFloat && strings.IndexAny(constant.Text, ".eE") >= 0:
346 return reflect.ValueOf(constant.Float64)
348 n := int(constant.Int64)
349 if int64(n) != constant.Int64 {
350 s.errorf("%s overflows int", constant.Text)
352 return reflect.ValueOf(n)
353 case constant.IsUint:
354 s.errorf("%s overflows int", constant.Text)
359 func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
360 return s.evalFieldChain(dot, dot, field.Ident, args, final)
363 func (s *state) evalVariableNode(dot reflect.Value, v *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
364 // $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
365 value := s.varValue(v.Ident[0])
366 if len(v.Ident) == 1 {
369 return s.evalFieldChain(dot, value, v.Ident[1:], args, final)
372 // evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
373 // dot is the environment in which to evaluate arguments, while
374 // receiver is the value being walked along the chain.
375 func (s *state) evalFieldChain(dot, receiver reflect.Value, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
377 for i := 0; i < n-1; i++ {
378 receiver = s.evalField(dot, ident[i], nil, zero, receiver)
380 // Now if it's a method, it gets the arguments.
381 return s.evalField(dot, ident[n-1], args, final, receiver)
384 func (s *state) evalFunction(dot reflect.Value, name string, args []parse.Node, final reflect.Value) reflect.Value {
385 function, ok := findFunction(name, s.tmpl)
387 s.errorf("%q is not a defined function", name)
389 return s.evalCall(dot, function, name, args, final)
392 // evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
393 // The 'final' argument represents the return value from the preceding
394 // value of the pipeline, if any.
395 func (s *state) evalField(dot reflect.Value, fieldName string, args []parse.Node, final, receiver reflect.Value) reflect.Value {
396 if !receiver.IsValid() {
399 typ := receiver.Type()
400 receiver, _ = indirect(receiver)
401 // Unless it's an interface, need to get to a value of type *T to guarantee
402 // we see all methods of T and *T.
404 if ptr.Kind() != reflect.Interface && ptr.CanAddr() {
407 if method := ptr.MethodByName(fieldName); method.IsValid() {
408 return s.evalCall(dot, method, fieldName, args, final)
410 hasArgs := len(args) > 1 || final.IsValid()
411 // It's not a method; is it a field of a struct?
412 receiver, isNil := indirect(receiver)
413 if receiver.Kind() == reflect.Struct {
414 tField, ok := receiver.Type().FieldByName(fieldName)
416 field := receiver.FieldByIndex(tField.Index)
418 s.errorf("%s is not a method but has arguments", fieldName)
420 if tField.PkgPath == "" { // field is exported
425 // If it's a map, attempt to use the field name as a key.
426 if receiver.Kind() == reflect.Map {
427 nameVal := reflect.ValueOf(fieldName)
428 if nameVal.Type().AssignableTo(receiver.Type().Key()) {
430 s.errorf("%s is not a method but has arguments", fieldName)
432 return receiver.MapIndex(nameVal)
436 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
438 s.errorf("can't evaluate field %s in type %s", fieldName, typ)
443 errorType = reflect.TypeOf((*error)(nil)).Elem()
444 fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
447 // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
448 // it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
449 // as the function itself.
450 func (s *state) evalCall(dot, fun reflect.Value, name string, args []parse.Node, final reflect.Value) reflect.Value {
452 args = args[1:] // Zeroth arg is function name/node; not passed to function.
459 numFixed := len(args)
460 if typ.IsVariadic() {
461 numFixed = typ.NumIn() - 1 // last arg is the variadic one.
462 if numIn < numFixed {
463 s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
465 } else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() {
466 s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args))
469 s.errorf("can't handle multiple results from method/function %q", name)
471 // Build the arg list.
472 argv := make([]reflect.Value, numIn)
473 // Args must be evaluated. Fixed args first.
475 for ; i < numFixed; i++ {
476 argv[i] = s.evalArg(dot, typ.In(i), args[i])
479 if typ.IsVariadic() {
480 argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
481 for ; i < len(args); i++ {
482 argv[i] = s.evalArg(dot, argType, args[i])
485 // Add final value if necessary.
489 result := fun.Call(argv)
490 // If we have an error that is not nil, stop execution and return that error to the caller.
491 if len(result) == 2 && !result[1].IsNil() {
492 s.errorf("error calling %s: %s", name, result[1].Interface().(error))
497 // validateType guarantees that the value is valid and assignable to the type.
498 func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
499 if !value.IsValid() {
501 case reflect.Interface, reflect.Ptr, reflect.Chan, reflect.Map, reflect.Slice, reflect.Func:
502 // An untyped nil interface{}. Accept as a proper nil value.
503 value = reflect.Zero(typ)
505 s.errorf("invalid value; expected %s", typ)
508 if !value.Type().AssignableTo(typ) {
509 // Does one dereference or indirection work? We could do more, as we
510 // do with method receivers, but that gets messy and method receivers
511 // are much more constrained, so it makes more sense there than here.
512 // Besides, one is almost always all you need.
514 case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
516 case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
519 s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
525 func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
526 switch arg := n.(type) {
528 return s.validateType(dot, typ)
529 case *parse.FieldNode:
530 return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, zero), typ)
531 case *parse.VariableNode:
532 return s.validateType(s.evalVariableNode(dot, arg, nil, zero), typ)
536 return s.evalBool(typ, n)
537 case reflect.Complex64, reflect.Complex128:
538 return s.evalComplex(typ, n)
539 case reflect.Float32, reflect.Float64:
540 return s.evalFloat(typ, n)
541 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
542 return s.evalInteger(typ, n)
543 case reflect.Interface:
544 if typ.NumMethod() == 0 {
545 return s.evalEmptyInterface(dot, n)
548 return s.evalString(typ, n)
549 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
550 return s.evalUnsignedInteger(typ, n)
552 s.errorf("can't handle %s for arg of type %s", n, typ)
556 func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
557 if n, ok := n.(*parse.BoolNode); ok {
558 value := reflect.New(typ).Elem()
559 value.SetBool(n.True)
562 s.errorf("expected bool; found %s", n)
566 func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
567 if n, ok := n.(*parse.StringNode); ok {
568 value := reflect.New(typ).Elem()
569 value.SetString(n.Text)
572 s.errorf("expected string; found %s", n)
576 func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
577 if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
578 value := reflect.New(typ).Elem()
579 value.SetInt(n.Int64)
582 s.errorf("expected integer; found %s", n)
586 func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
587 if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
588 value := reflect.New(typ).Elem()
589 value.SetUint(n.Uint64)
592 s.errorf("expected unsigned integer; found %s", n)
596 func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
597 if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
598 value := reflect.New(typ).Elem()
599 value.SetFloat(n.Float64)
602 s.errorf("expected float; found %s", n)
606 func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
607 if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
608 value := reflect.New(typ).Elem()
609 value.SetComplex(n.Complex128)
612 s.errorf("expected complex; found %s", n)
616 func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
617 switch n := n.(type) {
618 case *parse.BoolNode:
619 return reflect.ValueOf(n.True)
622 case *parse.FieldNode:
623 return s.evalFieldNode(dot, n, nil, zero)
624 case *parse.IdentifierNode:
625 return s.evalFunction(dot, n.Ident, nil, zero)
626 case *parse.NumberNode:
627 return s.idealConstant(n)
628 case *parse.StringNode:
629 return reflect.ValueOf(n.Text)
630 case *parse.VariableNode:
631 return s.evalVariableNode(dot, n, nil, zero)
633 s.errorf("can't handle assignment of %s to empty interface argument", n)
637 // indirect returns the item at the end of indirection, and a bool to indicate if it's nil.
638 // We indirect through pointers and empty interfaces (only) because
639 // non-empty interfaces have methods we might need.
640 func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
641 for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
645 if v.Kind() == reflect.Interface && v.NumMethod() > 0 {
652 // printValue writes the textual representation of the value to the output of
654 func (s *state) printValue(n parse.Node, v reflect.Value) {
655 if v.Kind() == reflect.Ptr {
656 v, _ = indirect(v) // fmt.Fprint handles nil.
659 fmt.Fprint(s.wr, "<no value>")
663 if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
664 if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
668 case reflect.Chan, reflect.Func:
669 s.errorf("can't print %s of type %s", n, v.Type())
673 fmt.Fprint(s.wr, v.Interface())