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