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.
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.
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 {
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 {
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
)
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
) {
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 {
103 // errorf records an ExecError and terminates processing.
104 func (s
*state
) errorf(format
string, args
...interface{}) {
105 name
:= doublePercent(s
.tmpl
.Name())
107 format
= fmt
.Sprintf("template: %s: %s", name
, format
)
109 location
, context
:= s
.tmpl
.ErrorContext(s
.node
)
110 format
= fmt
.Sprintf("template: %s: executing %q at <%s>: %s", location
, name
, doublePercent(context
), format
)
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
) {
132 // errRecover is the handler that turns panics into returns from the top
134 func errRecover(errp
*error
) {
137 switch err
:= e
.(type) {
141 *errp
= err
.Err
// Strip the wrapper.
143 *errp
= err
// Keep the wrapper.
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
{
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
)
186 value
= reflect
.ValueOf(data
)
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
)
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 {
209 for name
, tmpl
:= range t
.tmpl
{
210 if tmpl
.Tree
== nil || tmpl
.Root
== nil {
216 fmt
.Fprintf(&b
, "%q", name
)
220 s
= "; defined templates are: " + b
.String()
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
) {
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
)
238 s
.walkIfOrWith(parse
.NodeIf
, dot
, node
.Pipe
, node
.List
, node
.ElseList
)
239 case *parse
.ListNode
:
240 for _
, node
:= range node
.Nodes
{
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 {
251 case *parse
.WithNode
:
252 s
.walkIfOrWith(parse
.NodeWith
, dot
, node
.Pipe
, node
.List
, node
.ElseList
)
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
)
265 s
.errorf("if/with can't use %v", val
)
268 if typ
== parse
.NodeWith
{
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) {
287 // Something like var x interface{}, never set. It's a form of nil.
291 case reflect
.Array
, reflect
.Map
, reflect
.Slice
, reflect
.String
:
292 truth
= val
.Len() > 0
295 case reflect
.Complex64
, reflect
.Complex128
:
296 truth
= val
.Complex() != 0
297 case reflect
.Chan
, reflect
.Func
, reflect
.Ptr
, reflect
.Interface
:
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
306 truth
= true // Struct values are always true.
313 func (s
*state
) walkRange(dot reflect
.Value
, r
*parse
.RangeNode
) {
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.
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 {
324 // Set next var (lexically the first if there are two) to the index.
325 if len(r
.Pipe
.Decl
) > 1 {
332 case reflect
.Array
, reflect
.Slice
:
336 for i
:= 0; i
< val
.Len(); i
++ {
337 oneIteration(reflect
.ValueOf(i
), val
.Index(i
))
344 for _
, key
:= range sortKeys(val
.MapKeys()) {
345 oneIteration(key
, val
.MapIndex(key
))
354 elem
, ok
:= val
.Recv()
358 oneIteration(reflect
.ValueOf(i
), elem
)
364 case reflect
.Invalid
:
365 break // An invalid value is likely a nil map, etc. and acts like an empty map.
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
) {
376 tmpl
:= s
.tmpl
.tmpl
[t
.Name
]
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
)
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
) {
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
)
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
)
442 s
.notAFunction(cmd
.Args
, final
)
443 switch word
:= firstWord
.(type) {
444 case *parse
.BoolNode
:
445 return reflect
.ValueOf(word
.True
)
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
)
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.
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
)
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
)
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
{
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
{
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.
510 value
:= s
.varValue(variable
.Ident
[0])
511 if len(variable
.Ident
) == 1 {
512 s
.notAFunction(args
, final
)
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
{
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
{
533 function
, ok
:= findFunction(name
, s
.tmpl
)
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
)
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.
555 if ptr
.Kind() != reflect
.Interface
&& ptr
.Kind() != reflect
.Ptr
&& ptr
.CanAddr() {
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() {
565 tField
, ok
:= receiver
.Type().FieldByName(fieldName
)
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.
576 s
.errorf("%s has arguments but cannot be invoked as function", fieldName
)
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()) {
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
{
594 // Just use the invalid value.
596 result
= reflect
.Zero(receiver
.Type().Elem())
598 s
.errorf("map has no entry for key %q", fieldName
)
604 s
.errorf("can't evaluate field %s in type %s", fieldName
, typ
)
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
{
619 args
= args
[1:] // Zeroth arg is function name/node; not passed to function.
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
))
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.
643 for ; i
< numFixed
&& i
< len(args
); i
++ {
644 argv
[i
] = s
.evalArg(dot
, typ
.In(i
), args
[i
])
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.
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)
662 // The added final argument corresponds to the variadic part.
663 // Validate against the type of the elements of the variadic slice.
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() {
673 s
.errorf("error calling %s: %s", name
, result
[1].Interface().(error
))
676 if v
.Type() == reflectValueType
{
677 v
= v
.Interface().(reflect
.Value
)
682 // canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero.
683 func canBeNil(typ reflect
.Type
) bool {
685 case reflect
.Chan
, reflect
.Func
, reflect
.Interface
, reflect
.Map
, reflect
.Ptr
, reflect
.Slice
:
688 return typ
== reflectValueType
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() {
708 if value
.Type().AssignableTo(typ
) {
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.
718 case value
.Kind() == reflect
.Ptr
&& value
.Type().Elem().AssignableTo(typ
):
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():
726 s
.errorf("wrong type for value; expected %s; got %s", typ
, value
.Type())
732 func (s
*state
) evalArg(dot reflect
.Value
, typ reflect
.Type
, n parse
.Node
) reflect
.Value
{
734 switch arg
:= n
.(type) {
736 return s
.validateType(dot
, 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
)
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
)
767 if typ
== reflectValueType
{
768 return reflect
.ValueOf(s
.evalEmptyInterface(dot
, n
))
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
)
779 func (s
*state
) evalBool(typ reflect
.Type
, n parse
.Node
) reflect
.Value
{
781 if n
, ok
:= n
.(*parse
.BoolNode
); ok
{
782 value
:= reflect
.New(typ
).Elem()
783 value
.SetBool(n
.True
)
786 s
.errorf("expected bool; found %s", n
)
790 func (s
*state
) evalString(typ reflect
.Type
, n parse
.Node
) reflect
.Value
{
792 if n
, ok
:= n
.(*parse
.StringNode
); ok
{
793 value
:= reflect
.New(typ
).Elem()
794 value
.SetString(n
.Text
)
797 s
.errorf("expected string; found %s", n
)
801 func (s
*state
) evalInteger(typ reflect
.Type
, n parse
.Node
) reflect
.Value
{
803 if n
, ok
:= n
.(*parse
.NumberNode
); ok
&& n
.IsInt
{
804 value
:= reflect
.New(typ
).Elem()
805 value
.SetInt(n
.Int64
)
808 s
.errorf("expected integer; found %s", n
)
812 func (s
*state
) evalUnsignedInteger(typ reflect
.Type
, n parse
.Node
) reflect
.Value
{
814 if n
, ok
:= n
.(*parse
.NumberNode
); ok
&& n
.IsUint
{
815 value
:= reflect
.New(typ
).Elem()
816 value
.SetUint(n
.Uint64
)
819 s
.errorf("expected unsigned integer; found %s", n
)
823 func (s
*state
) evalFloat(typ reflect
.Type
, n parse
.Node
) reflect
.Value
{
825 if n
, ok
:= n
.(*parse
.NumberNode
); ok
&& n
.IsFloat
{
826 value
:= reflect
.New(typ
).Elem()
827 value
.SetFloat(n
.Float64
)
830 s
.errorf("expected float; found %s", n
)
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
)
840 s
.errorf("expected complex; found %s", n
)
844 func (s
*state
) evalEmptyInterface(dot reflect
.Value
, n parse
.Node
) reflect
.Value
{
846 switch n
:= n
.(type) {
847 case *parse
.BoolNode
:
848 return reflect
.ValueOf(n
.True
)
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
)
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
)
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() {
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
{
890 return reflect
.Value
{}
895 // printValue writes the textual representation of the value to the output of
897 func (s
*state
) printValue(n parse
.Node
, v reflect
.Value
) {
899 iface
, ok
:= printableValue(v
)
901 s
.errorf("can't print %s of type %s", n
, v
.Type())
903 _
, err
:= fmt
.Fprint(s
.wr
, iface
)
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.
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
)) {
924 case reflect
.Chan
, reflect
.Func
:
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
{
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()
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()