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