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