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