1 |
747 |
jeremybenn |
// 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.
|
4 |
|
|
|
5 |
|
|
package template
|
6 |
|
|
|
7 |
|
|
import (
|
8 |
|
|
"fmt"
|
9 |
|
|
"io"
|
10 |
|
|
"reflect"
|
11 |
|
|
"runtime"
|
12 |
|
|
"sort"
|
13 |
|
|
"strings"
|
14 |
|
|
"text/template/parse"
|
15 |
|
|
)
|
16 |
|
|
|
17 |
|
|
// state represents the state of an execution. It's not part of the
|
18 |
|
|
// template so that multiple executions of the same template
|
19 |
|
|
// can execute in parallel.
|
20 |
|
|
type state struct {
|
21 |
|
|
tmpl *Template
|
22 |
|
|
wr io.Writer
|
23 |
|
|
line int // line number for errors
|
24 |
|
|
vars []variable // push-down stack of variable values.
|
25 |
|
|
}
|
26 |
|
|
|
27 |
|
|
// variable holds the dynamic value of a variable such as $, $x etc.
|
28 |
|
|
type variable struct {
|
29 |
|
|
name string
|
30 |
|
|
value reflect.Value
|
31 |
|
|
}
|
32 |
|
|
|
33 |
|
|
// push pushes a new variable on the stack.
|
34 |
|
|
func (s *state) push(name string, value reflect.Value) {
|
35 |
|
|
s.vars = append(s.vars, variable{name, value})
|
36 |
|
|
}
|
37 |
|
|
|
38 |
|
|
// mark returns the length of the variable stack.
|
39 |
|
|
func (s *state) mark() int {
|
40 |
|
|
return len(s.vars)
|
41 |
|
|
}
|
42 |
|
|
|
43 |
|
|
// pop pops the variable stack up to the mark.
|
44 |
|
|
func (s *state) pop(mark int) {
|
45 |
|
|
s.vars = s.vars[0:mark]
|
46 |
|
|
}
|
47 |
|
|
|
48 |
|
|
// setVar overwrites the top-nth variable on the stack. Used by range iterations.
|
49 |
|
|
func (s *state) setVar(n int, value reflect.Value) {
|
50 |
|
|
s.vars[len(s.vars)-n].value = value
|
51 |
|
|
}
|
52 |
|
|
|
53 |
|
|
// varValue returns the value of the named variable.
|
54 |
|
|
func (s *state) varValue(name string) reflect.Value {
|
55 |
|
|
for i := s.mark() - 1; i >= 0; i-- {
|
56 |
|
|
if s.vars[i].name == name {
|
57 |
|
|
return s.vars[i].value
|
58 |
|
|
}
|
59 |
|
|
}
|
60 |
|
|
s.errorf("undefined variable: %s", name)
|
61 |
|
|
return zero
|
62 |
|
|
}
|
63 |
|
|
|
64 |
|
|
var zero reflect.Value
|
65 |
|
|
|
66 |
|
|
// errorf formats the error and terminates processing.
|
67 |
|
|
func (s *state) errorf(format string, args ...interface{}) {
|
68 |
|
|
format = fmt.Sprintf("template: %s:%d: %s", s.tmpl.Name(), s.line, format)
|
69 |
|
|
panic(fmt.Errorf(format, args...))
|
70 |
|
|
}
|
71 |
|
|
|
72 |
|
|
// error terminates processing.
|
73 |
|
|
func (s *state) error(err error) {
|
74 |
|
|
s.errorf("%s", err)
|
75 |
|
|
}
|
76 |
|
|
|
77 |
|
|
// errRecover is the handler that turns panics into returns from the top
|
78 |
|
|
// level of Parse.
|
79 |
|
|
func errRecover(errp *error) {
|
80 |
|
|
e := recover()
|
81 |
|
|
if e != nil {
|
82 |
|
|
switch err := e.(type) {
|
83 |
|
|
case runtime.Error:
|
84 |
|
|
panic(e)
|
85 |
|
|
case error:
|
86 |
|
|
*errp = err
|
87 |
|
|
default:
|
88 |
|
|
panic(e)
|
89 |
|
|
}
|
90 |
|
|
}
|
91 |
|
|
}
|
92 |
|
|
|
93 |
|
|
// ExecuteTemplate applies the template associated with t that has the given name
|
94 |
|
|
// to the specified data object and writes the output to wr.
|
95 |
|
|
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
|
96 |
|
|
tmpl := t.tmpl[name]
|
97 |
|
|
if tmpl == nil {
|
98 |
|
|
return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
|
99 |
|
|
}
|
100 |
|
|
return tmpl.Execute(wr, data)
|
101 |
|
|
}
|
102 |
|
|
|
103 |
|
|
// Execute applies a parsed template to the specified data object,
|
104 |
|
|
// and writes the output to wr.
|
105 |
|
|
func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
|
106 |
|
|
defer errRecover(&err)
|
107 |
|
|
value := reflect.ValueOf(data)
|
108 |
|
|
state := &state{
|
109 |
|
|
tmpl: t,
|
110 |
|
|
wr: wr,
|
111 |
|
|
line: 1,
|
112 |
|
|
vars: []variable{{"$", value}},
|
113 |
|
|
}
|
114 |
|
|
if t.Tree == nil || t.Root == nil {
|
115 |
|
|
state.errorf("%q is an incomplete or empty template", t.name)
|
116 |
|
|
}
|
117 |
|
|
state.walk(value, t.Root)
|
118 |
|
|
return
|
119 |
|
|
}
|
120 |
|
|
|
121 |
|
|
// Walk functions step through the major pieces of the template structure,
|
122 |
|
|
// generating output as they go.
|
123 |
|
|
func (s *state) walk(dot reflect.Value, n parse.Node) {
|
124 |
|
|
switch n := n.(type) {
|
125 |
|
|
case *parse.ActionNode:
|
126 |
|
|
s.line = n.Line
|
127 |
|
|
// Do not pop variables so they persist until next end.
|
128 |
|
|
// Also, if the action declares variables, don't print the result.
|
129 |
|
|
val := s.evalPipeline(dot, n.Pipe)
|
130 |
|
|
if len(n.Pipe.Decl) == 0 {
|
131 |
|
|
s.printValue(n, val)
|
132 |
|
|
}
|
133 |
|
|
case *parse.IfNode:
|
134 |
|
|
s.line = n.Line
|
135 |
|
|
s.walkIfOrWith(parse.NodeIf, dot, n.Pipe, n.List, n.ElseList)
|
136 |
|
|
case *parse.ListNode:
|
137 |
|
|
for _, node := range n.Nodes {
|
138 |
|
|
s.walk(dot, node)
|
139 |
|
|
}
|
140 |
|
|
case *parse.RangeNode:
|
141 |
|
|
s.line = n.Line
|
142 |
|
|
s.walkRange(dot, n)
|
143 |
|
|
case *parse.TemplateNode:
|
144 |
|
|
s.line = n.Line
|
145 |
|
|
s.walkTemplate(dot, n)
|
146 |
|
|
case *parse.TextNode:
|
147 |
|
|
if _, err := s.wr.Write(n.Text); err != nil {
|
148 |
|
|
s.error(err)
|
149 |
|
|
}
|
150 |
|
|
case *parse.WithNode:
|
151 |
|
|
s.line = n.Line
|
152 |
|
|
s.walkIfOrWith(parse.NodeWith, dot, n.Pipe, n.List, n.ElseList)
|
153 |
|
|
default:
|
154 |
|
|
s.errorf("unknown node: %s", n)
|
155 |
|
|
}
|
156 |
|
|
}
|
157 |
|
|
|
158 |
|
|
// walkIfOrWith walks an 'if' or 'with' node. The two control structures
|
159 |
|
|
// are identical in behavior except that 'with' sets dot.
|
160 |
|
|
func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
|
161 |
|
|
defer s.pop(s.mark())
|
162 |
|
|
val := s.evalPipeline(dot, pipe)
|
163 |
|
|
truth, ok := isTrue(val)
|
164 |
|
|
if !ok {
|
165 |
|
|
s.errorf("if/with can't use %v", val)
|
166 |
|
|
}
|
167 |
|
|
if truth {
|
168 |
|
|
if typ == parse.NodeWith {
|
169 |
|
|
s.walk(val, list)
|
170 |
|
|
} else {
|
171 |
|
|
s.walk(dot, list)
|
172 |
|
|
}
|
173 |
|
|
} else if elseList != nil {
|
174 |
|
|
s.walk(dot, elseList)
|
175 |
|
|
}
|
176 |
|
|
}
|
177 |
|
|
|
178 |
|
|
// isTrue returns whether the value is 'true', in the sense of not the zero of its type,
|
179 |
|
|
// and whether the value has a meaningful truth value.
|
180 |
|
|
func isTrue(val reflect.Value) (truth, ok bool) {
|
181 |
|
|
if !val.IsValid() {
|
182 |
|
|
// Something like var x interface{}, never set. It's a form of nil.
|
183 |
|
|
return false, true
|
184 |
|
|
}
|
185 |
|
|
switch val.Kind() {
|
186 |
|
|
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
|
187 |
|
|
truth = val.Len() > 0
|
188 |
|
|
case reflect.Bool:
|
189 |
|
|
truth = val.Bool()
|
190 |
|
|
case reflect.Complex64, reflect.Complex128:
|
191 |
|
|
truth = val.Complex() != 0
|
192 |
|
|
case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
|
193 |
|
|
truth = !val.IsNil()
|
194 |
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
195 |
|
|
truth = val.Int() != 0
|
196 |
|
|
case reflect.Float32, reflect.Float64:
|
197 |
|
|
truth = val.Float() != 0
|
198 |
|
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
199 |
|
|
truth = val.Uint() != 0
|
200 |
|
|
case reflect.Struct:
|
201 |
|
|
truth = true // Struct values are always true.
|
202 |
|
|
default:
|
203 |
|
|
return
|
204 |
|
|
}
|
205 |
|
|
return truth, true
|
206 |
|
|
}
|
207 |
|
|
|
208 |
|
|
func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
|
209 |
|
|
defer s.pop(s.mark())
|
210 |
|
|
val, _ := indirect(s.evalPipeline(dot, r.Pipe))
|
211 |
|
|
// mark top of stack before any variables in the body are pushed.
|
212 |
|
|
mark := s.mark()
|
213 |
|
|
oneIteration := func(index, elem reflect.Value) {
|
214 |
|
|
// Set top var (lexically the second if there are two) to the element.
|
215 |
|
|
if len(r.Pipe.Decl) > 0 {
|
216 |
|
|
s.setVar(1, elem)
|
217 |
|
|
}
|
218 |
|
|
// Set next var (lexically the first if there are two) to the index.
|
219 |
|
|
if len(r.Pipe.Decl) > 1 {
|
220 |
|
|
s.setVar(2, index)
|
221 |
|
|
}
|
222 |
|
|
s.walk(elem, r.List)
|
223 |
|
|
s.pop(mark)
|
224 |
|
|
}
|
225 |
|
|
switch val.Kind() {
|
226 |
|
|
case reflect.Array, reflect.Slice:
|
227 |
|
|
if val.Len() == 0 {
|
228 |
|
|
break
|
229 |
|
|
}
|
230 |
|
|
for i := 0; i < val.Len(); i++ {
|
231 |
|
|
oneIteration(reflect.ValueOf(i), val.Index(i))
|
232 |
|
|
}
|
233 |
|
|
return
|
234 |
|
|
case reflect.Map:
|
235 |
|
|
if val.Len() == 0 {
|
236 |
|
|
break
|
237 |
|
|
}
|
238 |
|
|
for _, key := range sortKeys(val.MapKeys()) {
|
239 |
|
|
oneIteration(key, val.MapIndex(key))
|
240 |
|
|
}
|
241 |
|
|
return
|
242 |
|
|
case reflect.Chan:
|
243 |
|
|
if val.IsNil() {
|
244 |
|
|
break
|
245 |
|
|
}
|
246 |
|
|
i := 0
|
247 |
|
|
for ; ; i++ {
|
248 |
|
|
elem, ok := val.Recv()
|
249 |
|
|
if !ok {
|
250 |
|
|
break
|
251 |
|
|
}
|
252 |
|
|
oneIteration(reflect.ValueOf(i), elem)
|
253 |
|
|
}
|
254 |
|
|
if i == 0 {
|
255 |
|
|
break
|
256 |
|
|
}
|
257 |
|
|
return
|
258 |
|
|
case reflect.Invalid:
|
259 |
|
|
break // An invalid value is likely a nil map, etc. and acts like an empty map.
|
260 |
|
|
default:
|
261 |
|
|
s.errorf("range can't iterate over %v", val)
|
262 |
|
|
}
|
263 |
|
|
if r.ElseList != nil {
|
264 |
|
|
s.walk(dot, r.ElseList)
|
265 |
|
|
}
|
266 |
|
|
}
|
267 |
|
|
|
268 |
|
|
func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
|
269 |
|
|
tmpl := s.tmpl.tmpl[t.Name]
|
270 |
|
|
if tmpl == nil {
|
271 |
|
|
s.errorf("template %q not defined", t.Name)
|
272 |
|
|
}
|
273 |
|
|
// Variables declared by the pipeline persist.
|
274 |
|
|
dot = s.evalPipeline(dot, t.Pipe)
|
275 |
|
|
newState := *s
|
276 |
|
|
newState.tmpl = tmpl
|
277 |
|
|
// No dynamic scoping: template invocations inherit no variables.
|
278 |
|
|
newState.vars = []variable{{"$", dot}}
|
279 |
|
|
newState.walk(dot, tmpl.Root)
|
280 |
|
|
}
|
281 |
|
|
|
282 |
|
|
// Eval functions evaluate pipelines, commands, and their elements and extract
|
283 |
|
|
// values from the data structure by examining fields, calling methods, and so on.
|
284 |
|
|
// The printing of those values happens only through walk functions.
|
285 |
|
|
|
286 |
|
|
// evalPipeline returns the value acquired by evaluating a pipeline. If the
|
287 |
|
|
// pipeline has a variable declaration, the variable will be pushed on the
|
288 |
|
|
// stack. Callers should therefore pop the stack after they are finished
|
289 |
|
|
// executing commands depending on the pipeline value.
|
290 |
|
|
func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
|
291 |
|
|
if pipe == nil {
|
292 |
|
|
return
|
293 |
|
|
}
|
294 |
|
|
for _, cmd := range pipe.Cmds {
|
295 |
|
|
value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
|
296 |
|
|
// If the object has type interface{}, dig down one level to the thing inside.
|
297 |
|
|
if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
|
298 |
|
|
value = reflect.ValueOf(value.Interface()) // lovely!
|
299 |
|
|
}
|
300 |
|
|
}
|
301 |
|
|
for _, variable := range pipe.Decl {
|
302 |
|
|
s.push(variable.Ident[0], value)
|
303 |
|
|
}
|
304 |
|
|
return value
|
305 |
|
|
}
|
306 |
|
|
|
307 |
|
|
func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
|
308 |
|
|
if len(args) > 1 || final.IsValid() {
|
309 |
|
|
s.errorf("can't give argument to non-function %s", args[0])
|
310 |
|
|
}
|
311 |
|
|
}
|
312 |
|
|
|
313 |
|
|
func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
|
314 |
|
|
firstWord := cmd.Args[0]
|
315 |
|
|
switch n := firstWord.(type) {
|
316 |
|
|
case *parse.FieldNode:
|
317 |
|
|
return s.evalFieldNode(dot, n, cmd.Args, final)
|
318 |
|
|
case *parse.IdentifierNode:
|
319 |
|
|
// Must be a function.
|
320 |
|
|
return s.evalFunction(dot, n.Ident, cmd.Args, final)
|
321 |
|
|
case *parse.VariableNode:
|
322 |
|
|
return s.evalVariableNode(dot, n, cmd.Args, final)
|
323 |
|
|
}
|
324 |
|
|
s.notAFunction(cmd.Args, final)
|
325 |
|
|
switch word := firstWord.(type) {
|
326 |
|
|
case *parse.BoolNode:
|
327 |
|
|
return reflect.ValueOf(word.True)
|
328 |
|
|
case *parse.DotNode:
|
329 |
|
|
return dot
|
330 |
|
|
case *parse.NumberNode:
|
331 |
|
|
return s.idealConstant(word)
|
332 |
|
|
case *parse.StringNode:
|
333 |
|
|
return reflect.ValueOf(word.Text)
|
334 |
|
|
}
|
335 |
|
|
s.errorf("can't evaluate command %q", firstWord)
|
336 |
|
|
panic("not reached")
|
337 |
|
|
}
|
338 |
|
|
|
339 |
|
|
// idealConstant is called to return the value of a number in a context where
|
340 |
|
|
// we don't know the type. In that case, the syntax of the number tells us
|
341 |
|
|
// its type, and we use Go rules to resolve. Note there is no such thing as
|
342 |
|
|
// a uint ideal constant in this situation - the value must be of int type.
|
343 |
|
|
func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
|
344 |
|
|
// These are ideal constants but we don't know the type
|
345 |
|
|
// and we have no context. (If it was a method argument,
|
346 |
|
|
// we'd know what we need.) The syntax guides us to some extent.
|
347 |
|
|
switch {
|
348 |
|
|
case constant.IsComplex:
|
349 |
|
|
return reflect.ValueOf(constant.Complex128) // incontrovertible.
|
350 |
|
|
case constant.IsFloat && strings.IndexAny(constant.Text, ".eE") >= 0:
|
351 |
|
|
return reflect.ValueOf(constant.Float64)
|
352 |
|
|
case constant.IsInt:
|
353 |
|
|
n := int(constant.Int64)
|
354 |
|
|
if int64(n) != constant.Int64 {
|
355 |
|
|
s.errorf("%s overflows int", constant.Text)
|
356 |
|
|
}
|
357 |
|
|
return reflect.ValueOf(n)
|
358 |
|
|
case constant.IsUint:
|
359 |
|
|
s.errorf("%s overflows int", constant.Text)
|
360 |
|
|
}
|
361 |
|
|
return zero
|
362 |
|
|
}
|
363 |
|
|
|
364 |
|
|
func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
|
365 |
|
|
return s.evalFieldChain(dot, dot, field.Ident, args, final)
|
366 |
|
|
}
|
367 |
|
|
|
368 |
|
|
func (s *state) evalVariableNode(dot reflect.Value, v *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
|
369 |
|
|
// $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
|
370 |
|
|
value := s.varValue(v.Ident[0])
|
371 |
|
|
if len(v.Ident) == 1 {
|
372 |
|
|
return value
|
373 |
|
|
}
|
374 |
|
|
return s.evalFieldChain(dot, value, v.Ident[1:], args, final)
|
375 |
|
|
}
|
376 |
|
|
|
377 |
|
|
// evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
|
378 |
|
|
// dot is the environment in which to evaluate arguments, while
|
379 |
|
|
// receiver is the value being walked along the chain.
|
380 |
|
|
func (s *state) evalFieldChain(dot, receiver reflect.Value, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
|
381 |
|
|
n := len(ident)
|
382 |
|
|
for i := 0; i < n-1; i++ {
|
383 |
|
|
receiver = s.evalField(dot, ident[i], nil, zero, receiver)
|
384 |
|
|
}
|
385 |
|
|
// Now if it's a method, it gets the arguments.
|
386 |
|
|
return s.evalField(dot, ident[n-1], args, final, receiver)
|
387 |
|
|
}
|
388 |
|
|
|
389 |
|
|
func (s *state) evalFunction(dot reflect.Value, name string, args []parse.Node, final reflect.Value) reflect.Value {
|
390 |
|
|
function, ok := findFunction(name, s.tmpl)
|
391 |
|
|
if !ok {
|
392 |
|
|
s.errorf("%q is not a defined function", name)
|
393 |
|
|
}
|
394 |
|
|
return s.evalCall(dot, function, name, args, final)
|
395 |
|
|
}
|
396 |
|
|
|
397 |
|
|
// evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
|
398 |
|
|
// The 'final' argument represents the return value from the preceding
|
399 |
|
|
// value of the pipeline, if any.
|
400 |
|
|
func (s *state) evalField(dot reflect.Value, fieldName string, args []parse.Node, final, receiver reflect.Value) reflect.Value {
|
401 |
|
|
if !receiver.IsValid() {
|
402 |
|
|
return zero
|
403 |
|
|
}
|
404 |
|
|
typ := receiver.Type()
|
405 |
|
|
receiver, _ = indirect(receiver)
|
406 |
|
|
// Unless it's an interface, need to get to a value of type *T to guarantee
|
407 |
|
|
// we see all methods of T and *T.
|
408 |
|
|
ptr := receiver
|
409 |
|
|
if ptr.Kind() != reflect.Interface && ptr.CanAddr() {
|
410 |
|
|
ptr = ptr.Addr()
|
411 |
|
|
}
|
412 |
|
|
if method := ptr.MethodByName(fieldName); method.IsValid() {
|
413 |
|
|
return s.evalCall(dot, method, fieldName, args, final)
|
414 |
|
|
}
|
415 |
|
|
hasArgs := len(args) > 1 || final.IsValid()
|
416 |
|
|
// It's not a method; is it a field of a struct?
|
417 |
|
|
receiver, isNil := indirect(receiver)
|
418 |
|
|
if receiver.Kind() == reflect.Struct {
|
419 |
|
|
tField, ok := receiver.Type().FieldByName(fieldName)
|
420 |
|
|
if ok {
|
421 |
|
|
field := receiver.FieldByIndex(tField.Index)
|
422 |
|
|
if hasArgs {
|
423 |
|
|
s.errorf("%s is not a method but has arguments", fieldName)
|
424 |
|
|
}
|
425 |
|
|
if tField.PkgPath == "" { // field is exported
|
426 |
|
|
return field
|
427 |
|
|
}
|
428 |
|
|
}
|
429 |
|
|
}
|
430 |
|
|
// If it's a map, attempt to use the field name as a key.
|
431 |
|
|
if receiver.Kind() == reflect.Map {
|
432 |
|
|
nameVal := reflect.ValueOf(fieldName)
|
433 |
|
|
if nameVal.Type().AssignableTo(receiver.Type().Key()) {
|
434 |
|
|
if hasArgs {
|
435 |
|
|
s.errorf("%s is not a method but has arguments", fieldName)
|
436 |
|
|
}
|
437 |
|
|
return receiver.MapIndex(nameVal)
|
438 |
|
|
}
|
439 |
|
|
}
|
440 |
|
|
if isNil {
|
441 |
|
|
s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
|
442 |
|
|
}
|
443 |
|
|
s.errorf("can't evaluate field %s in type %s", fieldName, typ)
|
444 |
|
|
panic("not reached")
|
445 |
|
|
}
|
446 |
|
|
|
447 |
|
|
var (
|
448 |
|
|
errorType = reflect.TypeOf((*error)(nil)).Elem()
|
449 |
|
|
fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
|
450 |
|
|
)
|
451 |
|
|
|
452 |
|
|
// evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
|
453 |
|
|
// it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
|
454 |
|
|
// as the function itself.
|
455 |
|
|
func (s *state) evalCall(dot, fun reflect.Value, name string, args []parse.Node, final reflect.Value) reflect.Value {
|
456 |
|
|
if args != nil {
|
457 |
|
|
args = args[1:] // Zeroth arg is function name/node; not passed to function.
|
458 |
|
|
}
|
459 |
|
|
typ := fun.Type()
|
460 |
|
|
numIn := len(args)
|
461 |
|
|
if final.IsValid() {
|
462 |
|
|
numIn++
|
463 |
|
|
}
|
464 |
|
|
numFixed := len(args)
|
465 |
|
|
if typ.IsVariadic() {
|
466 |
|
|
numFixed = typ.NumIn() - 1 // last arg is the variadic one.
|
467 |
|
|
if numIn < numFixed {
|
468 |
|
|
s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
|
469 |
|
|
}
|
470 |
|
|
} else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() {
|
471 |
|
|
s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args))
|
472 |
|
|
}
|
473 |
|
|
if !goodFunc(typ) {
|
474 |
|
|
s.errorf("can't handle multiple results from method/function %q", name)
|
475 |
|
|
}
|
476 |
|
|
// Build the arg list.
|
477 |
|
|
argv := make([]reflect.Value, numIn)
|
478 |
|
|
// Args must be evaluated. Fixed args first.
|
479 |
|
|
i := 0
|
480 |
|
|
for ; i < numFixed; i++ {
|
481 |
|
|
argv[i] = s.evalArg(dot, typ.In(i), args[i])
|
482 |
|
|
}
|
483 |
|
|
// Now the ... args.
|
484 |
|
|
if typ.IsVariadic() {
|
485 |
|
|
argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
|
486 |
|
|
for ; i < len(args); i++ {
|
487 |
|
|
argv[i] = s.evalArg(dot, argType, args[i])
|
488 |
|
|
}
|
489 |
|
|
}
|
490 |
|
|
// Add final value if necessary.
|
491 |
|
|
if final.IsValid() {
|
492 |
|
|
argv[i] = final
|
493 |
|
|
}
|
494 |
|
|
result := fun.Call(argv)
|
495 |
|
|
// If we have an error that is not nil, stop execution and return that error to the caller.
|
496 |
|
|
if len(result) == 2 && !result[1].IsNil() {
|
497 |
|
|
s.errorf("error calling %s: %s", name, result[1].Interface().(error))
|
498 |
|
|
}
|
499 |
|
|
return result[0]
|
500 |
|
|
}
|
501 |
|
|
|
502 |
|
|
// validateType guarantees that the value is valid and assignable to the type.
|
503 |
|
|
func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
|
504 |
|
|
if !value.IsValid() {
|
505 |
|
|
switch typ.Kind() {
|
506 |
|
|
case reflect.Interface, reflect.Ptr, reflect.Chan, reflect.Map, reflect.Slice, reflect.Func:
|
507 |
|
|
// An untyped nil interface{}. Accept as a proper nil value.
|
508 |
|
|
value = reflect.Zero(typ)
|
509 |
|
|
default:
|
510 |
|
|
s.errorf("invalid value; expected %s", typ)
|
511 |
|
|
}
|
512 |
|
|
}
|
513 |
|
|
if !value.Type().AssignableTo(typ) {
|
514 |
|
|
// Does one dereference or indirection work? We could do more, as we
|
515 |
|
|
// do with method receivers, but that gets messy and method receivers
|
516 |
|
|
// are much more constrained, so it makes more sense there than here.
|
517 |
|
|
// Besides, one is almost always all you need.
|
518 |
|
|
switch {
|
519 |
|
|
case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
|
520 |
|
|
value = value.Elem()
|
521 |
|
|
case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
|
522 |
|
|
value = value.Addr()
|
523 |
|
|
default:
|
524 |
|
|
s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
|
525 |
|
|
}
|
526 |
|
|
}
|
527 |
|
|
return value
|
528 |
|
|
}
|
529 |
|
|
|
530 |
|
|
func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
|
531 |
|
|
switch arg := n.(type) {
|
532 |
|
|
case *parse.DotNode:
|
533 |
|
|
return s.validateType(dot, typ)
|
534 |
|
|
case *parse.FieldNode:
|
535 |
|
|
return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, zero), typ)
|
536 |
|
|
case *parse.VariableNode:
|
537 |
|
|
return s.validateType(s.evalVariableNode(dot, arg, nil, zero), typ)
|
538 |
|
|
}
|
539 |
|
|
switch typ.Kind() {
|
540 |
|
|
case reflect.Bool:
|
541 |
|
|
return s.evalBool(typ, n)
|
542 |
|
|
case reflect.Complex64, reflect.Complex128:
|
543 |
|
|
return s.evalComplex(typ, n)
|
544 |
|
|
case reflect.Float32, reflect.Float64:
|
545 |
|
|
return s.evalFloat(typ, n)
|
546 |
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
547 |
|
|
return s.evalInteger(typ, n)
|
548 |
|
|
case reflect.Interface:
|
549 |
|
|
if typ.NumMethod() == 0 {
|
550 |
|
|
return s.evalEmptyInterface(dot, n)
|
551 |
|
|
}
|
552 |
|
|
case reflect.String:
|
553 |
|
|
return s.evalString(typ, n)
|
554 |
|
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
555 |
|
|
return s.evalUnsignedInteger(typ, n)
|
556 |
|
|
}
|
557 |
|
|
s.errorf("can't handle %s for arg of type %s", n, typ)
|
558 |
|
|
panic("not reached")
|
559 |
|
|
}
|
560 |
|
|
|
561 |
|
|
func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
|
562 |
|
|
if n, ok := n.(*parse.BoolNode); ok {
|
563 |
|
|
value := reflect.New(typ).Elem()
|
564 |
|
|
value.SetBool(n.True)
|
565 |
|
|
return value
|
566 |
|
|
}
|
567 |
|
|
s.errorf("expected bool; found %s", n)
|
568 |
|
|
panic("not reached")
|
569 |
|
|
}
|
570 |
|
|
|
571 |
|
|
func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
|
572 |
|
|
if n, ok := n.(*parse.StringNode); ok {
|
573 |
|
|
value := reflect.New(typ).Elem()
|
574 |
|
|
value.SetString(n.Text)
|
575 |
|
|
return value
|
576 |
|
|
}
|
577 |
|
|
s.errorf("expected string; found %s", n)
|
578 |
|
|
panic("not reached")
|
579 |
|
|
}
|
580 |
|
|
|
581 |
|
|
func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
|
582 |
|
|
if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
|
583 |
|
|
value := reflect.New(typ).Elem()
|
584 |
|
|
value.SetInt(n.Int64)
|
585 |
|
|
return value
|
586 |
|
|
}
|
587 |
|
|
s.errorf("expected integer; found %s", n)
|
588 |
|
|
panic("not reached")
|
589 |
|
|
}
|
590 |
|
|
|
591 |
|
|
func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
|
592 |
|
|
if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
|
593 |
|
|
value := reflect.New(typ).Elem()
|
594 |
|
|
value.SetUint(n.Uint64)
|
595 |
|
|
return value
|
596 |
|
|
}
|
597 |
|
|
s.errorf("expected unsigned integer; found %s", n)
|
598 |
|
|
panic("not reached")
|
599 |
|
|
}
|
600 |
|
|
|
601 |
|
|
func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
|
602 |
|
|
if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
|
603 |
|
|
value := reflect.New(typ).Elem()
|
604 |
|
|
value.SetFloat(n.Float64)
|
605 |
|
|
return value
|
606 |
|
|
}
|
607 |
|
|
s.errorf("expected float; found %s", n)
|
608 |
|
|
panic("not reached")
|
609 |
|
|
}
|
610 |
|
|
|
611 |
|
|
func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
|
612 |
|
|
if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
|
613 |
|
|
value := reflect.New(typ).Elem()
|
614 |
|
|
value.SetComplex(n.Complex128)
|
615 |
|
|
return value
|
616 |
|
|
}
|
617 |
|
|
s.errorf("expected complex; found %s", n)
|
618 |
|
|
panic("not reached")
|
619 |
|
|
}
|
620 |
|
|
|
621 |
|
|
func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
|
622 |
|
|
switch n := n.(type) {
|
623 |
|
|
case *parse.BoolNode:
|
624 |
|
|
return reflect.ValueOf(n.True)
|
625 |
|
|
case *parse.DotNode:
|
626 |
|
|
return dot
|
627 |
|
|
case *parse.FieldNode:
|
628 |
|
|
return s.evalFieldNode(dot, n, nil, zero)
|
629 |
|
|
case *parse.IdentifierNode:
|
630 |
|
|
return s.evalFunction(dot, n.Ident, nil, zero)
|
631 |
|
|
case *parse.NumberNode:
|
632 |
|
|
return s.idealConstant(n)
|
633 |
|
|
case *parse.StringNode:
|
634 |
|
|
return reflect.ValueOf(n.Text)
|
635 |
|
|
case *parse.VariableNode:
|
636 |
|
|
return s.evalVariableNode(dot, n, nil, zero)
|
637 |
|
|
}
|
638 |
|
|
s.errorf("can't handle assignment of %s to empty interface argument", n)
|
639 |
|
|
panic("not reached")
|
640 |
|
|
}
|
641 |
|
|
|
642 |
|
|
// indirect returns the item at the end of indirection, and a bool to indicate if it's nil.
|
643 |
|
|
// We indirect through pointers and empty interfaces (only) because
|
644 |
|
|
// non-empty interfaces have methods we might need.
|
645 |
|
|
func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
|
646 |
|
|
for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
|
647 |
|
|
if v.IsNil() {
|
648 |
|
|
return v, true
|
649 |
|
|
}
|
650 |
|
|
if v.Kind() == reflect.Interface && v.NumMethod() > 0 {
|
651 |
|
|
break
|
652 |
|
|
}
|
653 |
|
|
}
|
654 |
|
|
return v, false
|
655 |
|
|
}
|
656 |
|
|
|
657 |
|
|
// printValue writes the textual representation of the value to the output of
|
658 |
|
|
// the template.
|
659 |
|
|
func (s *state) printValue(n parse.Node, v reflect.Value) {
|
660 |
|
|
if v.Kind() == reflect.Ptr {
|
661 |
|
|
v, _ = indirect(v) // fmt.Fprint handles nil.
|
662 |
|
|
}
|
663 |
|
|
if !v.IsValid() {
|
664 |
|
|
fmt.Fprint(s.wr, "")
|
665 |
|
|
return
|
666 |
|
|
}
|
667 |
|
|
|
668 |
|
|
if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
|
669 |
|
|
if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
|
670 |
|
|
v = v.Addr()
|
671 |
|
|
} else {
|
672 |
|
|
switch v.Kind() {
|
673 |
|
|
case reflect.Chan, reflect.Func:
|
674 |
|
|
s.errorf("can't print %s of type %s", n, v.Type())
|
675 |
|
|
}
|
676 |
|
|
}
|
677 |
|
|
}
|
678 |
|
|
fmt.Fprint(s.wr, v.Interface())
|
679 |
|
|
}
|
680 |
|
|
|
681 |
|
|
// Types to help sort the keys in a map for reproducible output.
|
682 |
|
|
|
683 |
|
|
type rvs []reflect.Value
|
684 |
|
|
|
685 |
|
|
func (x rvs) Len() int { return len(x) }
|
686 |
|
|
func (x rvs) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
|
687 |
|
|
|
688 |
|
|
type rvInts struct{ rvs }
|
689 |
|
|
|
690 |
|
|
func (x rvInts) Less(i, j int) bool { return x.rvs[i].Int() < x.rvs[j].Int() }
|
691 |
|
|
|
692 |
|
|
type rvUints struct{ rvs }
|
693 |
|
|
|
694 |
|
|
func (x rvUints) Less(i, j int) bool { return x.rvs[i].Uint() < x.rvs[j].Uint() }
|
695 |
|
|
|
696 |
|
|
type rvFloats struct{ rvs }
|
697 |
|
|
|
698 |
|
|
func (x rvFloats) Less(i, j int) bool { return x.rvs[i].Float() < x.rvs[j].Float() }
|
699 |
|
|
|
700 |
|
|
type rvStrings struct{ rvs }
|
701 |
|
|
|
702 |
|
|
func (x rvStrings) Less(i, j int) bool { return x.rvs[i].String() < x.rvs[j].String() }
|
703 |
|
|
|
704 |
|
|
// sortKeys sorts (if it can) the slice of reflect.Values, which is a slice of map keys.
|
705 |
|
|
func sortKeys(v []reflect.Value) []reflect.Value {
|
706 |
|
|
if len(v) <= 1 {
|
707 |
|
|
return v
|
708 |
|
|
}
|
709 |
|
|
switch v[0].Kind() {
|
710 |
|
|
case reflect.Float32, reflect.Float64:
|
711 |
|
|
sort.Sort(rvFloats{v})
|
712 |
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
713 |
|
|
sort.Sort(rvInts{v})
|
714 |
|
|
case reflect.String:
|
715 |
|
|
sort.Sort(rvStrings{v})
|
716 |
|
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
717 |
|
|
sort.Sort(rvUints{v})
|
718 |
|
|
}
|
719 |
|
|
return v
|
720 |
|
|
}
|