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 5package template 6 7import ( 8 "bytes" 9 "fmt" 10 "internal/fmtsort" 11 "io" 12 "reflect" 13 "runtime" 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. 22var maxExecDepth = initMaxExecDepth() 23 24func initMaxExecDepth() int { 25 // For gccgo we make this 1000 rather than 100000 to avoid 26 // stack overflow on non-split-stack systems. 27 if runtime.GOARCH == "wasm" || runtime.Compiler == "gccgo" { 28 return 1000 29 } 30 return 100000 31} 32 33// state represents the state of an execution. It's not part of the 34// template so that multiple executions of the same template 35// can execute in parallel. 36type state struct { 37 tmpl *Template 38 wr io.Writer 39 node parse.Node // current node, for errors 40 vars []variable // push-down stack of variable values. 41 depth int // the height of the stack of executing templates. 42} 43 44// variable holds the dynamic value of a variable such as $, $x etc. 45type variable struct { 46 name string 47 value reflect.Value 48} 49 50// push pushes a new variable on the stack. 51func (s *state) push(name string, value reflect.Value) { 52 s.vars = append(s.vars, variable{name, value}) 53} 54 55// mark returns the length of the variable stack. 56func (s *state) mark() int { 57 return len(s.vars) 58} 59 60// pop pops the variable stack up to the mark. 61func (s *state) pop(mark int) { 62 s.vars = s.vars[0:mark] 63} 64 65// setVar overwrites the last declared variable with the given name. 66// Used by variable assignments. 67func (s *state) setVar(name string, value reflect.Value) { 68 for i := s.mark() - 1; i >= 0; i-- { 69 if s.vars[i].name == name { 70 s.vars[i].value = value 71 return 72 } 73 } 74 s.errorf("undefined variable: %s", name) 75} 76 77// setTopVar overwrites the top-nth variable on the stack. Used by range iterations. 78func (s *state) setTopVar(n int, value reflect.Value) { 79 s.vars[len(s.vars)-n].value = value 80} 81 82// varValue returns the value of the named variable. 83func (s *state) varValue(name string) reflect.Value { 84 for i := s.mark() - 1; i >= 0; i-- { 85 if s.vars[i].name == name { 86 return s.vars[i].value 87 } 88 } 89 s.errorf("undefined variable: %s", name) 90 return zero 91} 92 93var zero reflect.Value 94 95type missingValType struct{} 96 97var missingVal = reflect.ValueOf(missingValType{}) 98 99// at marks the state to be on node n, for error reporting. 100func (s *state) at(node parse.Node) { 101 s.node = node 102} 103 104// doublePercent returns the string with %'s replaced by %%, if necessary, 105// so it can be used safely inside a Printf format string. 106func doublePercent(str string) string { 107 return strings.ReplaceAll(str, "%", "%%") 108} 109 110// TODO: It would be nice if ExecError was more broken down, but 111// the way ErrorContext embeds the template name makes the 112// processing too clumsy. 113 114// ExecError is the custom error type returned when Execute has an 115// error evaluating its template. (If a write error occurs, the actual 116// error is returned; it will not be of type ExecError.) 117type ExecError struct { 118 Name string // Name of template. 119 Err error // Pre-formatted error. 120} 121 122func (e ExecError) Error() string { 123 return e.Err.Error() 124} 125 126// errorf records an ExecError and terminates processing. 127func (s *state) errorf(format string, args ...interface{}) { 128 name := doublePercent(s.tmpl.Name()) 129 if s.node == nil { 130 format = fmt.Sprintf("template: %s: %s", name, format) 131 } else { 132 location, context := s.tmpl.ErrorContext(s.node) 133 format = fmt.Sprintf("template: %s: executing %q at <%s>: %s", location, name, doublePercent(context), format) 134 } 135 panic(ExecError{ 136 Name: s.tmpl.Name(), 137 Err: fmt.Errorf(format, args...), 138 }) 139} 140 141// writeError is the wrapper type used internally when Execute has an 142// error writing to its output. We strip the wrapper in errRecover. 143// Note that this is not an implementation of error, so it cannot escape 144// from the package as an error value. 145type writeError struct { 146 Err error // Original error. 147} 148 149func (s *state) writeError(err error) { 150 panic(writeError{ 151 Err: err, 152 }) 153} 154 155// errRecover is the handler that turns panics into returns from the top 156// level of Parse. 157func errRecover(errp *error) { 158 e := recover() 159 if e != nil { 160 switch err := e.(type) { 161 case runtime.Error: 162 panic(e) 163 case writeError: 164 *errp = err.Err // Strip the wrapper. 165 case ExecError: 166 *errp = err // Keep the wrapper. 167 default: 168 panic(e) 169 } 170 } 171} 172 173// ExecuteTemplate applies the template associated with t that has the given name 174// to the specified data object and writes the output to wr. 175// If an error occurs executing the template or writing its output, 176// execution stops, but partial results may already have been written to 177// the output writer. 178// A template may be executed safely in parallel, although if parallel 179// executions share a Writer the output may be interleaved. 180func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error { 181 var tmpl *Template 182 if t.common != nil { 183 tmpl = t.tmpl[name] 184 } 185 if tmpl == nil { 186 return fmt.Errorf("template: no template %q associated with template %q", name, t.name) 187 } 188 return tmpl.Execute(wr, data) 189} 190 191// Execute applies a parsed template to the specified data object, 192// and writes the output to wr. 193// If an error occurs executing the template or writing its output, 194// execution stops, but partial results may already have been written to 195// the output writer. 196// A template may be executed safely in parallel, although if parallel 197// executions share a Writer the output may be interleaved. 198// 199// If data is a reflect.Value, the template applies to the concrete 200// value that the reflect.Value holds, as in fmt.Print. 201func (t *Template) Execute(wr io.Writer, data interface{}) error { 202 return t.execute(wr, data) 203} 204 205func (t *Template) execute(wr io.Writer, data interface{}) (err error) { 206 defer errRecover(&err) 207 value, ok := data.(reflect.Value) 208 if !ok { 209 value = reflect.ValueOf(data) 210 } 211 state := &state{ 212 tmpl: t, 213 wr: wr, 214 vars: []variable{{"$", value}}, 215 } 216 if t.Tree == nil || t.Root == nil { 217 state.errorf("%q is an incomplete or empty template", t.Name()) 218 } 219 state.walk(value, t.Root) 220 return 221} 222 223// DefinedTemplates returns a string listing the defined templates, 224// prefixed by the string "; defined templates are: ". If there are none, 225// it returns the empty string. For generating an error message here 226// and in html/template. 227func (t *Template) DefinedTemplates() string { 228 if t.common == nil { 229 return "" 230 } 231 var b bytes.Buffer 232 for name, tmpl := range t.tmpl { 233 if tmpl.Tree == nil || tmpl.Root == nil { 234 continue 235 } 236 if b.Len() > 0 { 237 b.WriteString(", ") 238 } 239 fmt.Fprintf(&b, "%q", name) 240 } 241 var s string 242 if b.Len() > 0 { 243 s = "; defined templates are: " + b.String() 244 } 245 return s 246} 247 248// Walk functions step through the major pieces of the template structure, 249// generating output as they go. 250func (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. 283func (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(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. 304func IsTrue(val interface{}) (truth, ok bool) { 305 return isTrue(reflect.ValueOf(val)) 306} 307 308func 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 336func (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 398func (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. 425func (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 448func (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 454func (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 is ignored. 466 return s.evalPipeline(dot, n) 467 case *parse.VariableNode: 468 return s.evalVariableNode(dot, n, cmd.Args, final) 469 } 470 s.at(firstWord) 471 s.notAFunction(cmd.Args, final) 472 switch word := firstWord.(type) { 473 case *parse.BoolNode: 474 return reflect.ValueOf(word.True) 475 case *parse.DotNode: 476 return dot 477 case *parse.NilNode: 478 s.errorf("nil is not a command") 479 case *parse.NumberNode: 480 return s.idealConstant(word) 481 case *parse.StringNode: 482 return reflect.ValueOf(word.Text) 483 } 484 s.errorf("can't evaluate command %q", firstWord) 485 panic("not reached") 486} 487 488// idealConstant is called to return the value of a number in a context where 489// we don't know the type. In that case, the syntax of the number tells us 490// its type, and we use Go rules to resolve. Note there is no such thing as 491// a uint ideal constant in this situation - the value must be of int type. 492func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value { 493 // These are ideal constants but we don't know the type 494 // and we have no context. (If it was a method argument, 495 // we'd know what we need.) The syntax guides us to some extent. 496 s.at(constant) 497 switch { 498 case constant.IsComplex: 499 return reflect.ValueOf(constant.Complex128) // incontrovertible. 500 case constant.IsFloat && !isHexConstant(constant.Text) && strings.ContainsAny(constant.Text, ".eE"): 501 return reflect.ValueOf(constant.Float64) 502 case constant.IsInt: 503 n := int(constant.Int64) 504 if int64(n) != constant.Int64 { 505 s.errorf("%s overflows int", constant.Text) 506 } 507 return reflect.ValueOf(n) 508 case constant.IsUint: 509 s.errorf("%s overflows int", constant.Text) 510 } 511 return zero 512} 513 514func isHexConstant(s string) bool { 515 return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') 516} 517 518func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value { 519 s.at(field) 520 return s.evalFieldChain(dot, dot, field, field.Ident, args, final) 521} 522 523func (s *state) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value { 524 s.at(chain) 525 if len(chain.Field) == 0 { 526 s.errorf("internal error: no fields in evalChainNode") 527 } 528 if chain.Node.Type() == parse.NodeNil { 529 s.errorf("indirection through explicit nil in %s", chain) 530 } 531 // (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields. 532 pipe := s.evalArg(dot, nil, chain.Node) 533 return s.evalFieldChain(dot, pipe, chain, chain.Field, args, final) 534} 535 536func (s *state) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value { 537 // $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields. 538 s.at(variable) 539 value := s.varValue(variable.Ident[0]) 540 if len(variable.Ident) == 1 { 541 s.notAFunction(args, final) 542 return value 543 } 544 return s.evalFieldChain(dot, value, variable, variable.Ident[1:], args, final) 545} 546 547// evalFieldChain evaluates .X.Y.Z possibly followed by arguments. 548// dot is the environment in which to evaluate arguments, while 549// receiver is the value being walked along the chain. 550func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ident []string, args []parse.Node, final reflect.Value) reflect.Value { 551 n := len(ident) 552 for i := 0; i < n-1; i++ { 553 receiver = s.evalField(dot, ident[i], node, nil, missingVal, receiver) 554 } 555 // Now if it's a method, it gets the arguments. 556 return s.evalField(dot, ident[n-1], node, args, final, receiver) 557} 558 559func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value { 560 s.at(node) 561 name := node.Ident 562 function, ok := findFunction(name, s.tmpl) 563 if !ok { 564 s.errorf("%q is not a defined function", name) 565 } 566 return s.evalCall(dot, function, cmd, name, args, final) 567} 568 569// evalField evaluates an expression like (.Field) or (.Field arg1 arg2). 570// The 'final' argument represents the return value from the preceding 571// value of the pipeline, if any. 572func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value { 573 if !receiver.IsValid() { 574 if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key. 575 s.errorf("nil data; no entry for key %q", fieldName) 576 } 577 return zero 578 } 579 typ := receiver.Type() 580 receiver, isNil := indirect(receiver) 581 if receiver.Kind() == reflect.Interface && isNil { 582 // Calling a method on a nil interface can't work. The 583 // MethodByName method call below would panic. 584 s.errorf("nil pointer evaluating %s.%s", typ, fieldName) 585 return zero 586 } 587 588 // Unless it's an interface, need to get to a value of type *T to guarantee 589 // we see all methods of T and *T. 590 ptr := receiver 591 if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Ptr && ptr.CanAddr() { 592 ptr = ptr.Addr() 593 } 594 if method := ptr.MethodByName(fieldName); method.IsValid() { 595 return s.evalCall(dot, method, node, fieldName, args, final) 596 } 597 hasArgs := len(args) > 1 || final != missingVal 598 // It's not a method; must be a field of a struct or an element of a map. 599 switch receiver.Kind() { 600 case reflect.Struct: 601 tField, ok := receiver.Type().FieldByName(fieldName) 602 if ok { 603 if isNil { 604 s.errorf("nil pointer evaluating %s.%s", typ, fieldName) 605 } 606 field := receiver.FieldByIndex(tField.Index) 607 if tField.PkgPath != "" { // field is unexported 608 s.errorf("%s is an unexported field of struct type %s", fieldName, typ) 609 } 610 // If it's a function, we must call it. 611 if hasArgs { 612 s.errorf("%s has arguments but cannot be invoked as function", fieldName) 613 } 614 return field 615 } 616 case reflect.Map: 617 if isNil { 618 s.errorf("nil pointer evaluating %s.%s", typ, fieldName) 619 } 620 // If it's a map, attempt to use the field name as a key. 621 nameVal := reflect.ValueOf(fieldName) 622 if nameVal.Type().AssignableTo(receiver.Type().Key()) { 623 if hasArgs { 624 s.errorf("%s is not a method but has arguments", fieldName) 625 } 626 result := receiver.MapIndex(nameVal) 627 if !result.IsValid() { 628 switch s.tmpl.option.missingKey { 629 case mapInvalid: 630 // Just use the invalid value. 631 case mapZeroValue: 632 result = reflect.Zero(receiver.Type().Elem()) 633 case mapError: 634 s.errorf("map has no entry for key %q", fieldName) 635 } 636 } 637 return result 638 } 639 } 640 s.errorf("can't evaluate field %s in type %s", fieldName, typ) 641 panic("not reached") 642} 643 644var ( 645 errorType = reflect.TypeOf((*error)(nil)).Elem() 646 fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem() 647 reflectValueType = reflect.TypeOf((*reflect.Value)(nil)).Elem() 648) 649 650// evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so 651// it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0] 652// as the function itself. 653func (s *state) evalCall(dot, fun reflect.Value, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value { 654 if args != nil { 655 args = args[1:] // Zeroth arg is function name/node; not passed to function. 656 } 657 typ := fun.Type() 658 numIn := len(args) 659 if final != missingVal { 660 numIn++ 661 } 662 numFixed := len(args) 663 if typ.IsVariadic() { 664 numFixed = typ.NumIn() - 1 // last arg is the variadic one. 665 if numIn < numFixed { 666 s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args)) 667 } 668 } else if numIn != typ.NumIn() { 669 s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), numIn) 670 } 671 if !goodFunc(typ) { 672 // TODO: This could still be a confusing error; maybe goodFunc should provide info. 673 s.errorf("can't call method/function %q with %d results", name, typ.NumOut()) 674 } 675 // Build the arg list. 676 argv := make([]reflect.Value, numIn) 677 // Args must be evaluated. Fixed args first. 678 i := 0 679 for ; i < numFixed && i < len(args); i++ { 680 argv[i] = s.evalArg(dot, typ.In(i), args[i]) 681 } 682 // Now the ... args. 683 if typ.IsVariadic() { 684 argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice. 685 for ; i < len(args); i++ { 686 argv[i] = s.evalArg(dot, argType, args[i]) 687 } 688 } 689 // Add final value if necessary. 690 if final != missingVal { 691 t := typ.In(typ.NumIn() - 1) 692 if typ.IsVariadic() { 693 if numIn-1 < numFixed { 694 // The added final argument corresponds to a fixed parameter of the function. 695 // Validate against the type of the actual parameter. 696 t = typ.In(numIn - 1) 697 } else { 698 // The added final argument corresponds to the variadic part. 699 // Validate against the type of the elements of the variadic slice. 700 t = t.Elem() 701 } 702 } 703 argv[i] = s.validateType(final, t) 704 } 705 v, err := safeCall(fun, argv) 706 // If we have an error that is not nil, stop execution and return that 707 // error to the caller. 708 if err != nil { 709 s.at(node) 710 s.errorf("error calling %s: %v", name, err) 711 } 712 if v.Type() == reflectValueType { 713 v = v.Interface().(reflect.Value) 714 } 715 return v 716} 717 718// canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero. 719func canBeNil(typ reflect.Type) bool { 720 switch typ.Kind() { 721 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: 722 return true 723 case reflect.Struct: 724 return typ == reflectValueType 725 } 726 return false 727} 728 729// validateType guarantees that the value is valid and assignable to the type. 730func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value { 731 if !value.IsValid() { 732 if typ == nil { 733 // An untyped nil interface{}. Accept as a proper nil value. 734 return reflect.ValueOf(nil) 735 } 736 if canBeNil(typ) { 737 // Like above, but use the zero value of the non-nil type. 738 return reflect.Zero(typ) 739 } 740 s.errorf("invalid value; expected %s", typ) 741 } 742 if typ == reflectValueType && value.Type() != typ { 743 return reflect.ValueOf(value) 744 } 745 if typ != nil && !value.Type().AssignableTo(typ) { 746 if value.Kind() == reflect.Interface && !value.IsNil() { 747 value = value.Elem() 748 if value.Type().AssignableTo(typ) { 749 return value 750 } 751 // fallthrough 752 } 753 // Does one dereference or indirection work? We could do more, as we 754 // do with method receivers, but that gets messy and method receivers 755 // are much more constrained, so it makes more sense there than here. 756 // Besides, one is almost always all you need. 757 switch { 758 case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ): 759 value = value.Elem() 760 if !value.IsValid() { 761 s.errorf("dereference of nil pointer of type %s", typ) 762 } 763 case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr(): 764 value = value.Addr() 765 default: 766 s.errorf("wrong type for value; expected %s; got %s", typ, value.Type()) 767 } 768 } 769 return value 770} 771 772func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value { 773 s.at(n) 774 switch arg := n.(type) { 775 case *parse.DotNode: 776 return s.validateType(dot, typ) 777 case *parse.NilNode: 778 if canBeNil(typ) { 779 return reflect.Zero(typ) 780 } 781 s.errorf("cannot assign nil to %s", typ) 782 case *parse.FieldNode: 783 return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, missingVal), typ) 784 case *parse.VariableNode: 785 return s.validateType(s.evalVariableNode(dot, arg, nil, missingVal), typ) 786 case *parse.PipeNode: 787 return s.validateType(s.evalPipeline(dot, arg), typ) 788 case *parse.IdentifierNode: 789 return s.validateType(s.evalFunction(dot, arg, arg, nil, missingVal), typ) 790 case *parse.ChainNode: 791 return s.validateType(s.evalChainNode(dot, arg, nil, missingVal), typ) 792 } 793 switch typ.Kind() { 794 case reflect.Bool: 795 return s.evalBool(typ, n) 796 case reflect.Complex64, reflect.Complex128: 797 return s.evalComplex(typ, n) 798 case reflect.Float32, reflect.Float64: 799 return s.evalFloat(typ, n) 800 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 801 return s.evalInteger(typ, n) 802 case reflect.Interface: 803 if typ.NumMethod() == 0 { 804 return s.evalEmptyInterface(dot, n) 805 } 806 case reflect.Struct: 807 if typ == reflectValueType { 808 return reflect.ValueOf(s.evalEmptyInterface(dot, n)) 809 } 810 case reflect.String: 811 return s.evalString(typ, n) 812 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 813 return s.evalUnsignedInteger(typ, n) 814 } 815 s.errorf("can't handle %s for arg of type %s", n, typ) 816 panic("not reached") 817} 818 819func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value { 820 s.at(n) 821 if n, ok := n.(*parse.BoolNode); ok { 822 value := reflect.New(typ).Elem() 823 value.SetBool(n.True) 824 return value 825 } 826 s.errorf("expected bool; found %s", n) 827 panic("not reached") 828} 829 830func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value { 831 s.at(n) 832 if n, ok := n.(*parse.StringNode); ok { 833 value := reflect.New(typ).Elem() 834 value.SetString(n.Text) 835 return value 836 } 837 s.errorf("expected string; found %s", n) 838 panic("not reached") 839} 840 841func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value { 842 s.at(n) 843 if n, ok := n.(*parse.NumberNode); ok && n.IsInt { 844 value := reflect.New(typ).Elem() 845 value.SetInt(n.Int64) 846 return value 847 } 848 s.errorf("expected integer; found %s", n) 849 panic("not reached") 850} 851 852func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value { 853 s.at(n) 854 if n, ok := n.(*parse.NumberNode); ok && n.IsUint { 855 value := reflect.New(typ).Elem() 856 value.SetUint(n.Uint64) 857 return value 858 } 859 s.errorf("expected unsigned integer; found %s", n) 860 panic("not reached") 861} 862 863func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value { 864 s.at(n) 865 if n, ok := n.(*parse.NumberNode); ok && n.IsFloat { 866 value := reflect.New(typ).Elem() 867 value.SetFloat(n.Float64) 868 return value 869 } 870 s.errorf("expected float; found %s", n) 871 panic("not reached") 872} 873 874func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value { 875 if n, ok := n.(*parse.NumberNode); ok && n.IsComplex { 876 value := reflect.New(typ).Elem() 877 value.SetComplex(n.Complex128) 878 return value 879 } 880 s.errorf("expected complex; found %s", n) 881 panic("not reached") 882} 883 884func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value { 885 s.at(n) 886 switch n := n.(type) { 887 case *parse.BoolNode: 888 return reflect.ValueOf(n.True) 889 case *parse.DotNode: 890 return dot 891 case *parse.FieldNode: 892 return s.evalFieldNode(dot, n, nil, missingVal) 893 case *parse.IdentifierNode: 894 return s.evalFunction(dot, n, n, nil, missingVal) 895 case *parse.NilNode: 896 // NilNode is handled in evalArg, the only place that calls here. 897 s.errorf("evalEmptyInterface: nil (can't happen)") 898 case *parse.NumberNode: 899 return s.idealConstant(n) 900 case *parse.StringNode: 901 return reflect.ValueOf(n.Text) 902 case *parse.VariableNode: 903 return s.evalVariableNode(dot, n, nil, missingVal) 904 case *parse.PipeNode: 905 return s.evalPipeline(dot, n) 906 } 907 s.errorf("can't handle assignment of %s to empty interface argument", n) 908 panic("not reached") 909} 910 911// indirect returns the item at the end of indirection, and a bool to indicate if it's nil. 912func indirect(v reflect.Value) (rv reflect.Value, isNil bool) { 913 for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() { 914 if v.IsNil() { 915 return v, true 916 } 917 } 918 return v, false 919} 920 921// indirectInterface returns the concrete value in an interface value, 922// or else the zero reflect.Value. 923// That is, if v represents the interface value x, the result is the same as reflect.ValueOf(x): 924// the fact that x was an interface value is forgotten. 925func indirectInterface(v reflect.Value) reflect.Value { 926 if v.Kind() != reflect.Interface { 927 return v 928 } 929 if v.IsNil() { 930 return reflect.Value{} 931 } 932 return v.Elem() 933} 934 935// printValue writes the textual representation of the value to the output of 936// the template. 937func (s *state) printValue(n parse.Node, v reflect.Value) { 938 s.at(n) 939 iface, ok := printableValue(v) 940 if !ok { 941 s.errorf("can't print %s of type %s", n, v.Type()) 942 } 943 _, err := fmt.Fprint(s.wr, iface) 944 if err != nil { 945 s.writeError(err) 946 } 947} 948 949// printableValue returns the, possibly indirected, interface value inside v that 950// is best for a call to formatted printer. 951func printableValue(v reflect.Value) (interface{}, bool) { 952 if v.Kind() == reflect.Ptr { 953 v, _ = indirect(v) // fmt.Fprint handles nil. 954 } 955 if !v.IsValid() { 956 return "<no value>", true 957 } 958 959 if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) { 960 if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) { 961 v = v.Addr() 962 } else { 963 switch v.Kind() { 964 case reflect.Chan, reflect.Func: 965 return nil, false 966 } 967 } 968 } 969 return v.Interface(), true 970} 971