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