PageRenderTime 50ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

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