LWG 3035. std::allocator's constructors should be constexpr
[official-gcc.git] / libgo / go / text / template / exec.go
blob2923dd9d83fb4d01d72b9f9c365c7ff8ff38134e
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.
5 package template
7 import (
8 "bytes"
9 "fmt"
10 "io"
11 "reflect"
12 "runtime"
13 "sort"
14 "strings"
15 "text/template/parse"
18 // maxExecDepth specifies the maximum stack depth of templates within
19 // templates. This limit is only practically reached by accidentally
20 // recursive template invocations. This limit allows us to return
21 // an error instead of triggering a stack overflow.
22 // For gccgo we make this 1000 rather than 100000 to avoid stack overflow
23 // on non-split-stack systems.
24 const maxExecDepth = 1000
26 // state represents the state of an execution. It's not part of the
27 // template so that multiple executions of the same template
28 // can execute in parallel.
29 type state struct {
30 tmpl *Template
31 wr io.Writer
32 node parse.Node // current node, for errors
33 vars []variable // push-down stack of variable values.
34 depth int // the height of the stack of executing templates.
37 // variable holds the dynamic value of a variable such as $, $x etc.
38 type variable struct {
39 name string
40 value reflect.Value
43 // push pushes a new variable on the stack.
44 func (s *state) push(name string, value reflect.Value) {
45 s.vars = append(s.vars, variable{name, value})
48 // mark returns the length of the variable stack.
49 func (s *state) mark() int {
50 return len(s.vars)
53 // pop pops the variable stack up to the mark.
54 func (s *state) pop(mark int) {
55 s.vars = s.vars[0:mark]
58 // setVar overwrites the top-nth variable on the stack. Used by range iterations.
59 func (s *state) setVar(n int, value reflect.Value) {
60 s.vars[len(s.vars)-n].value = value
63 // varValue returns the value of the named variable.
64 func (s *state) varValue(name string) reflect.Value {
65 for i := s.mark() - 1; i >= 0; i-- {
66 if s.vars[i].name == name {
67 return s.vars[i].value
70 s.errorf("undefined variable: %s", name)
71 return zero
74 var zero reflect.Value
76 // at marks the state to be on node n, for error reporting.
77 func (s *state) at(node parse.Node) {
78 s.node = node
81 // doublePercent returns the string with %'s replaced by %%, if necessary,
82 // so it can be used safely inside a Printf format string.
83 func doublePercent(str string) string {
84 return strings.Replace(str, "%", "%%", -1)
87 // TODO: It would be nice if ExecError was more broken down, but
88 // the way ErrorContext embeds the template name makes the
89 // processing too clumsy.
91 // ExecError is the custom error type returned when Execute has an
92 // error evaluating its template. (If a write error occurs, the actual
93 // error is returned; it will not be of type ExecError.)
94 type ExecError struct {
95 Name string // Name of template.
96 Err error // Pre-formatted error.
99 func (e ExecError) Error() string {
100 return e.Err.Error()
103 // errorf records an ExecError and terminates processing.
104 func (s *state) errorf(format string, args ...interface{}) {
105 name := doublePercent(s.tmpl.Name())
106 if s.node == nil {
107 format = fmt.Sprintf("template: %s: %s", name, format)
108 } else {
109 location, context := s.tmpl.ErrorContext(s.node)
110 format = fmt.Sprintf("template: %s: executing %q at <%s>: %s", location, name, doublePercent(context), format)
112 panic(ExecError{
113 Name: s.tmpl.Name(),
114 Err: fmt.Errorf(format, args...),
118 // writeError is the wrapper type used internally when Execute has an
119 // error writing to its output. We strip the wrapper in errRecover.
120 // Note that this is not an implementation of error, so it cannot escape
121 // from the package as an error value.
122 type writeError struct {
123 Err error // Original error.
126 func (s *state) writeError(err error) {
127 panic(writeError{
128 Err: err,
132 // errRecover is the handler that turns panics into returns from the top
133 // level of Parse.
134 func errRecover(errp *error) {
135 e := recover()
136 if e != nil {
137 switch err := e.(type) {
138 case runtime.Error:
139 panic(e)
140 case writeError:
141 *errp = err.Err // Strip the wrapper.
142 case ExecError:
143 *errp = err // Keep the wrapper.
144 default:
145 panic(e)
150 // ExecuteTemplate applies the template associated with t that has the given name
151 // to the specified data object and writes the output to wr.
152 // If an error occurs executing the template or writing its output,
153 // execution stops, but partial results may already have been written to
154 // the output writer.
155 // A template may be executed safely in parallel, although if parallel
156 // executions share a Writer the output may be interleaved.
157 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
158 var tmpl *Template
159 if t.common != nil {
160 tmpl = t.tmpl[name]
162 if tmpl == nil {
163 return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
165 return tmpl.Execute(wr, data)
168 // Execute applies a parsed template to the specified data object,
169 // and writes the output to wr.
170 // If an error occurs executing the template or writing its output,
171 // execution stops, but partial results may already have been written to
172 // the output writer.
173 // A template may be executed safely in parallel, although if parallel
174 // executions share a Writer the output may be interleaved.
176 // If data is a reflect.Value, the template applies to the concrete
177 // value that the reflect.Value holds, as in fmt.Print.
178 func (t *Template) Execute(wr io.Writer, data interface{}) error {
179 return t.execute(wr, data)
182 func (t *Template) execute(wr io.Writer, data interface{}) (err error) {
183 defer errRecover(&err)
184 value, ok := data.(reflect.Value)
185 if !ok {
186 value = reflect.ValueOf(data)
188 state := &state{
189 tmpl: t,
190 wr: wr,
191 vars: []variable{{"$", value}},
193 if t.Tree == nil || t.Root == nil {
194 state.errorf("%q is an incomplete or empty template", t.Name())
196 state.walk(value, t.Root)
197 return
200 // DefinedTemplates returns a string listing the defined templates,
201 // prefixed by the string "; defined templates are: ". If there are none,
202 // it returns the empty string. For generating an error message here
203 // and in html/template.
204 func (t *Template) DefinedTemplates() string {
205 if t.common == nil {
206 return ""
208 var b bytes.Buffer
209 for name, tmpl := range t.tmpl {
210 if tmpl.Tree == nil || tmpl.Root == nil {
211 continue
213 if b.Len() > 0 {
214 b.WriteString(", ")
216 fmt.Fprintf(&b, "%q", name)
218 var s string
219 if b.Len() > 0 {
220 s = "; defined templates are: " + b.String()
222 return s
225 // Walk functions step through the major pieces of the template structure,
226 // generating output as they go.
227 func (s *state) walk(dot reflect.Value, node parse.Node) {
228 s.at(node)
229 switch node := node.(type) {
230 case *parse.ActionNode:
231 // Do not pop variables so they persist until next end.
232 // Also, if the action declares variables, don't print the result.
233 val := s.evalPipeline(dot, node.Pipe)
234 if len(node.Pipe.Decl) == 0 {
235 s.printValue(node, val)
237 case *parse.IfNode:
238 s.walkIfOrWith(parse.NodeIf, dot, node.Pipe, node.List, node.ElseList)
239 case *parse.ListNode:
240 for _, node := range node.Nodes {
241 s.walk(dot, node)
243 case *parse.RangeNode:
244 s.walkRange(dot, node)
245 case *parse.TemplateNode:
246 s.walkTemplate(dot, node)
247 case *parse.TextNode:
248 if _, err := s.wr.Write(node.Text); err != nil {
249 s.writeError(err)
251 case *parse.WithNode:
252 s.walkIfOrWith(parse.NodeWith, dot, node.Pipe, node.List, node.ElseList)
253 default:
254 s.errorf("unknown node: %s", node)
258 // walkIfOrWith walks an 'if' or 'with' node. The two control structures
259 // are identical in behavior except that 'with' sets dot.
260 func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
261 defer s.pop(s.mark())
262 val := s.evalPipeline(dot, pipe)
263 truth, ok := isTrue(val)
264 if !ok {
265 s.errorf("if/with can't use %v", val)
267 if truth {
268 if typ == parse.NodeWith {
269 s.walk(val, list)
270 } else {
271 s.walk(dot, list)
273 } else if elseList != nil {
274 s.walk(dot, elseList)
278 // IsTrue reports whether the value is 'true', in the sense of not the zero of its type,
279 // and whether the value has a meaningful truth value. This is the definition of
280 // truth used by if and other such actions.
281 func IsTrue(val interface{}) (truth, ok bool) {
282 return isTrue(reflect.ValueOf(val))
285 func isTrue(val reflect.Value) (truth, ok bool) {
286 if !val.IsValid() {
287 // Something like var x interface{}, never set. It's a form of nil.
288 return false, true
290 switch val.Kind() {
291 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
292 truth = val.Len() > 0
293 case reflect.Bool:
294 truth = val.Bool()
295 case reflect.Complex64, reflect.Complex128:
296 truth = val.Complex() != 0
297 case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
298 truth = !val.IsNil()
299 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
300 truth = val.Int() != 0
301 case reflect.Float32, reflect.Float64:
302 truth = val.Float() != 0
303 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
304 truth = val.Uint() != 0
305 case reflect.Struct:
306 truth = true // Struct values are always true.
307 default:
308 return
310 return truth, true
313 func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
314 s.at(r)
315 defer s.pop(s.mark())
316 val, _ := indirect(s.evalPipeline(dot, r.Pipe))
317 // mark top of stack before any variables in the body are pushed.
318 mark := s.mark()
319 oneIteration := func(index, elem reflect.Value) {
320 // Set top var (lexically the second if there are two) to the element.
321 if len(r.Pipe.Decl) > 0 {
322 s.setVar(1, elem)
324 // Set next var (lexically the first if there are two) to the index.
325 if len(r.Pipe.Decl) > 1 {
326 s.setVar(2, index)
328 s.walk(elem, r.List)
329 s.pop(mark)
331 switch val.Kind() {
332 case reflect.Array, reflect.Slice:
333 if val.Len() == 0 {
334 break
336 for i := 0; i < val.Len(); i++ {
337 oneIteration(reflect.ValueOf(i), val.Index(i))
339 return
340 case reflect.Map:
341 if val.Len() == 0 {
342 break
344 for _, key := range sortKeys(val.MapKeys()) {
345 oneIteration(key, val.MapIndex(key))
347 return
348 case reflect.Chan:
349 if val.IsNil() {
350 break
352 i := 0
353 for ; ; i++ {
354 elem, ok := val.Recv()
355 if !ok {
356 break
358 oneIteration(reflect.ValueOf(i), elem)
360 if i == 0 {
361 break
363 return
364 case reflect.Invalid:
365 break // An invalid value is likely a nil map, etc. and acts like an empty map.
366 default:
367 s.errorf("range can't iterate over %v", val)
369 if r.ElseList != nil {
370 s.walk(dot, r.ElseList)
374 func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
375 s.at(t)
376 tmpl := s.tmpl.tmpl[t.Name]
377 if tmpl == nil {
378 s.errorf("template %q not defined", t.Name)
380 if s.depth == maxExecDepth {
381 s.errorf("exceeded maximum template depth (%v)", maxExecDepth)
383 // Variables declared by the pipeline persist.
384 dot = s.evalPipeline(dot, t.Pipe)
385 newState := *s
386 newState.depth++
387 newState.tmpl = tmpl
388 // No dynamic scoping: template invocations inherit no variables.
389 newState.vars = []variable{{"$", dot}}
390 newState.walk(dot, tmpl.Root)
393 // Eval functions evaluate pipelines, commands, and their elements and extract
394 // values from the data structure by examining fields, calling methods, and so on.
395 // The printing of those values happens only through walk functions.
397 // evalPipeline returns the value acquired by evaluating a pipeline. If the
398 // pipeline has a variable declaration, the variable will be pushed on the
399 // stack. Callers should therefore pop the stack after they are finished
400 // executing commands depending on the pipeline value.
401 func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
402 if pipe == nil {
403 return
405 s.at(pipe)
406 for _, cmd := range pipe.Cmds {
407 value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
408 // If the object has type interface{}, dig down one level to the thing inside.
409 if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
410 value = reflect.ValueOf(value.Interface()) // lovely!
413 for _, variable := range pipe.Decl {
414 s.push(variable.Ident[0], value)
416 return value
419 func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
420 if len(args) > 1 || final.IsValid() {
421 s.errorf("can't give argument to non-function %s", args[0])
425 func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
426 firstWord := cmd.Args[0]
427 switch n := firstWord.(type) {
428 case *parse.FieldNode:
429 return s.evalFieldNode(dot, n, cmd.Args, final)
430 case *parse.ChainNode:
431 return s.evalChainNode(dot, n, cmd.Args, final)
432 case *parse.IdentifierNode:
433 // Must be a function.
434 return s.evalFunction(dot, n, cmd, cmd.Args, final)
435 case *parse.PipeNode:
436 // Parenthesized pipeline. The arguments are all inside the pipeline; final is ignored.
437 return s.evalPipeline(dot, n)
438 case *parse.VariableNode:
439 return s.evalVariableNode(dot, n, cmd.Args, final)
441 s.at(firstWord)
442 s.notAFunction(cmd.Args, final)
443 switch word := firstWord.(type) {
444 case *parse.BoolNode:
445 return reflect.ValueOf(word.True)
446 case *parse.DotNode:
447 return dot
448 case *parse.NilNode:
449 s.errorf("nil is not a command")
450 case *parse.NumberNode:
451 return s.idealConstant(word)
452 case *parse.StringNode:
453 return reflect.ValueOf(word.Text)
455 s.errorf("can't evaluate command %q", firstWord)
456 panic("not reached")
459 // idealConstant is called to return the value of a number in a context where
460 // we don't know the type. In that case, the syntax of the number tells us
461 // its type, and we use Go rules to resolve. Note there is no such thing as
462 // a uint ideal constant in this situation - the value must be of int type.
463 func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
464 // These are ideal constants but we don't know the type
465 // and we have no context. (If it was a method argument,
466 // we'd know what we need.) The syntax guides us to some extent.
467 s.at(constant)
468 switch {
469 case constant.IsComplex:
470 return reflect.ValueOf(constant.Complex128) // incontrovertible.
471 case constant.IsFloat && !isHexConstant(constant.Text) && strings.ContainsAny(constant.Text, ".eE"):
472 return reflect.ValueOf(constant.Float64)
473 case constant.IsInt:
474 n := int(constant.Int64)
475 if int64(n) != constant.Int64 {
476 s.errorf("%s overflows int", constant.Text)
478 return reflect.ValueOf(n)
479 case constant.IsUint:
480 s.errorf("%s overflows int", constant.Text)
482 return zero
485 func isHexConstant(s string) bool {
486 return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')
489 func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
490 s.at(field)
491 return s.evalFieldChain(dot, dot, field, field.Ident, args, final)
494 func (s *state) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value {
495 s.at(chain)
496 if len(chain.Field) == 0 {
497 s.errorf("internal error: no fields in evalChainNode")
499 if chain.Node.Type() == parse.NodeNil {
500 s.errorf("indirection through explicit nil in %s", chain)
502 // (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields.
503 pipe := s.evalArg(dot, nil, chain.Node)
504 return s.evalFieldChain(dot, pipe, chain, chain.Field, args, final)
507 func (s *state) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
508 // $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
509 s.at(variable)
510 value := s.varValue(variable.Ident[0])
511 if len(variable.Ident) == 1 {
512 s.notAFunction(args, final)
513 return value
515 return s.evalFieldChain(dot, value, variable, variable.Ident[1:], args, final)
518 // evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
519 // dot is the environment in which to evaluate arguments, while
520 // receiver is the value being walked along the chain.
521 func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
522 n := len(ident)
523 for i := 0; i < n-1; i++ {
524 receiver = s.evalField(dot, ident[i], node, nil, zero, receiver)
526 // Now if it's a method, it gets the arguments.
527 return s.evalField(dot, ident[n-1], node, args, final, receiver)
530 func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
531 s.at(node)
532 name := node.Ident
533 function, ok := findFunction(name, s.tmpl)
534 if !ok {
535 s.errorf("%q is not a defined function", name)
537 return s.evalCall(dot, function, cmd, name, args, final)
540 // evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
541 // The 'final' argument represents the return value from the preceding
542 // value of the pipeline, if any.
543 func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
544 if !receiver.IsValid() {
545 if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key.
546 s.errorf("nil data; no entry for key %q", fieldName)
548 return zero
550 typ := receiver.Type()
551 receiver, isNil := indirect(receiver)
552 // Unless it's an interface, need to get to a value of type *T to guarantee
553 // we see all methods of T and *T.
554 ptr := receiver
555 if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Ptr && ptr.CanAddr() {
556 ptr = ptr.Addr()
558 if method := ptr.MethodByName(fieldName); method.IsValid() {
559 return s.evalCall(dot, method, node, fieldName, args, final)
561 hasArgs := len(args) > 1 || final.IsValid()
562 // It's not a method; must be a field of a struct or an element of a map.
563 switch receiver.Kind() {
564 case reflect.Struct:
565 tField, ok := receiver.Type().FieldByName(fieldName)
566 if ok {
567 if isNil {
568 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
570 field := receiver.FieldByIndex(tField.Index)
571 if tField.PkgPath != "" { // field is unexported
572 s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
574 // If it's a function, we must call it.
575 if hasArgs {
576 s.errorf("%s has arguments but cannot be invoked as function", fieldName)
578 return field
580 case reflect.Map:
581 if isNil {
582 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
584 // If it's a map, attempt to use the field name as a key.
585 nameVal := reflect.ValueOf(fieldName)
586 if nameVal.Type().AssignableTo(receiver.Type().Key()) {
587 if hasArgs {
588 s.errorf("%s is not a method but has arguments", fieldName)
590 result := receiver.MapIndex(nameVal)
591 if !result.IsValid() {
592 switch s.tmpl.option.missingKey {
593 case mapInvalid:
594 // Just use the invalid value.
595 case mapZeroValue:
596 result = reflect.Zero(receiver.Type().Elem())
597 case mapError:
598 s.errorf("map has no entry for key %q", fieldName)
601 return result
604 s.errorf("can't evaluate field %s in type %s", fieldName, typ)
605 panic("not reached")
608 var (
609 errorType = reflect.TypeOf((*error)(nil)).Elem()
610 fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
611 reflectValueType = reflect.TypeOf((*reflect.Value)(nil)).Elem()
614 // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
615 // it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
616 // as the function itself.
617 func (s *state) evalCall(dot, fun reflect.Value, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value {
618 if args != nil {
619 args = args[1:] // Zeroth arg is function name/node; not passed to function.
621 typ := fun.Type()
622 numIn := len(args)
623 if final.IsValid() {
624 numIn++
626 numFixed := len(args)
627 if typ.IsVariadic() {
628 numFixed = typ.NumIn() - 1 // last arg is the variadic one.
629 if numIn < numFixed {
630 s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
632 } else if numIn != typ.NumIn() {
633 s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args))
635 if !goodFunc(typ) {
636 // TODO: This could still be a confusing error; maybe goodFunc should provide info.
637 s.errorf("can't call method/function %q with %d results", name, typ.NumOut())
639 // Build the arg list.
640 argv := make([]reflect.Value, numIn)
641 // Args must be evaluated. Fixed args first.
642 i := 0
643 for ; i < numFixed && i < len(args); i++ {
644 argv[i] = s.evalArg(dot, typ.In(i), args[i])
646 // Now the ... args.
647 if typ.IsVariadic() {
648 argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
649 for ; i < len(args); i++ {
650 argv[i] = s.evalArg(dot, argType, args[i])
653 // Add final value if necessary.
654 if final.IsValid() {
655 t := typ.In(typ.NumIn() - 1)
656 if typ.IsVariadic() {
657 if numIn-1 < numFixed {
658 // The added final argument corresponds to a fixed parameter of the function.
659 // Validate against the type of the actual parameter.
660 t = typ.In(numIn - 1)
661 } else {
662 // The added final argument corresponds to the variadic part.
663 // Validate against the type of the elements of the variadic slice.
664 t = t.Elem()
667 argv[i] = s.validateType(final, t)
669 result := fun.Call(argv)
670 // If we have an error that is not nil, stop execution and return that error to the caller.
671 if len(result) == 2 && !result[1].IsNil() {
672 s.at(node)
673 s.errorf("error calling %s: %s", name, result[1].Interface().(error))
675 v := result[0]
676 if v.Type() == reflectValueType {
677 v = v.Interface().(reflect.Value)
679 return v
682 // canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero.
683 func canBeNil(typ reflect.Type) bool {
684 switch typ.Kind() {
685 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
686 return true
687 case reflect.Struct:
688 return typ == reflectValueType
690 return false
693 // validateType guarantees that the value is valid and assignable to the type.
694 func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
695 if !value.IsValid() {
696 if typ == nil || canBeNil(typ) {
697 // An untyped nil interface{}. Accept as a proper nil value.
698 return reflect.Zero(typ)
700 s.errorf("invalid value; expected %s", typ)
702 if typ == reflectValueType && value.Type() != typ {
703 return reflect.ValueOf(value)
705 if typ != nil && !value.Type().AssignableTo(typ) {
706 if value.Kind() == reflect.Interface && !value.IsNil() {
707 value = value.Elem()
708 if value.Type().AssignableTo(typ) {
709 return value
711 // fallthrough
713 // Does one dereference or indirection work? We could do more, as we
714 // do with method receivers, but that gets messy and method receivers
715 // are much more constrained, so it makes more sense there than here.
716 // Besides, one is almost always all you need.
717 switch {
718 case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
719 value = value.Elem()
720 if !value.IsValid() {
721 s.errorf("dereference of nil pointer of type %s", typ)
723 case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
724 value = value.Addr()
725 default:
726 s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
729 return value
732 func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
733 s.at(n)
734 switch arg := n.(type) {
735 case *parse.DotNode:
736 return s.validateType(dot, typ)
737 case *parse.NilNode:
738 if canBeNil(typ) {
739 return reflect.Zero(typ)
741 s.errorf("cannot assign nil to %s", typ)
742 case *parse.FieldNode:
743 return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, zero), typ)
744 case *parse.VariableNode:
745 return s.validateType(s.evalVariableNode(dot, arg, nil, zero), typ)
746 case *parse.PipeNode:
747 return s.validateType(s.evalPipeline(dot, arg), typ)
748 case *parse.IdentifierNode:
749 return s.validateType(s.evalFunction(dot, arg, arg, nil, zero), typ)
750 case *parse.ChainNode:
751 return s.validateType(s.evalChainNode(dot, arg, nil, zero), typ)
753 switch typ.Kind() {
754 case reflect.Bool:
755 return s.evalBool(typ, n)
756 case reflect.Complex64, reflect.Complex128:
757 return s.evalComplex(typ, n)
758 case reflect.Float32, reflect.Float64:
759 return s.evalFloat(typ, n)
760 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
761 return s.evalInteger(typ, n)
762 case reflect.Interface:
763 if typ.NumMethod() == 0 {
764 return s.evalEmptyInterface(dot, n)
766 case reflect.Struct:
767 if typ == reflectValueType {
768 return reflect.ValueOf(s.evalEmptyInterface(dot, n))
770 case reflect.String:
771 return s.evalString(typ, n)
772 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
773 return s.evalUnsignedInteger(typ, n)
775 s.errorf("can't handle %s for arg of type %s", n, typ)
776 panic("not reached")
779 func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
780 s.at(n)
781 if n, ok := n.(*parse.BoolNode); ok {
782 value := reflect.New(typ).Elem()
783 value.SetBool(n.True)
784 return value
786 s.errorf("expected bool; found %s", n)
787 panic("not reached")
790 func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
791 s.at(n)
792 if n, ok := n.(*parse.StringNode); ok {
793 value := reflect.New(typ).Elem()
794 value.SetString(n.Text)
795 return value
797 s.errorf("expected string; found %s", n)
798 panic("not reached")
801 func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
802 s.at(n)
803 if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
804 value := reflect.New(typ).Elem()
805 value.SetInt(n.Int64)
806 return value
808 s.errorf("expected integer; found %s", n)
809 panic("not reached")
812 func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
813 s.at(n)
814 if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
815 value := reflect.New(typ).Elem()
816 value.SetUint(n.Uint64)
817 return value
819 s.errorf("expected unsigned integer; found %s", n)
820 panic("not reached")
823 func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
824 s.at(n)
825 if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
826 value := reflect.New(typ).Elem()
827 value.SetFloat(n.Float64)
828 return value
830 s.errorf("expected float; found %s", n)
831 panic("not reached")
834 func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
835 if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
836 value := reflect.New(typ).Elem()
837 value.SetComplex(n.Complex128)
838 return value
840 s.errorf("expected complex; found %s", n)
841 panic("not reached")
844 func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
845 s.at(n)
846 switch n := n.(type) {
847 case *parse.BoolNode:
848 return reflect.ValueOf(n.True)
849 case *parse.DotNode:
850 return dot
851 case *parse.FieldNode:
852 return s.evalFieldNode(dot, n, nil, zero)
853 case *parse.IdentifierNode:
854 return s.evalFunction(dot, n, n, nil, zero)
855 case *parse.NilNode:
856 // NilNode is handled in evalArg, the only place that calls here.
857 s.errorf("evalEmptyInterface: nil (can't happen)")
858 case *parse.NumberNode:
859 return s.idealConstant(n)
860 case *parse.StringNode:
861 return reflect.ValueOf(n.Text)
862 case *parse.VariableNode:
863 return s.evalVariableNode(dot, n, nil, zero)
864 case *parse.PipeNode:
865 return s.evalPipeline(dot, n)
867 s.errorf("can't handle assignment of %s to empty interface argument", n)
868 panic("not reached")
871 // indirect returns the item at the end of indirection, and a bool to indicate if it's nil.
872 func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
873 for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
874 if v.IsNil() {
875 return v, true
878 return v, false
881 // indirectInterface returns the concrete value in an interface value,
882 // or else the zero reflect.Value.
883 // That is, if v represents the interface value x, the result is the same as reflect.ValueOf(x):
884 // the fact that x was an interface value is forgotten.
885 func indirectInterface(v reflect.Value) reflect.Value {
886 if v.Kind() != reflect.Interface {
887 return v
889 if v.IsNil() {
890 return reflect.Value{}
892 return v.Elem()
895 // printValue writes the textual representation of the value to the output of
896 // the template.
897 func (s *state) printValue(n parse.Node, v reflect.Value) {
898 s.at(n)
899 iface, ok := printableValue(v)
900 if !ok {
901 s.errorf("can't print %s of type %s", n, v.Type())
903 _, err := fmt.Fprint(s.wr, iface)
904 if err != nil {
905 s.writeError(err)
909 // printableValue returns the, possibly indirected, interface value inside v that
910 // is best for a call to formatted printer.
911 func printableValue(v reflect.Value) (interface{}, bool) {
912 if v.Kind() == reflect.Ptr {
913 v, _ = indirect(v) // fmt.Fprint handles nil.
915 if !v.IsValid() {
916 return "<no value>", true
919 if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
920 if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
921 v = v.Addr()
922 } else {
923 switch v.Kind() {
924 case reflect.Chan, reflect.Func:
925 return nil, false
929 return v.Interface(), true
932 // sortKeys sorts (if it can) the slice of reflect.Values, which is a slice of map keys.
933 func sortKeys(v []reflect.Value) []reflect.Value {
934 if len(v) <= 1 {
935 return v
937 switch v[0].Kind() {
938 case reflect.Float32, reflect.Float64:
939 sort.Slice(v, func(i, j int) bool {
940 return v[i].Float() < v[j].Float()
942 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
943 sort.Slice(v, func(i, j int) bool {
944 return v[i].Int() < v[j].Int()
946 case reflect.String:
947 sort.Slice(v, func(i, j int) bool {
948 return v[i].String() < v[j].String()
950 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
951 sort.Slice(v, func(i, j int) bool {
952 return v[i].Uint() < v[j].Uint()
955 return v