github.com/riscv/riscv-go@v0.0.0-20200123204226-124ebd6fcc8e/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 if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key. 545 s.errorf("nil data; no entry for key %q", fieldName) 546 } 547 return zero 548 } 549 typ := receiver.Type() 550 receiver, isNil := indirect(receiver) 551 // Unless it's an interface, need to get to a value of type *T to guarantee 552 // we see all methods of T and *T. 553 ptr := receiver 554 if ptr.Kind() != reflect.Interface && ptr.CanAddr() { 555 ptr = ptr.Addr() 556 } 557 if method := ptr.MethodByName(fieldName); method.IsValid() { 558 return s.evalCall(dot, method, node, fieldName, args, final) 559 } 560 hasArgs := len(args) > 1 || final.IsValid() 561 // It's not a method; must be a field of a struct or an element of a map. 562 switch receiver.Kind() { 563 case reflect.Struct: 564 tField, ok := receiver.Type().FieldByName(fieldName) 565 if ok { 566 if isNil { 567 s.errorf("nil pointer evaluating %s.%s", typ, fieldName) 568 } 569 field := receiver.FieldByIndex(tField.Index) 570 if tField.PkgPath != "" { // field is unexported 571 s.errorf("%s is an unexported field of struct type %s", fieldName, typ) 572 } 573 // If it's a function, we must call it. 574 if hasArgs { 575 s.errorf("%s has arguments but cannot be invoked as function", fieldName) 576 } 577 return field 578 } 579 case reflect.Map: 580 if isNil { 581 s.errorf("nil pointer evaluating %s.%s", typ, fieldName) 582 } 583 // If it's a map, attempt to use the field name as a key. 584 nameVal := reflect.ValueOf(fieldName) 585 if nameVal.Type().AssignableTo(receiver.Type().Key()) { 586 if hasArgs { 587 s.errorf("%s is not a method but has arguments", fieldName) 588 } 589 result := receiver.MapIndex(nameVal) 590 if !result.IsValid() { 591 switch s.tmpl.option.missingKey { 592 case mapInvalid: 593 // Just use the invalid value. 594 case mapZeroValue: 595 result = reflect.Zero(receiver.Type().Elem()) 596 case mapError: 597 s.errorf("map has no entry for key %q", fieldName) 598 } 599 } 600 return result 601 } 602 } 603 s.errorf("can't evaluate field %s in type %s", fieldName, typ) 604 panic("not reached") 605 } 606 607 var ( 608 errorType = reflect.TypeOf((*error)(nil)).Elem() 609 fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem() 610 reflectValueType = reflect.TypeOf((*reflect.Value)(nil)).Elem() 611 ) 612 613 // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so 614 // it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0] 615 // as the function itself. 616 func (s *state) evalCall(dot, fun reflect.Value, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value { 617 if args != nil { 618 args = args[1:] // Zeroth arg is function name/node; not passed to function. 619 } 620 typ := fun.Type() 621 numIn := len(args) 622 if final.IsValid() { 623 numIn++ 624 } 625 numFixed := len(args) 626 if typ.IsVariadic() { 627 numFixed = typ.NumIn() - 1 // last arg is the variadic one. 628 if numIn < numFixed { 629 s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args)) 630 } 631 } else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() { 632 s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args)) 633 } 634 if !goodFunc(typ) { 635 // TODO: This could still be a confusing error; maybe goodFunc should provide info. 636 s.errorf("can't call method/function %q with %d results", name, typ.NumOut()) 637 } 638 // Build the arg list. 639 argv := make([]reflect.Value, numIn) 640 // Args must be evaluated. Fixed args first. 641 i := 0 642 for ; i < numFixed && i < len(args); i++ { 643 argv[i] = s.evalArg(dot, typ.In(i), args[i]) 644 } 645 // Now the ... args. 646 if typ.IsVariadic() { 647 argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice. 648 for ; i < len(args); i++ { 649 argv[i] = s.evalArg(dot, argType, args[i]) 650 } 651 } 652 // Add final value if necessary. 653 if final.IsValid() { 654 t := typ.In(typ.NumIn() - 1) 655 if typ.IsVariadic() { 656 if numIn-1 < numFixed { 657 // The added final argument corresponds to a fixed parameter of the function. 658 // Validate against the type of the actual parameter. 659 t = typ.In(numIn - 1) 660 } else { 661 // The added final argument corresponds to the variadic part. 662 // Validate against the type of the elements of the variadic slice. 663 t = t.Elem() 664 } 665 } 666 argv[i] = s.validateType(final, t) 667 } 668 result := fun.Call(argv) 669 // If we have an error that is not nil, stop execution and return that error to the caller. 670 if len(result) == 2 && !result[1].IsNil() { 671 s.at(node) 672 s.errorf("error calling %s: %s", name, result[1].Interface().(error)) 673 } 674 v := result[0] 675 if v.Type() == reflectValueType { 676 v = v.Interface().(reflect.Value) 677 } 678 return v 679 } 680 681 // canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero. 682 func canBeNil(typ reflect.Type) bool { 683 switch typ.Kind() { 684 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: 685 return true 686 case reflect.Struct: 687 return typ == reflectValueType 688 } 689 return false 690 } 691 692 // validateType guarantees that the value is valid and assignable to the type. 693 func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value { 694 if !value.IsValid() { 695 if typ == nil || canBeNil(typ) { 696 // An untyped nil interface{}. Accept as a proper nil value. 697 return reflect.Zero(typ) 698 } 699 s.errorf("invalid value; expected %s", typ) 700 } 701 if typ == reflectValueType && value.Type() != typ { 702 return reflect.ValueOf(value) 703 } 704 if typ != nil && !value.Type().AssignableTo(typ) { 705 if value.Kind() == reflect.Interface && !value.IsNil() { 706 value = value.Elem() 707 if value.Type().AssignableTo(typ) { 708 return value 709 } 710 // fallthrough 711 } 712 // Does one dereference or indirection work? We could do more, as we 713 // do with method receivers, but that gets messy and method receivers 714 // are much more constrained, so it makes more sense there than here. 715 // Besides, one is almost always all you need. 716 switch { 717 case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ): 718 value = value.Elem() 719 if !value.IsValid() { 720 s.errorf("dereference of nil pointer of type %s", typ) 721 } 722 case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr(): 723 value = value.Addr() 724 default: 725 s.errorf("wrong type for value; expected %s; got %s", typ, value.Type()) 726 } 727 } 728 return value 729 } 730 731 func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value { 732 s.at(n) 733 switch arg := n.(type) { 734 case *parse.DotNode: 735 return s.validateType(dot, typ) 736 case *parse.NilNode: 737 if canBeNil(typ) { 738 return reflect.Zero(typ) 739 } 740 s.errorf("cannot assign nil to %s", typ) 741 case *parse.FieldNode: 742 return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, zero), typ) 743 case *parse.VariableNode: 744 return s.validateType(s.evalVariableNode(dot, arg, nil, zero), typ) 745 case *parse.PipeNode: 746 return s.validateType(s.evalPipeline(dot, arg), typ) 747 case *parse.IdentifierNode: 748 return s.validateType(s.evalFunction(dot, arg, arg, nil, zero), typ) 749 case *parse.ChainNode: 750 return s.validateType(s.evalChainNode(dot, arg, nil, zero), typ) 751 } 752 switch typ.Kind() { 753 case reflect.Bool: 754 return s.evalBool(typ, n) 755 case reflect.Complex64, reflect.Complex128: 756 return s.evalComplex(typ, n) 757 case reflect.Float32, reflect.Float64: 758 return s.evalFloat(typ, n) 759 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 760 return s.evalInteger(typ, n) 761 case reflect.Interface: 762 if typ.NumMethod() == 0 { 763 return s.evalEmptyInterface(dot, n) 764 } 765 case reflect.Struct: 766 if typ == reflectValueType { 767 return reflect.ValueOf(s.evalEmptyInterface(dot, n)) 768 } 769 case reflect.String: 770 return s.evalString(typ, n) 771 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 772 return s.evalUnsignedInteger(typ, n) 773 } 774 s.errorf("can't handle %s for arg of type %s", n, typ) 775 panic("not reached") 776 } 777 778 func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value { 779 s.at(n) 780 if n, ok := n.(*parse.BoolNode); ok { 781 value := reflect.New(typ).Elem() 782 value.SetBool(n.True) 783 return value 784 } 785 s.errorf("expected bool; found %s", n) 786 panic("not reached") 787 } 788 789 func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value { 790 s.at(n) 791 if n, ok := n.(*parse.StringNode); ok { 792 value := reflect.New(typ).Elem() 793 value.SetString(n.Text) 794 return value 795 } 796 s.errorf("expected string; found %s", n) 797 panic("not reached") 798 } 799 800 func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value { 801 s.at(n) 802 if n, ok := n.(*parse.NumberNode); ok && n.IsInt { 803 value := reflect.New(typ).Elem() 804 value.SetInt(n.Int64) 805 return value 806 } 807 s.errorf("expected integer; found %s", n) 808 panic("not reached") 809 } 810 811 func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value { 812 s.at(n) 813 if n, ok := n.(*parse.NumberNode); ok && n.IsUint { 814 value := reflect.New(typ).Elem() 815 value.SetUint(n.Uint64) 816 return value 817 } 818 s.errorf("expected unsigned integer; found %s", n) 819 panic("not reached") 820 } 821 822 func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value { 823 s.at(n) 824 if n, ok := n.(*parse.NumberNode); ok && n.IsFloat { 825 value := reflect.New(typ).Elem() 826 value.SetFloat(n.Float64) 827 return value 828 } 829 s.errorf("expected float; found %s", n) 830 panic("not reached") 831 } 832 833 func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value { 834 if n, ok := n.(*parse.NumberNode); ok && n.IsComplex { 835 value := reflect.New(typ).Elem() 836 value.SetComplex(n.Complex128) 837 return value 838 } 839 s.errorf("expected complex; found %s", n) 840 panic("not reached") 841 } 842 843 func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value { 844 s.at(n) 845 switch n := n.(type) { 846 case *parse.BoolNode: 847 return reflect.ValueOf(n.True) 848 case *parse.DotNode: 849 return dot 850 case *parse.FieldNode: 851 return s.evalFieldNode(dot, n, nil, zero) 852 case *parse.IdentifierNode: 853 return s.evalFunction(dot, n, n, nil, zero) 854 case *parse.NilNode: 855 // NilNode is handled in evalArg, the only place that calls here. 856 s.errorf("evalEmptyInterface: nil (can't happen)") 857 case *parse.NumberNode: 858 return s.idealConstant(n) 859 case *parse.StringNode: 860 return reflect.ValueOf(n.Text) 861 case *parse.VariableNode: 862 return s.evalVariableNode(dot, n, nil, zero) 863 case *parse.PipeNode: 864 return s.evalPipeline(dot, n) 865 } 866 s.errorf("can't handle assignment of %s to empty interface argument", n) 867 panic("not reached") 868 } 869 870 // indirect returns the item at the end of indirection, and a bool to indicate if it's nil. 871 func indirect(v reflect.Value) (rv reflect.Value, isNil bool) { 872 for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() { 873 if v.IsNil() { 874 return v, true 875 } 876 } 877 return v, false 878 } 879 880 // indirectInterface returns the concrete value in an interface value, 881 // or else the zero reflect.Value. 882 // That is, if v represents the interface value x, the result is the same as reflect.ValueOf(x): 883 // the fact that x was an interface value is forgotten. 884 func indirectInterface(v reflect.Value) reflect.Value { 885 if v.Kind() != reflect.Interface { 886 return v 887 } 888 if v.IsNil() { 889 return reflect.Value{} 890 } 891 return v.Elem() 892 } 893 894 // printValue writes the textual representation of the value to the output of 895 // the template. 896 func (s *state) printValue(n parse.Node, v reflect.Value) { 897 s.at(n) 898 iface, ok := printableValue(v) 899 if !ok { 900 s.errorf("can't print %s of type %s", n, v.Type()) 901 } 902 _, err := fmt.Fprint(s.wr, iface) 903 if err != nil { 904 s.writeError(err) 905 } 906 } 907 908 // printableValue returns the, possibly indirected, interface value inside v that 909 // is best for a call to formatted printer. 910 func printableValue(v reflect.Value) (interface{}, bool) { 911 if v.Kind() == reflect.Ptr { 912 v, _ = indirect(v) // fmt.Fprint handles nil. 913 } 914 if !v.IsValid() { 915 return "<no value>", true 916 } 917 918 if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) { 919 if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) { 920 v = v.Addr() 921 } else { 922 switch v.Kind() { 923 case reflect.Chan, reflect.Func: 924 return nil, false 925 } 926 } 927 } 928 return v.Interface(), true 929 } 930 931 // Types to help sort the keys in a map for reproducible output. 932 933 type rvs []reflect.Value 934 935 func (x rvs) Len() int { return len(x) } 936 func (x rvs) Swap(i, j int) { x[i], x[j] = x[j], x[i] } 937 938 type rvInts struct{ rvs } 939 940 func (x rvInts) Less(i, j int) bool { return x.rvs[i].Int() < x.rvs[j].Int() } 941 942 type rvUints struct{ rvs } 943 944 func (x rvUints) Less(i, j int) bool { return x.rvs[i].Uint() < x.rvs[j].Uint() } 945 946 type rvFloats struct{ rvs } 947 948 func (x rvFloats) Less(i, j int) bool { return x.rvs[i].Float() < x.rvs[j].Float() } 949 950 type rvStrings struct{ rvs } 951 952 func (x rvStrings) Less(i, j int) bool { return x.rvs[i].String() < x.rvs[j].String() } 953 954 // sortKeys sorts (if it can) the slice of reflect.Values, which is a slice of map keys. 955 func sortKeys(v []reflect.Value) []reflect.Value { 956 if len(v) <= 1 { 957 return v 958 } 959 switch v[0].Kind() { 960 case reflect.Float32, reflect.Float64: 961 sort.Sort(rvFloats{v}) 962 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 963 sort.Sort(rvInts{v}) 964 case reflect.String: 965 sort.Sort(rvStrings{v}) 966 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 967 sort.Sort(rvUints{v}) 968 } 969 return v 970 }