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