exec.go 26 KB

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