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