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