PageRenderTime 57ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/src/pkg/text/template/exec.go

https://bitbucket.org/nightsnaker/go
Go | 800 lines | 649 code | 59 blank | 92 comment | 164 complexity | 8969e9020270870875d444535fabe053 MD5 | raw file
Possible License(s): BSD-3-Clause
  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. package template
  5. import (
  6. "fmt"
  7. "io"
  8. "reflect"
  9. "runtime"
  10. "sort"
  11. "strings"
  12. "text/template/parse"
  13. )
  14. // state represents the state of an execution. It's not part of the
  15. // template so that multiple executions of the same template
  16. // can execute in parallel.
  17. type state struct {
  18. tmpl *Template
  19. wr io.Writer
  20. node parse.Node // current node, for errors
  21. vars []variable // push-down stack of variable values.
  22. }
  23. // variable holds the dynamic value of a variable such as $, $x etc.
  24. type variable struct {
  25. name string
  26. value reflect.Value
  27. }
  28. // push pushes a new variable on the stack.
  29. func (s *state) push(name string, value reflect.Value) {
  30. s.vars = append(s.vars, variable{name, value})
  31. }
  32. // mark returns the length of the variable stack.
  33. func (s *state) mark() int {
  34. return len(s.vars)
  35. }
  36. // pop pops the variable stack up to the mark.
  37. func (s *state) pop(mark int) {
  38. s.vars = s.vars[0:mark]
  39. }
  40. // setVar overwrites the top-nth variable on the stack. Used by range iterations.
  41. func (s *state) setVar(n int, value reflect.Value) {
  42. s.vars[len(s.vars)-n].value = value
  43. }
  44. // varValue returns the value of the named variable.
  45. func (s *state) varValue(name string) reflect.Value {
  46. for i := s.mark() - 1; i >= 0; i-- {
  47. if s.vars[i].name == name {
  48. return s.vars[i].value
  49. }
  50. }
  51. s.errorf("undefined variable: %s", name)
  52. return zero
  53. }
  54. var zero reflect.Value
  55. // at marks the state to be on node n, for error reporting.
  56. func (s *state) at(node parse.Node) {
  57. s.node = node
  58. }
  59. // doublePercent returns the string with %'s replaced by %%, if necessary,
  60. // so it can be used safely inside a Printf format string.
  61. func doublePercent(str string) string {
  62. if strings.Contains(str, "%") {
  63. str = strings.Replace(str, "%", "%%", -1)
  64. }
  65. return str
  66. }
  67. // errorf formats the error and terminates processing.
  68. func (s *state) errorf(format string, args ...interface{}) {
  69. name := doublePercent(s.tmpl.Name())
  70. if s.node == nil {
  71. format = fmt.Sprintf("template: %s: %s", name, format)
  72. } else {
  73. location, context := s.tmpl.ErrorContext(s.node)
  74. format = fmt.Sprintf("template: %s: executing %q at <%s>: %s", location, name, doublePercent(context), format)
  75. }
  76. panic(fmt.Errorf(format, args...))
  77. }
  78. // errRecover is the handler that turns panics into returns from the top
  79. // level of Parse.
  80. func errRecover(errp *error) {
  81. e := recover()
  82. if e != nil {
  83. switch err := e.(type) {
  84. case runtime.Error:
  85. panic(e)
  86. case error:
  87. *errp = err
  88. default:
  89. panic(e)
  90. }
  91. }
  92. }
  93. // ExecuteTemplate applies the template associated with t that has the given name
  94. // to the specified data object and writes the output to wr.
  95. func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
  96. tmpl := t.tmpl[name]
  97. if tmpl == nil {
  98. return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
  99. }
  100. return tmpl.Execute(wr, data)
  101. }
  102. // Execute applies a parsed template to the specified data object,
  103. // and writes the output to wr.
  104. func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
  105. defer errRecover(&err)
  106. value := reflect.ValueOf(data)
  107. state := &state{
  108. tmpl: t,
  109. wr: wr,
  110. vars: []variable{{"$", value}},
  111. }
  112. if t.Tree == nil || t.Root == nil {
  113. state.errorf("%q is an incomplete or empty template", t.name)
  114. }
  115. state.walk(value, t.Root)
  116. return
  117. }
  118. // Walk functions step through the major pieces of the template structure,
  119. // generating output as they go.
  120. func (s *state) walk(dot reflect.Value, node parse.Node) {
  121. s.at(node)
  122. switch node := node.(type) {
  123. case *parse.ActionNode:
  124. // Do not pop variables so they persist until next end.
  125. // Also, if the action declares variables, don't print the result.
  126. val := s.evalPipeline(dot, node.Pipe)
  127. if len(node.Pipe.Decl) == 0 {
  128. s.printValue(node, val)
  129. }
  130. case *parse.IfNode:
  131. s.walkIfOrWith(parse.NodeIf, dot, node.Pipe, node.List, node.ElseList)
  132. case *parse.ListNode:
  133. for _, node := range node.Nodes {
  134. s.walk(dot, node)
  135. }
  136. case *parse.RangeNode:
  137. s.walkRange(dot, node)
  138. case *parse.TemplateNode:
  139. s.walkTemplate(dot, node)
  140. case *parse.TextNode:
  141. if _, err := s.wr.Write(node.Text); err != nil {
  142. s.errorf("%s", err)
  143. }
  144. case *parse.WithNode:
  145. s.walkIfOrWith(parse.NodeWith, dot, node.Pipe, node.List, node.ElseList)
  146. default:
  147. s.errorf("unknown node: %s", node)
  148. }
  149. }
  150. // walkIfOrWith walks an 'if' or 'with' node. The two control structures
  151. // are identical in behavior except that 'with' sets dot.
  152. func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
  153. defer s.pop(s.mark())
  154. val := s.evalPipeline(dot, pipe)
  155. truth, ok := isTrue(val)
  156. if !ok {
  157. s.errorf("if/with can't use %v", val)
  158. }
  159. if truth {
  160. if typ == parse.NodeWith {
  161. s.walk(val, list)
  162. } else {
  163. s.walk(dot, list)
  164. }
  165. } else if elseList != nil {
  166. s.walk(dot, elseList)
  167. }
  168. }
  169. // isTrue returns whether the value is 'true', in the sense of not the zero of its type,
  170. // and whether the value has a meaningful truth value.
  171. func isTrue(val reflect.Value) (truth, ok bool) {
  172. if !val.IsValid() {
  173. // Something like var x interface{}, never set. It's a form of nil.
  174. return false, true
  175. }
  176. switch val.Kind() {
  177. case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
  178. truth = val.Len() > 0
  179. case reflect.Bool:
  180. truth = val.Bool()
  181. case reflect.Complex64, reflect.Complex128:
  182. truth = val.Complex() != 0
  183. case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
  184. truth = !val.IsNil()
  185. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  186. truth = val.Int() != 0
  187. case reflect.Float32, reflect.Float64:
  188. truth = val.Float() != 0
  189. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  190. truth = val.Uint() != 0
  191. case reflect.Struct:
  192. truth = true // Struct values are always true.
  193. default:
  194. return
  195. }
  196. return truth, true
  197. }
  198. func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
  199. s.at(r)
  200. defer s.pop(s.mark())
  201. val, _ := indirect(s.evalPipeline(dot, r.Pipe))
  202. // mark top of stack before any variables in the body are pushed.
  203. mark := s.mark()
  204. oneIteration := func(index, elem reflect.Value) {
  205. // Set top var (lexically the second if there are two) to the element.
  206. if len(r.Pipe.Decl) > 0 {
  207. s.setVar(1, elem)
  208. }
  209. // Set next var (lexically the first if there are two) to the index.
  210. if len(r.Pipe.Decl) > 1 {
  211. s.setVar(2, index)
  212. }
  213. s.walk(elem, r.List)
  214. s.pop(mark)
  215. }
  216. switch val.Kind() {
  217. case reflect.Array, reflect.Slice:
  218. if val.Len() == 0 {
  219. break
  220. }
  221. for i := 0; i < val.Len(); i++ {
  222. oneIteration(reflect.ValueOf(i), val.Index(i))
  223. }
  224. return
  225. case reflect.Map:
  226. if val.Len() == 0 {
  227. break
  228. }
  229. for _, key := range sortKeys(val.MapKeys()) {
  230. oneIteration(key, val.MapIndex(key))
  231. }
  232. return
  233. case reflect.Chan:
  234. if val.IsNil() {
  235. break
  236. }
  237. i := 0
  238. for ; ; i++ {
  239. elem, ok := val.Recv()
  240. if !ok {
  241. break
  242. }
  243. oneIteration(reflect.ValueOf(i), elem)
  244. }
  245. if i == 0 {
  246. break
  247. }
  248. return
  249. case reflect.Invalid:
  250. break // An invalid value is likely a nil map, etc. and acts like an empty map.
  251. default:
  252. s.errorf("range can't iterate over %v", val)
  253. }
  254. if r.ElseList != nil {
  255. s.walk(dot, r.ElseList)
  256. }
  257. }
  258. func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
  259. s.at(t)
  260. tmpl := s.tmpl.tmpl[t.Name]
  261. if tmpl == nil {
  262. s.errorf("template %q not defined", t.Name)
  263. }
  264. // Variables declared by the pipeline persist.
  265. dot = s.evalPipeline(dot, t.Pipe)
  266. newState := *s
  267. newState.tmpl = tmpl
  268. // No dynamic scoping: template invocations inherit no variables.
  269. newState.vars = []variable{{"$", dot}}
  270. newState.walk(dot, tmpl.Root)
  271. }
  272. // Eval functions evaluate pipelines, commands, and their elements and extract
  273. // values from the data structure by examining fields, calling methods, and so on.
  274. // The printing of those values happens only through walk functions.
  275. // evalPipeline returns the value acquired by evaluating a pipeline. If the
  276. // pipeline has a variable declaration, the variable will be pushed on the
  277. // stack. Callers should therefore pop the stack after they are finished
  278. // executing commands depending on the pipeline value.
  279. func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
  280. if pipe == nil {
  281. return
  282. }
  283. s.at(pipe)
  284. for _, cmd := range pipe.Cmds {
  285. value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
  286. // If the object has type interface{}, dig down one level to the thing inside.
  287. if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
  288. value = reflect.ValueOf(value.Interface()) // lovely!
  289. }
  290. }
  291. for _, variable := range pipe.Decl {
  292. s.push(variable.Ident[0], value)
  293. }
  294. return value
  295. }
  296. func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
  297. if len(args) > 1 || final.IsValid() {
  298. s.errorf("can't give argument to non-function %s", args[0])
  299. }
  300. }
  301. func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
  302. firstWord := cmd.Args[0]
  303. switch n := firstWord.(type) {
  304. case *parse.FieldNode:
  305. return s.evalFieldNode(dot, n, cmd.Args, final)
  306. case *parse.ChainNode:
  307. return s.evalChainNode(dot, n, cmd.Args, final)
  308. case *parse.IdentifierNode:
  309. // Must be a function.
  310. return s.evalFunction(dot, n, cmd, cmd.Args, final)
  311. case *parse.PipeNode:
  312. // Parenthesized pipeline. The arguments are all inside the pipeline; final is ignored.
  313. return s.evalPipeline(dot, n)
  314. case *parse.VariableNode:
  315. return s.evalVariableNode(dot, n, cmd.Args, final)
  316. }
  317. s.at(firstWord)
  318. s.notAFunction(cmd.Args, final)
  319. switch word := firstWord.(type) {
  320. case *parse.BoolNode:
  321. return reflect.ValueOf(word.True)
  322. case *parse.DotNode:
  323. return dot
  324. case *parse.NilNode:
  325. s.errorf("nil is not a command")
  326. case *parse.NumberNode:
  327. return s.idealConstant(word)
  328. case *parse.StringNode:
  329. return reflect.ValueOf(word.Text)
  330. }
  331. s.errorf("can't evaluate command %q", firstWord)
  332. panic("not reached")
  333. }
  334. // idealConstant is called to return the value of a number in a context where
  335. // we don't know the type. In that case, the syntax of the number tells us
  336. // its type, and we use Go rules to resolve. Note there is no such thing as
  337. // a uint ideal constant in this situation - the value must be of int type.
  338. func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
  339. // These are ideal constants but we don't know the type
  340. // and we have no context. (If it was a method argument,
  341. // we'd know what we need.) The syntax guides us to some extent.
  342. s.at(constant)
  343. switch {
  344. case constant.IsComplex:
  345. return reflect.ValueOf(constant.Complex128) // incontrovertible.
  346. case constant.IsFloat && strings.IndexAny(constant.Text, ".eE") >= 0:
  347. return reflect.ValueOf(constant.Float64)
  348. case constant.IsInt:
  349. n := int(constant.Int64)
  350. if int64(n) != constant.Int64 {
  351. s.errorf("%s overflows int", constant.Text)
  352. }
  353. return reflect.ValueOf(n)
  354. case constant.IsUint:
  355. s.errorf("%s overflows int", constant.Text)
  356. }
  357. return zero
  358. }
  359. func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
  360. s.at(field)
  361. return s.evalFieldChain(dot, dot, field, field.Ident, args, final)
  362. }
  363. func (s *state) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value {
  364. s.at(chain)
  365. // (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields.
  366. pipe := s.evalArg(dot, nil, chain.Node)
  367. if len(chain.Field) == 0 {
  368. s.errorf("internal error: no fields in evalChainNode")
  369. }
  370. return s.evalFieldChain(dot, pipe, chain, chain.Field, args, final)
  371. }
  372. func (s *state) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
  373. // $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
  374. s.at(variable)
  375. value := s.varValue(variable.Ident[0])
  376. if len(variable.Ident) == 1 {
  377. s.notAFunction(args, final)
  378. return value
  379. }
  380. return s.evalFieldChain(dot, value, variable, variable.Ident[1:], args, final)
  381. }
  382. // evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
  383. // dot is the environment in which to evaluate arguments, while
  384. // receiver is the value being walked along the chain.
  385. func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
  386. n := len(ident)
  387. for i := 0; i < n-1; i++ {
  388. receiver = s.evalField(dot, ident[i], node, nil, zero, receiver)
  389. }
  390. // Now if it's a method, it gets the arguments.
  391. return s.evalField(dot, ident[n-1], node, args, final, receiver)
  392. }
  393. func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
  394. s.at(node)
  395. name := node.Ident
  396. function, ok := findFunction(name, s.tmpl)
  397. if !ok {
  398. s.errorf("%q is not a defined function", name)
  399. }
  400. return s.evalCall(dot, function, cmd, name, args, final)
  401. }
  402. // evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
  403. // The 'final' argument represents the return value from the preceding
  404. // value of the pipeline, if any.
  405. func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
  406. if !receiver.IsValid() {
  407. return zero
  408. }
  409. typ := receiver.Type()
  410. receiver, _ = indirect(receiver)
  411. // Unless it's an interface, need to get to a value of type *T to guarantee
  412. // we see all methods of T and *T.
  413. ptr := receiver
  414. if ptr.Kind() != reflect.Interface && ptr.CanAddr() {
  415. ptr = ptr.Addr()
  416. }
  417. if method := ptr.MethodByName(fieldName); method.IsValid() {
  418. return s.evalCall(dot, method, node, fieldName, args, final)
  419. }
  420. hasArgs := len(args) > 1 || final.IsValid()
  421. // It's not a method; must be a field of a struct or an element of a map. The receiver must not be nil.
  422. receiver, isNil := indirect(receiver)
  423. if isNil {
  424. s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
  425. }
  426. switch receiver.Kind() {
  427. case reflect.Struct:
  428. tField, ok := receiver.Type().FieldByName(fieldName)
  429. if ok {
  430. field := receiver.FieldByIndex(tField.Index)
  431. if tField.PkgPath != "" { // field is unexported
  432. s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
  433. }
  434. // If it's a function, we must call it.
  435. if hasArgs {
  436. s.errorf("%s has arguments but cannot be invoked as function", fieldName)
  437. }
  438. return field
  439. }
  440. s.errorf("%s is not a field of struct type %s", fieldName, typ)
  441. case reflect.Map:
  442. // If it's a map, attempt to use the field name as a key.
  443. nameVal := reflect.ValueOf(fieldName)
  444. if nameVal.Type().AssignableTo(receiver.Type().Key()) {
  445. if hasArgs {
  446. s.errorf("%s is not a method but has arguments", fieldName)
  447. }
  448. return receiver.MapIndex(nameVal)
  449. }
  450. }
  451. s.errorf("can't evaluate field %s in type %s", fieldName, typ)
  452. panic("not reached")
  453. }
  454. var (
  455. errorType = reflect.TypeOf((*error)(nil)).Elem()
  456. fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
  457. )
  458. // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
  459. // it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
  460. // as the function itself.
  461. func (s *state) evalCall(dot, fun reflect.Value, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value {
  462. if args != nil {
  463. args = args[1:] // Zeroth arg is function name/node; not passed to function.
  464. }
  465. typ := fun.Type()
  466. numIn := len(args)
  467. if final.IsValid() {
  468. numIn++
  469. }
  470. numFixed := len(args)
  471. if typ.IsVariadic() {
  472. numFixed = typ.NumIn() - 1 // last arg is the variadic one.
  473. if numIn < numFixed {
  474. s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
  475. }
  476. } else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() {
  477. s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args))
  478. }
  479. if !goodFunc(typ) {
  480. // TODO: This could still be a confusing error; maybe goodFunc should provide info.
  481. s.errorf("can't call method/function %q with %d results", name, typ.NumOut())
  482. }
  483. // Build the arg list.
  484. argv := make([]reflect.Value, numIn)
  485. // Args must be evaluated. Fixed args first.
  486. i := 0
  487. for ; i < numFixed; i++ {
  488. argv[i] = s.evalArg(dot, typ.In(i), args[i])
  489. }
  490. // Now the ... args.
  491. if typ.IsVariadic() {
  492. argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
  493. for ; i < len(args); i++ {
  494. argv[i] = s.evalArg(dot, argType, args[i])
  495. }
  496. }
  497. // Add final value if necessary.
  498. if final.IsValid() {
  499. t := typ.In(typ.NumIn() - 1)
  500. if typ.IsVariadic() {
  501. t = t.Elem()
  502. }
  503. argv[i] = s.validateType(final, t)
  504. }
  505. result := fun.Call(argv)
  506. // If we have an error that is not nil, stop execution and return that error to the caller.
  507. if len(result) == 2 && !result[1].IsNil() {
  508. s.at(node)
  509. s.errorf("error calling %s: %s", name, result[1].Interface().(error))
  510. }
  511. return result[0]
  512. }
  513. // canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero.
  514. func canBeNil(typ reflect.Type) bool {
  515. switch typ.Kind() {
  516. case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
  517. return true
  518. }
  519. return false
  520. }
  521. // validateType guarantees that the value is valid and assignable to the type.
  522. func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
  523. if !value.IsValid() {
  524. if typ == nil || canBeNil(typ) {
  525. // An untyped nil interface{}. Accept as a proper nil value.
  526. return reflect.Zero(typ)
  527. }
  528. s.errorf("invalid value; expected %s", typ)
  529. }
  530. if typ != nil && !value.Type().AssignableTo(typ) {
  531. if value.Kind() == reflect.Interface && !value.IsNil() {
  532. value = value.Elem()
  533. if value.Type().AssignableTo(typ) {
  534. return value
  535. }
  536. // fallthrough
  537. }
  538. // Does one dereference or indirection work? We could do more, as we
  539. // do with method receivers, but that gets messy and method receivers
  540. // are much more constrained, so it makes more sense there than here.
  541. // Besides, one is almost always all you need.
  542. switch {
  543. case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
  544. value = value.Elem()
  545. case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
  546. value = value.Addr()
  547. default:
  548. s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
  549. }
  550. }
  551. return value
  552. }
  553. func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
  554. s.at(n)
  555. switch arg := n.(type) {
  556. case *parse.DotNode:
  557. return s.validateType(dot, typ)
  558. case *parse.NilNode:
  559. if canBeNil(typ) {
  560. return reflect.Zero(typ)
  561. }
  562. s.errorf("cannot assign nil to %s", typ)
  563. case *parse.FieldNode:
  564. return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, zero), typ)
  565. case *parse.VariableNode:
  566. return s.validateType(s.evalVariableNode(dot, arg, nil, zero), typ)
  567. case *parse.PipeNode:
  568. return s.validateType(s.evalPipeline(dot, arg), typ)
  569. }
  570. switch typ.Kind() {
  571. case reflect.Bool:
  572. return s.evalBool(typ, n)
  573. case reflect.Complex64, reflect.Complex128:
  574. return s.evalComplex(typ, n)
  575. case reflect.Float32, reflect.Float64:
  576. return s.evalFloat(typ, n)
  577. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  578. return s.evalInteger(typ, n)
  579. case reflect.Interface:
  580. if typ.NumMethod() == 0 {
  581. return s.evalEmptyInterface(dot, n)
  582. }
  583. case reflect.String:
  584. return s.evalString(typ, n)
  585. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  586. return s.evalUnsignedInteger(typ, n)
  587. }
  588. s.errorf("can't handle %s for arg of type %s", n, typ)
  589. panic("not reached")
  590. }
  591. func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
  592. s.at(n)
  593. if n, ok := n.(*parse.BoolNode); ok {
  594. value := reflect.New(typ).Elem()
  595. value.SetBool(n.True)
  596. return value
  597. }
  598. s.errorf("expected bool; found %s", n)
  599. panic("not reached")
  600. }
  601. func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
  602. s.at(n)
  603. if n, ok := n.(*parse.StringNode); ok {
  604. value := reflect.New(typ).Elem()
  605. value.SetString(n.Text)
  606. return value
  607. }
  608. s.errorf("expected string; found %s", n)
  609. panic("not reached")
  610. }
  611. func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
  612. s.at(n)
  613. if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
  614. value := reflect.New(typ).Elem()
  615. value.SetInt(n.Int64)
  616. return value
  617. }
  618. s.errorf("expected integer; found %s", n)
  619. panic("not reached")
  620. }
  621. func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
  622. s.at(n)
  623. if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
  624. value := reflect.New(typ).Elem()
  625. value.SetUint(n.Uint64)
  626. return value
  627. }
  628. s.errorf("expected unsigned integer; found %s", n)
  629. panic("not reached")
  630. }
  631. func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
  632. s.at(n)
  633. if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
  634. value := reflect.New(typ).Elem()
  635. value.SetFloat(n.Float64)
  636. return value
  637. }
  638. s.errorf("expected float; found %s", n)
  639. panic("not reached")
  640. }
  641. func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
  642. if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
  643. value := reflect.New(typ).Elem()
  644. value.SetComplex(n.Complex128)
  645. return value
  646. }
  647. s.errorf("expected complex; found %s", n)
  648. panic("not reached")
  649. }
  650. func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
  651. s.at(n)
  652. switch n := n.(type) {
  653. case *parse.BoolNode:
  654. return reflect.ValueOf(n.True)
  655. case *parse.DotNode:
  656. return dot
  657. case *parse.FieldNode:
  658. return s.evalFieldNode(dot, n, nil, zero)
  659. case *parse.IdentifierNode:
  660. return s.evalFunction(dot, n, n, nil, zero)
  661. case *parse.NilNode:
  662. // NilNode is handled in evalArg, the only place that calls here.
  663. s.errorf("evalEmptyInterface: nil (can't happen)")
  664. case *parse.NumberNode:
  665. return s.idealConstant(n)
  666. case *parse.StringNode:
  667. return reflect.ValueOf(n.Text)
  668. case *parse.VariableNode:
  669. return s.evalVariableNode(dot, n, nil, zero)
  670. case *parse.PipeNode:
  671. return s.evalPipeline(dot, n)
  672. }
  673. s.errorf("can't handle assignment of %s to empty interface argument", n)
  674. panic("not reached")
  675. }
  676. // indirect returns the item at the end of indirection, and a bool to indicate if it's nil.
  677. // We indirect through pointers and empty interfaces (only) because
  678. // non-empty interfaces have methods we might need.
  679. func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
  680. for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
  681. if v.IsNil() {
  682. return v, true
  683. }
  684. if v.Kind() == reflect.Interface && v.NumMethod() > 0 {
  685. break
  686. }
  687. }
  688. return v, false
  689. }
  690. // printValue writes the textual representation of the value to the output of
  691. // the template.
  692. func (s *state) printValue(n parse.Node, v reflect.Value) {
  693. s.at(n)
  694. if v.Kind() == reflect.Ptr {
  695. v, _ = indirect(v) // fmt.Fprint handles nil.
  696. }
  697. if !v.IsValid() {
  698. fmt.Fprint(s.wr, "<no value>")
  699. return
  700. }
  701. if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
  702. if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
  703. v = v.Addr()
  704. } else {
  705. switch v.Kind() {
  706. case reflect.Chan, reflect.Func:
  707. s.errorf("can't print %s of type %s", n, v.Type())
  708. }
  709. }
  710. }
  711. fmt.Fprint(s.wr, v.Interface())
  712. }
  713. // Types to help sort the keys in a map for reproducible output.
  714. type rvs []reflect.Value
  715. func (x rvs) Len() int { return len(x) }
  716. func (x rvs) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
  717. type rvInts struct{ rvs }
  718. func (x rvInts) Less(i, j int) bool { return x.rvs[i].Int() < x.rvs[j].Int() }
  719. type rvUints struct{ rvs }
  720. func (x rvUints) Less(i, j int) bool { return x.rvs[i].Uint() < x.rvs[j].Uint() }
  721. type rvFloats struct{ rvs }
  722. func (x rvFloats) Less(i, j int) bool { return x.rvs[i].Float() < x.rvs[j].Float() }
  723. type rvStrings struct{ rvs }
  724. func (x rvStrings) Less(i, j int) bool { return x.rvs[i].String() < x.rvs[j].String() }
  725. // sortKeys sorts (if it can) the slice of reflect.Values, which is a slice of map keys.
  726. func sortKeys(v []reflect.Value) []reflect.Value {
  727. if len(v) <= 1 {
  728. return v
  729. }
  730. switch v[0].Kind() {
  731. case reflect.Float32, reflect.Float64:
  732. sort.Sort(rvFloats{v})
  733. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  734. sort.Sort(rvInts{v})
  735. case reflect.String:
  736. sort.Sort(rvStrings{v})
  737. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  738. sort.Sort(rvUints{v})
  739. }
  740. return v
  741. }