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