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