libgo: update to Go 1.11
[official-gcc.git] / libgo / go / text / template / exec.go
blob7ee60bd6f6d504c2945e52be9ec6fd4a24883d5f
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 var maxExecDepth = initMaxExecDepth()
24 func initMaxExecDepth() int {
25 // For gccgo we make this 1000 rather than 100000 to avoid
26 // stack overflow on non-split-stack systems.
27 if runtime.GOARCH == "wasm" || runtime.Compiler == "gccgo" {
28 return 1000
30 return 100000
33 // state represents the state of an execution. It's not part of the
34 // template so that multiple executions of the same template
35 // can execute in parallel.
36 type state struct {
37 tmpl *Template
38 wr io.Writer
39 node parse.Node // current node, for errors
40 vars []variable // push-down stack of variable values.
41 depth int // the height of the stack of executing templates.
44 // variable holds the dynamic value of a variable such as $, $x etc.
45 type variable struct {
46 name string
47 value reflect.Value
50 // push pushes a new variable on the stack.
51 func (s *state) push(name string, value reflect.Value) {
52 s.vars = append(s.vars, variable{name, value})
55 // mark returns the length of the variable stack.
56 func (s *state) mark() int {
57 return len(s.vars)
60 // pop pops the variable stack up to the mark.
61 func (s *state) pop(mark int) {
62 s.vars = s.vars[0:mark]
65 // setVar overwrites the last declared variable with the given name.
66 // Used by variable assignments.
67 func (s *state) setVar(name string, value reflect.Value) {
68 for i := s.mark() - 1; i >= 0; i-- {
69 if s.vars[i].name == name {
70 s.vars[i].value = value
71 return
74 s.errorf("undefined variable: %s", name)
77 // setTopVar overwrites the top-nth variable on the stack. Used by range iterations.
78 func (s *state) setTopVar(n int, value reflect.Value) {
79 s.vars[len(s.vars)-n].value = value
82 // varValue returns the value of the named variable.
83 func (s *state) varValue(name string) reflect.Value {
84 for i := s.mark() - 1; i >= 0; i-- {
85 if s.vars[i].name == name {
86 return s.vars[i].value
89 s.errorf("undefined variable: %s", name)
90 return zero
93 var zero reflect.Value
95 type missingValType struct{}
97 var missingVal = reflect.ValueOf(missingValType{})
99 // at marks the state to be on node n, for error reporting.
100 func (s *state) at(node parse.Node) {
101 s.node = node
104 // doublePercent returns the string with %'s replaced by %%, if necessary,
105 // so it can be used safely inside a Printf format string.
106 func doublePercent(str string) string {
107 return strings.Replace(str, "%", "%%", -1)
110 // TODO: It would be nice if ExecError was more broken down, but
111 // the way ErrorContext embeds the template name makes the
112 // processing too clumsy.
114 // ExecError is the custom error type returned when Execute has an
115 // error evaluating its template. (If a write error occurs, the actual
116 // error is returned; it will not be of type ExecError.)
117 type ExecError struct {
118 Name string // Name of template.
119 Err error // Pre-formatted error.
122 func (e ExecError) Error() string {
123 return e.Err.Error()
126 // errorf records an ExecError and terminates processing.
127 func (s *state) errorf(format string, args ...interface{}) {
128 name := doublePercent(s.tmpl.Name())
129 if s.node == nil {
130 format = fmt.Sprintf("template: %s: %s", name, format)
131 } else {
132 location, context := s.tmpl.ErrorContext(s.node)
133 format = fmt.Sprintf("template: %s: executing %q at <%s>: %s", location, name, doublePercent(context), format)
135 panic(ExecError{
136 Name: s.tmpl.Name(),
137 Err: fmt.Errorf(format, args...),
141 // writeError is the wrapper type used internally when Execute has an
142 // error writing to its output. We strip the wrapper in errRecover.
143 // Note that this is not an implementation of error, so it cannot escape
144 // from the package as an error value.
145 type writeError struct {
146 Err error // Original error.
149 func (s *state) writeError(err error) {
150 panic(writeError{
151 Err: err,
155 // errRecover is the handler that turns panics into returns from the top
156 // level of Parse.
157 func errRecover(errp *error) {
158 e := recover()
159 if e != nil {
160 switch err := e.(type) {
161 case runtime.Error:
162 panic(e)
163 case writeError:
164 *errp = err.Err // Strip the wrapper.
165 case ExecError:
166 *errp = err // Keep the wrapper.
167 default:
168 panic(e)
173 // ExecuteTemplate applies the template associated with t that has the given name
174 // to the specified data object and writes the output to wr.
175 // If an error occurs executing the template or writing its output,
176 // execution stops, but partial results may already have been written to
177 // the output writer.
178 // A template may be executed safely in parallel, although if parallel
179 // executions share a Writer the output may be interleaved.
180 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
181 var tmpl *Template
182 if t.common != nil {
183 tmpl = t.tmpl[name]
185 if tmpl == nil {
186 return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
188 return tmpl.Execute(wr, data)
191 // Execute applies a parsed template to the specified data object,
192 // and writes the output to wr.
193 // If an error occurs executing the template or writing its output,
194 // execution stops, but partial results may already have been written to
195 // the output writer.
196 // A template may be executed safely in parallel, although if parallel
197 // executions share a Writer the output may be interleaved.
199 // If data is a reflect.Value, the template applies to the concrete
200 // value that the reflect.Value holds, as in fmt.Print.
201 func (t *Template) Execute(wr io.Writer, data interface{}) error {
202 return t.execute(wr, data)
205 func (t *Template) execute(wr io.Writer, data interface{}) (err error) {
206 defer errRecover(&err)
207 value, ok := data.(reflect.Value)
208 if !ok {
209 value = reflect.ValueOf(data)
211 state := &state{
212 tmpl: t,
213 wr: wr,
214 vars: []variable{{"$", value}},
216 if t.Tree == nil || t.Root == nil {
217 state.errorf("%q is an incomplete or empty template", t.Name())
219 state.walk(value, t.Root)
220 return
223 // DefinedTemplates returns a string listing the defined templates,
224 // prefixed by the string "; defined templates are: ". If there are none,
225 // it returns the empty string. For generating an error message here
226 // and in html/template.
227 func (t *Template) DefinedTemplates() string {
228 if t.common == nil {
229 return ""
231 var b bytes.Buffer
232 for name, tmpl := range t.tmpl {
233 if tmpl.Tree == nil || tmpl.Root == nil {
234 continue
236 if b.Len() > 0 {
237 b.WriteString(", ")
239 fmt.Fprintf(&b, "%q", name)
241 var s string
242 if b.Len() > 0 {
243 s = "; defined templates are: " + b.String()
245 return s
248 // Walk functions step through the major pieces of the template structure,
249 // generating output as they go.
250 func (s *state) walk(dot reflect.Value, node parse.Node) {
251 s.at(node)
252 switch node := node.(type) {
253 case *parse.ActionNode:
254 // Do not pop variables so they persist until next end.
255 // Also, if the action declares variables, don't print the result.
256 val := s.evalPipeline(dot, node.Pipe)
257 if len(node.Pipe.Decl) == 0 {
258 s.printValue(node, val)
260 case *parse.IfNode:
261 s.walkIfOrWith(parse.NodeIf, dot, node.Pipe, node.List, node.ElseList)
262 case *parse.ListNode:
263 for _, node := range node.Nodes {
264 s.walk(dot, node)
266 case *parse.RangeNode:
267 s.walkRange(dot, node)
268 case *parse.TemplateNode:
269 s.walkTemplate(dot, node)
270 case *parse.TextNode:
271 if _, err := s.wr.Write(node.Text); err != nil {
272 s.writeError(err)
274 case *parse.WithNode:
275 s.walkIfOrWith(parse.NodeWith, dot, node.Pipe, node.List, node.ElseList)
276 default:
277 s.errorf("unknown node: %s", node)
281 // walkIfOrWith walks an 'if' or 'with' node. The two control structures
282 // are identical in behavior except that 'with' sets dot.
283 func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
284 defer s.pop(s.mark())
285 val := s.evalPipeline(dot, pipe)
286 truth, ok := isTrue(val)
287 if !ok {
288 s.errorf("if/with can't use %v", val)
290 if truth {
291 if typ == parse.NodeWith {
292 s.walk(val, list)
293 } else {
294 s.walk(dot, list)
296 } else if elseList != nil {
297 s.walk(dot, elseList)
301 // IsTrue reports whether the value is 'true', in the sense of not the zero of its type,
302 // and whether the value has a meaningful truth value. This is the definition of
303 // truth used by if and other such actions.
304 func IsTrue(val interface{}) (truth, ok bool) {
305 return isTrue(reflect.ValueOf(val))
308 func isTrue(val reflect.Value) (truth, ok bool) {
309 if !val.IsValid() {
310 // Something like var x interface{}, never set. It's a form of nil.
311 return false, true
313 switch val.Kind() {
314 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
315 truth = val.Len() > 0
316 case reflect.Bool:
317 truth = val.Bool()
318 case reflect.Complex64, reflect.Complex128:
319 truth = val.Complex() != 0
320 case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
321 truth = !val.IsNil()
322 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
323 truth = val.Int() != 0
324 case reflect.Float32, reflect.Float64:
325 truth = val.Float() != 0
326 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
327 truth = val.Uint() != 0
328 case reflect.Struct:
329 truth = true // Struct values are always true.
330 default:
331 return
333 return truth, true
336 func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
337 s.at(r)
338 defer s.pop(s.mark())
339 val, _ := indirect(s.evalPipeline(dot, r.Pipe))
340 // mark top of stack before any variables in the body are pushed.
341 mark := s.mark()
342 oneIteration := func(index, elem reflect.Value) {
343 // Set top var (lexically the second if there are two) to the element.
344 if len(r.Pipe.Decl) > 0 {
345 s.setTopVar(1, elem)
347 // Set next var (lexically the first if there are two) to the index.
348 if len(r.Pipe.Decl) > 1 {
349 s.setTopVar(2, index)
351 s.walk(elem, r.List)
352 s.pop(mark)
354 switch val.Kind() {
355 case reflect.Array, reflect.Slice:
356 if val.Len() == 0 {
357 break
359 for i := 0; i < val.Len(); i++ {
360 oneIteration(reflect.ValueOf(i), val.Index(i))
362 return
363 case reflect.Map:
364 if val.Len() == 0 {
365 break
367 for _, key := range sortKeys(val.MapKeys()) {
368 oneIteration(key, val.MapIndex(key))
370 return
371 case reflect.Chan:
372 if val.IsNil() {
373 break
375 i := 0
376 for ; ; i++ {
377 elem, ok := val.Recv()
378 if !ok {
379 break
381 oneIteration(reflect.ValueOf(i), elem)
383 if i == 0 {
384 break
386 return
387 case reflect.Invalid:
388 break // An invalid value is likely a nil map, etc. and acts like an empty map.
389 default:
390 s.errorf("range can't iterate over %v", val)
392 if r.ElseList != nil {
393 s.walk(dot, r.ElseList)
397 func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
398 s.at(t)
399 tmpl := s.tmpl.tmpl[t.Name]
400 if tmpl == nil {
401 s.errorf("template %q not defined", t.Name)
403 if s.depth == maxExecDepth {
404 s.errorf("exceeded maximum template depth (%v)", maxExecDepth)
406 // Variables declared by the pipeline persist.
407 dot = s.evalPipeline(dot, t.Pipe)
408 newState := *s
409 newState.depth++
410 newState.tmpl = tmpl
411 // No dynamic scoping: template invocations inherit no variables.
412 newState.vars = []variable{{"$", dot}}
413 newState.walk(dot, tmpl.Root)
416 // Eval functions evaluate pipelines, commands, and their elements and extract
417 // values from the data structure by examining fields, calling methods, and so on.
418 // The printing of those values happens only through walk functions.
420 // evalPipeline returns the value acquired by evaluating a pipeline. If the
421 // pipeline has a variable declaration, the variable will be pushed on the
422 // stack. Callers should therefore pop the stack after they are finished
423 // executing commands depending on the pipeline value.
424 func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
425 if pipe == nil {
426 return
428 s.at(pipe)
429 value = missingVal
430 for _, cmd := range pipe.Cmds {
431 value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
432 // If the object has type interface{}, dig down one level to the thing inside.
433 if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
434 value = reflect.ValueOf(value.Interface()) // lovely!
437 for _, variable := range pipe.Decl {
438 if pipe.IsAssign {
439 s.setVar(variable.Ident[0], value)
440 } else {
441 s.push(variable.Ident[0], value)
444 return value
447 func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
448 if len(args) > 1 || final != missingVal {
449 s.errorf("can't give argument to non-function %s", args[0])
453 func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
454 firstWord := cmd.Args[0]
455 switch n := firstWord.(type) {
456 case *parse.FieldNode:
457 return s.evalFieldNode(dot, n, cmd.Args, final)
458 case *parse.ChainNode:
459 return s.evalChainNode(dot, n, cmd.Args, final)
460 case *parse.IdentifierNode:
461 // Must be a function.
462 return s.evalFunction(dot, n, cmd, cmd.Args, final)
463 case *parse.PipeNode:
464 // Parenthesized pipeline. The arguments are all inside the pipeline; final is ignored.
465 return s.evalPipeline(dot, n)
466 case *parse.VariableNode:
467 return s.evalVariableNode(dot, n, cmd.Args, final)
469 s.at(firstWord)
470 s.notAFunction(cmd.Args, final)
471 switch word := firstWord.(type) {
472 case *parse.BoolNode:
473 return reflect.ValueOf(word.True)
474 case *parse.DotNode:
475 return dot
476 case *parse.NilNode:
477 s.errorf("nil is not a command")
478 case *parse.NumberNode:
479 return s.idealConstant(word)
480 case *parse.StringNode:
481 return reflect.ValueOf(word.Text)
483 s.errorf("can't evaluate command %q", firstWord)
484 panic("not reached")
487 // idealConstant is called to return the value of a number in a context where
488 // we don't know the type. In that case, the syntax of the number tells us
489 // its type, and we use Go rules to resolve. Note there is no such thing as
490 // a uint ideal constant in this situation - the value must be of int type.
491 func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
492 // These are ideal constants but we don't know the type
493 // and we have no context. (If it was a method argument,
494 // we'd know what we need.) The syntax guides us to some extent.
495 s.at(constant)
496 switch {
497 case constant.IsComplex:
498 return reflect.ValueOf(constant.Complex128) // incontrovertible.
499 case constant.IsFloat && !isHexConstant(constant.Text) && strings.ContainsAny(constant.Text, ".eE"):
500 return reflect.ValueOf(constant.Float64)
501 case constant.IsInt:
502 n := int(constant.Int64)
503 if int64(n) != constant.Int64 {
504 s.errorf("%s overflows int", constant.Text)
506 return reflect.ValueOf(n)
507 case constant.IsUint:
508 s.errorf("%s overflows int", constant.Text)
510 return zero
513 func isHexConstant(s string) bool {
514 return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')
517 func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
518 s.at(field)
519 return s.evalFieldChain(dot, dot, field, field.Ident, args, final)
522 func (s *state) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value {
523 s.at(chain)
524 if len(chain.Field) == 0 {
525 s.errorf("internal error: no fields in evalChainNode")
527 if chain.Node.Type() == parse.NodeNil {
528 s.errorf("indirection through explicit nil in %s", chain)
530 // (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields.
531 pipe := s.evalArg(dot, nil, chain.Node)
532 return s.evalFieldChain(dot, pipe, chain, chain.Field, args, final)
535 func (s *state) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
536 // $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
537 s.at(variable)
538 value := s.varValue(variable.Ident[0])
539 if len(variable.Ident) == 1 {
540 s.notAFunction(args, final)
541 return value
543 return s.evalFieldChain(dot, value, variable, variable.Ident[1:], args, final)
546 // evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
547 // dot is the environment in which to evaluate arguments, while
548 // receiver is the value being walked along the chain.
549 func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
550 n := len(ident)
551 for i := 0; i < n-1; i++ {
552 receiver = s.evalField(dot, ident[i], node, nil, missingVal, receiver)
554 // Now if it's a method, it gets the arguments.
555 return s.evalField(dot, ident[n-1], node, args, final, receiver)
558 func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
559 s.at(node)
560 name := node.Ident
561 function, ok := findFunction(name, s.tmpl)
562 if !ok {
563 s.errorf("%q is not a defined function", name)
565 return s.evalCall(dot, function, cmd, name, args, final)
568 // evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
569 // The 'final' argument represents the return value from the preceding
570 // value of the pipeline, if any.
571 func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
572 if !receiver.IsValid() {
573 if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key.
574 s.errorf("nil data; no entry for key %q", fieldName)
576 return zero
578 typ := receiver.Type()
579 receiver, isNil := indirect(receiver)
580 // Unless it's an interface, need to get to a value of type *T to guarantee
581 // we see all methods of T and *T.
582 ptr := receiver
583 if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Ptr && ptr.CanAddr() {
584 ptr = ptr.Addr()
586 if method := ptr.MethodByName(fieldName); method.IsValid() {
587 return s.evalCall(dot, method, node, fieldName, args, final)
589 hasArgs := len(args) > 1 || final != missingVal
590 // It's not a method; must be a field of a struct or an element of a map.
591 switch receiver.Kind() {
592 case reflect.Struct:
593 tField, ok := receiver.Type().FieldByName(fieldName)
594 if ok {
595 if isNil {
596 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
598 field := receiver.FieldByIndex(tField.Index)
599 if tField.PkgPath != "" { // field is unexported
600 s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
602 // If it's a function, we must call it.
603 if hasArgs {
604 s.errorf("%s has arguments but cannot be invoked as function", fieldName)
606 return field
608 case reflect.Map:
609 if isNil {
610 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
612 // If it's a map, attempt to use the field name as a key.
613 nameVal := reflect.ValueOf(fieldName)
614 if nameVal.Type().AssignableTo(receiver.Type().Key()) {
615 if hasArgs {
616 s.errorf("%s is not a method but has arguments", fieldName)
618 result := receiver.MapIndex(nameVal)
619 if !result.IsValid() {
620 switch s.tmpl.option.missingKey {
621 case mapInvalid:
622 // Just use the invalid value.
623 case mapZeroValue:
624 result = reflect.Zero(receiver.Type().Elem())
625 case mapError:
626 s.errorf("map has no entry for key %q", fieldName)
629 return result
632 s.errorf("can't evaluate field %s in type %s", fieldName, typ)
633 panic("not reached")
636 var (
637 errorType = reflect.TypeOf((*error)(nil)).Elem()
638 fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
639 reflectValueType = reflect.TypeOf((*reflect.Value)(nil)).Elem()
642 // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
643 // it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
644 // as the function itself.
645 func (s *state) evalCall(dot, fun reflect.Value, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value {
646 if args != nil {
647 args = args[1:] // Zeroth arg is function name/node; not passed to function.
649 typ := fun.Type()
650 numIn := len(args)
651 if final != missingVal {
652 numIn++
654 numFixed := len(args)
655 if typ.IsVariadic() {
656 numFixed = typ.NumIn() - 1 // last arg is the variadic one.
657 if numIn < numFixed {
658 s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
660 } else if numIn != typ.NumIn() {
661 s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), numIn)
663 if !goodFunc(typ) {
664 // TODO: This could still be a confusing error; maybe goodFunc should provide info.
665 s.errorf("can't call method/function %q with %d results", name, typ.NumOut())
667 // Build the arg list.
668 argv := make([]reflect.Value, numIn)
669 // Args must be evaluated. Fixed args first.
670 i := 0
671 for ; i < numFixed && i < len(args); i++ {
672 argv[i] = s.evalArg(dot, typ.In(i), args[i])
674 // Now the ... args.
675 if typ.IsVariadic() {
676 argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
677 for ; i < len(args); i++ {
678 argv[i] = s.evalArg(dot, argType, args[i])
681 // Add final value if necessary.
682 if final != missingVal {
683 t := typ.In(typ.NumIn() - 1)
684 if typ.IsVariadic() {
685 if numIn-1 < numFixed {
686 // The added final argument corresponds to a fixed parameter of the function.
687 // Validate against the type of the actual parameter.
688 t = typ.In(numIn - 1)
689 } else {
690 // The added final argument corresponds to the variadic part.
691 // Validate against the type of the elements of the variadic slice.
692 t = t.Elem()
695 argv[i] = s.validateType(final, t)
697 result := fun.Call(argv)
698 // If we have an error that is not nil, stop execution and return that error to the caller.
699 if len(result) == 2 && !result[1].IsNil() {
700 s.at(node)
701 s.errorf("error calling %s: %s", name, result[1].Interface().(error))
703 v := result[0]
704 if v.Type() == reflectValueType {
705 v = v.Interface().(reflect.Value)
707 return v
710 // canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero.
711 func canBeNil(typ reflect.Type) bool {
712 switch typ.Kind() {
713 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
714 return true
715 case reflect.Struct:
716 return typ == reflectValueType
718 return false
721 // validateType guarantees that the value is valid and assignable to the type.
722 func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
723 if !value.IsValid() {
724 if typ == nil {
725 // An untyped nil interface{}. Accept as a proper nil value.
726 return reflect.ValueOf(nil)
728 if canBeNil(typ) {
729 // Like above, but use the zero value of the non-nil type.
730 return reflect.Zero(typ)
732 s.errorf("invalid value; expected %s", typ)
734 if typ == reflectValueType && value.Type() != typ {
735 return reflect.ValueOf(value)
737 if typ != nil && !value.Type().AssignableTo(typ) {
738 if value.Kind() == reflect.Interface && !value.IsNil() {
739 value = value.Elem()
740 if value.Type().AssignableTo(typ) {
741 return value
743 // fallthrough
745 // Does one dereference or indirection work? We could do more, as we
746 // do with method receivers, but that gets messy and method receivers
747 // are much more constrained, so it makes more sense there than here.
748 // Besides, one is almost always all you need.
749 switch {
750 case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
751 value = value.Elem()
752 if !value.IsValid() {
753 s.errorf("dereference of nil pointer of type %s", typ)
755 case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
756 value = value.Addr()
757 default:
758 s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
761 return value
764 func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
765 s.at(n)
766 switch arg := n.(type) {
767 case *parse.DotNode:
768 return s.validateType(dot, typ)
769 case *parse.NilNode:
770 if canBeNil(typ) {
771 return reflect.Zero(typ)
773 s.errorf("cannot assign nil to %s", typ)
774 case *parse.FieldNode:
775 return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, missingVal), typ)
776 case *parse.VariableNode:
777 return s.validateType(s.evalVariableNode(dot, arg, nil, missingVal), typ)
778 case *parse.PipeNode:
779 return s.validateType(s.evalPipeline(dot, arg), typ)
780 case *parse.IdentifierNode:
781 return s.validateType(s.evalFunction(dot, arg, arg, nil, missingVal), typ)
782 case *parse.ChainNode:
783 return s.validateType(s.evalChainNode(dot, arg, nil, missingVal), typ)
785 switch typ.Kind() {
786 case reflect.Bool:
787 return s.evalBool(typ, n)
788 case reflect.Complex64, reflect.Complex128:
789 return s.evalComplex(typ, n)
790 case reflect.Float32, reflect.Float64:
791 return s.evalFloat(typ, n)
792 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
793 return s.evalInteger(typ, n)
794 case reflect.Interface:
795 if typ.NumMethod() == 0 {
796 return s.evalEmptyInterface(dot, n)
798 case reflect.Struct:
799 if typ == reflectValueType {
800 return reflect.ValueOf(s.evalEmptyInterface(dot, n))
802 case reflect.String:
803 return s.evalString(typ, n)
804 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
805 return s.evalUnsignedInteger(typ, n)
807 s.errorf("can't handle %s for arg of type %s", n, typ)
808 panic("not reached")
811 func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
812 s.at(n)
813 if n, ok := n.(*parse.BoolNode); ok {
814 value := reflect.New(typ).Elem()
815 value.SetBool(n.True)
816 return value
818 s.errorf("expected bool; found %s", n)
819 panic("not reached")
822 func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
823 s.at(n)
824 if n, ok := n.(*parse.StringNode); ok {
825 value := reflect.New(typ).Elem()
826 value.SetString(n.Text)
827 return value
829 s.errorf("expected string; found %s", n)
830 panic("not reached")
833 func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
834 s.at(n)
835 if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
836 value := reflect.New(typ).Elem()
837 value.SetInt(n.Int64)
838 return value
840 s.errorf("expected integer; found %s", n)
841 panic("not reached")
844 func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
845 s.at(n)
846 if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
847 value := reflect.New(typ).Elem()
848 value.SetUint(n.Uint64)
849 return value
851 s.errorf("expected unsigned integer; found %s", n)
852 panic("not reached")
855 func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
856 s.at(n)
857 if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
858 value := reflect.New(typ).Elem()
859 value.SetFloat(n.Float64)
860 return value
862 s.errorf("expected float; found %s", n)
863 panic("not reached")
866 func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
867 if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
868 value := reflect.New(typ).Elem()
869 value.SetComplex(n.Complex128)
870 return value
872 s.errorf("expected complex; found %s", n)
873 panic("not reached")
876 func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
877 s.at(n)
878 switch n := n.(type) {
879 case *parse.BoolNode:
880 return reflect.ValueOf(n.True)
881 case *parse.DotNode:
882 return dot
883 case *parse.FieldNode:
884 return s.evalFieldNode(dot, n, nil, missingVal)
885 case *parse.IdentifierNode:
886 return s.evalFunction(dot, n, n, nil, missingVal)
887 case *parse.NilNode:
888 // NilNode is handled in evalArg, the only place that calls here.
889 s.errorf("evalEmptyInterface: nil (can't happen)")
890 case *parse.NumberNode:
891 return s.idealConstant(n)
892 case *parse.StringNode:
893 return reflect.ValueOf(n.Text)
894 case *parse.VariableNode:
895 return s.evalVariableNode(dot, n, nil, missingVal)
896 case *parse.PipeNode:
897 return s.evalPipeline(dot, n)
899 s.errorf("can't handle assignment of %s to empty interface argument", n)
900 panic("not reached")
903 // indirect returns the item at the end of indirection, and a bool to indicate if it's nil.
904 func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
905 for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
906 if v.IsNil() {
907 return v, true
910 return v, false
913 // indirectInterface returns the concrete value in an interface value,
914 // or else the zero reflect.Value.
915 // That is, if v represents the interface value x, the result is the same as reflect.ValueOf(x):
916 // the fact that x was an interface value is forgotten.
917 func indirectInterface(v reflect.Value) reflect.Value {
918 if v.Kind() != reflect.Interface {
919 return v
921 if v.IsNil() {
922 return reflect.Value{}
924 return v.Elem()
927 // printValue writes the textual representation of the value to the output of
928 // the template.
929 func (s *state) printValue(n parse.Node, v reflect.Value) {
930 s.at(n)
931 iface, ok := printableValue(v)
932 if !ok {
933 s.errorf("can't print %s of type %s", n, v.Type())
935 _, err := fmt.Fprint(s.wr, iface)
936 if err != nil {
937 s.writeError(err)
941 // printableValue returns the, possibly indirected, interface value inside v that
942 // is best for a call to formatted printer.
943 func printableValue(v reflect.Value) (interface{}, bool) {
944 if v.Kind() == reflect.Ptr {
945 v, _ = indirect(v) // fmt.Fprint handles nil.
947 if !v.IsValid() {
948 return "<no value>", true
951 if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
952 if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
953 v = v.Addr()
954 } else {
955 switch v.Kind() {
956 case reflect.Chan, reflect.Func:
957 return nil, false
961 return v.Interface(), true
964 // sortKeys sorts (if it can) the slice of reflect.Values, which is a slice of map keys.
965 func sortKeys(v []reflect.Value) []reflect.Value {
966 if len(v) <= 1 {
967 return v
969 switch v[0].Kind() {
970 case reflect.Float32, reflect.Float64:
971 sort.Slice(v, func(i, j int) bool {
972 return v[i].Float() < v[j].Float()
974 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
975 sort.Slice(v, func(i, j int) bool {
976 return v[i].Int() < v[j].Int()
978 case reflect.String:
979 sort.Slice(v, func(i, j int) bool {
980 return v[i].String() < v[j].String()
982 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
983 sort.Slice(v, func(i, j int) bool {
984 return v[i].Uint() < v[j].Uint()
987 return v