node.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. // Copyright 2016 José Santos <henrique_1609@me.com>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package jet
  15. import (
  16. "bytes"
  17. "fmt"
  18. )
  19. var textFormat = "%s" //Changed to "%q" in tests for better error messages.
  20. type Node interface {
  21. Type() NodeType
  22. String() string
  23. Position() Pos
  24. line() int
  25. error(error)
  26. errorf(string, ...interface{})
  27. }
  28. type Expression interface {
  29. Node
  30. }
  31. // Pos represents a byte position in the original input text from which
  32. // this template was parsed.
  33. type Pos int
  34. func (p Pos) Position() Pos {
  35. return p
  36. }
  37. // NodeType identifies the type of a parse tree node.
  38. type NodeType int
  39. type NodeBase struct {
  40. TemplatePath string
  41. Line int
  42. NodeType
  43. Pos
  44. }
  45. func (node *NodeBase) line() int {
  46. return node.Line
  47. }
  48. func (node *NodeBase) error(err error) {
  49. node.errorf("%s", err)
  50. }
  51. func (node *NodeBase) errorf(format string, v ...interface{}) {
  52. panic(fmt.Errorf("Jet Runtime Error (%q:%d): %s", node.TemplatePath, node.Line, fmt.Sprintf(format, v...)))
  53. }
  54. // Type returns itself and provides an easy default implementation
  55. // for embedding in a Node. Embedded in all non-trivial Nodes.
  56. func (t NodeType) Type() NodeType {
  57. return t
  58. }
  59. const (
  60. NodeText NodeType = iota //Plain text.
  61. NodeAction //A non-control action such as a field evaluation.
  62. NodeChain //A sequence of field accesses.
  63. NodeCommand //An element of a pipeline.
  64. NodeField //A field or method name.
  65. NodeIdentifier //An identifier; always a function name.
  66. NodeList //A list of Nodes.
  67. NodePipe //A pipeline of commands.
  68. NodeSet
  69. //NodeWith //A with action.
  70. NodeInclude
  71. NodeBlock
  72. nodeEnd //An end action. Not added to tree.
  73. NodeYield
  74. nodeContent
  75. NodeIf //An if action.
  76. nodeElse //An else action. Not added to tree.
  77. NodeRange //A range action.
  78. NodeTry
  79. nodeCatch
  80. NodeReturn
  81. beginExpressions
  82. NodeString //A string constant.
  83. NodeNil //An untyped nil constant.
  84. NodeNumber //A numerical constant.
  85. NodeBool //A boolean constant.
  86. NodeAdditiveExpr
  87. NodeMultiplicativeExpr
  88. NodeComparativeExpr
  89. NodeNumericComparativeExpr
  90. NodeLogicalExpr
  91. NodeCallExpr
  92. NodeNotExpr
  93. NodeTernaryExpr
  94. NodeIndexExpr
  95. NodeSliceExpr
  96. endExpressions
  97. )
  98. // Nodes.
  99. // ListNode holds a sequence of nodes.
  100. type ListNode struct {
  101. NodeBase
  102. Nodes []Node //The element nodes in lexical order.
  103. }
  104. func (l *ListNode) append(n Node) {
  105. l.Nodes = append(l.Nodes, n)
  106. }
  107. func (l *ListNode) String() string {
  108. b := new(bytes.Buffer)
  109. for _, n := range l.Nodes {
  110. fmt.Fprint(b, n)
  111. }
  112. return b.String()
  113. }
  114. // TextNode holds plain text.
  115. type TextNode struct {
  116. NodeBase
  117. Text []byte
  118. }
  119. func (t *TextNode) String() string {
  120. return fmt.Sprintf(textFormat, t.Text)
  121. }
  122. // PipeNode holds a pipeline with optional declaration
  123. type PipeNode struct {
  124. NodeBase //The line number in the input. Deprecated: Kept for compatibility.
  125. Cmds []*CommandNode //The commands in lexical order.
  126. }
  127. func (p *PipeNode) append(command *CommandNode) {
  128. p.Cmds = append(p.Cmds, command)
  129. }
  130. func (p *PipeNode) String() string {
  131. s := ""
  132. for i, c := range p.Cmds {
  133. if i > 0 {
  134. s += " | "
  135. }
  136. s += c.String()
  137. }
  138. return s
  139. }
  140. // ActionNode holds an action (something bounded by delimiters).
  141. // Control actions have their own nodes; ActionNode represents simple
  142. // ones such as field evaluations and parenthesized pipelines.
  143. type ActionNode struct {
  144. NodeBase
  145. Set *SetNode
  146. Pipe *PipeNode
  147. }
  148. func (a *ActionNode) String() string {
  149. if a.Set != nil {
  150. if a.Pipe == nil {
  151. return fmt.Sprintf("{{%s}}", a.Set)
  152. }
  153. return fmt.Sprintf("{{%s;%s}}", a.Set, a.Pipe)
  154. }
  155. return fmt.Sprintf("{{%s}}", a.Pipe)
  156. }
  157. // CommandNode holds a command (a pipeline inside an evaluating action).
  158. type CommandNode struct {
  159. NodeBase
  160. CallExprNode
  161. }
  162. func (c *CommandNode) append(arg Node) {
  163. c.Args = append(c.Args, arg)
  164. }
  165. func (c *CommandNode) String() string {
  166. if c.Args == nil {
  167. return c.BaseExpr.String()
  168. }
  169. arguments := ""
  170. for i, expr := range c.Args {
  171. if i > 0 {
  172. arguments += ", "
  173. }
  174. arguments += expr.String()
  175. }
  176. return fmt.Sprintf("%s(%s)", c.BaseExpr, arguments)
  177. }
  178. // IdentifierNode holds an identifier.
  179. type IdentifierNode struct {
  180. NodeBase
  181. Ident string //The identifier's name.
  182. }
  183. func (i *IdentifierNode) String() string {
  184. return i.Ident
  185. }
  186. // NilNode holds the special identifier 'nil' representing an untyped nil constant.
  187. type NilNode struct {
  188. NodeBase
  189. }
  190. func (n *NilNode) String() string {
  191. return "nil"
  192. }
  193. // FieldNode holds a field (identifier starting with '.').
  194. // The names may be chained ('.x.y').
  195. // The period is dropped from each ident.
  196. type FieldNode struct {
  197. NodeBase
  198. Ident []string //The identifiers in lexical order.
  199. }
  200. func (f *FieldNode) String() string {
  201. s := ""
  202. for _, id := range f.Ident {
  203. s += "." + id
  204. }
  205. return s
  206. }
  207. // ChainNode holds a term followed by a chain of field accesses (identifier starting with '.').
  208. // The names may be chained ('.x.y').
  209. // The periods are dropped from each ident.
  210. type ChainNode struct {
  211. NodeBase
  212. Node Node
  213. Field []string //The identifiers in lexical order.
  214. }
  215. // Add adds the named field (which should start with a period) to the end of the chain.
  216. func (c *ChainNode) Add(field string) {
  217. if len(field) == 0 || field[0] != '.' {
  218. panic("no dot in field")
  219. }
  220. field = field[1:] //Remove leading dot.
  221. if field == "" {
  222. panic("empty field")
  223. }
  224. c.Field = append(c.Field, field)
  225. }
  226. func (c *ChainNode) String() string {
  227. s := c.Node.String()
  228. if _, ok := c.Node.(*PipeNode); ok {
  229. s = "(" + s + ")"
  230. }
  231. for _, field := range c.Field {
  232. s += "." + field
  233. }
  234. return s
  235. }
  236. // BoolNode holds a boolean constant.
  237. type BoolNode struct {
  238. NodeBase
  239. True bool //The value of the boolean constant.
  240. }
  241. func (b *BoolNode) String() string {
  242. if b.True {
  243. return "true"
  244. }
  245. return "false"
  246. }
  247. // NumberNode holds a number: signed or unsigned integer, float, or complex.
  248. // The value is parsed and stored under all the types that can represent the value.
  249. // This simulates in a small amount of code the behavior of Go's ideal constants.
  250. type NumberNode struct {
  251. NodeBase
  252. IsInt bool //Number has an integral value.
  253. IsUint bool //Number has an unsigned integral value.
  254. IsFloat bool //Number has a floating-point value.
  255. IsComplex bool //Number is complex.
  256. Int64 int64 //The signed integer value.
  257. Uint64 uint64 //The unsigned integer value.
  258. Float64 float64 //The floating-point value.
  259. Complex128 complex128 //The complex value.
  260. Text string //The original textual representation from the input.
  261. }
  262. // simplifyComplex pulls out any other types that are represented by the complex number.
  263. // These all require that the imaginary part be zero.
  264. func (n *NumberNode) simplifyComplex() {
  265. n.IsFloat = imag(n.Complex128) == 0
  266. if n.IsFloat {
  267. n.Float64 = real(n.Complex128)
  268. n.IsInt = float64(int64(n.Float64)) == n.Float64
  269. if n.IsInt {
  270. n.Int64 = int64(n.Float64)
  271. }
  272. n.IsUint = float64(uint64(n.Float64)) == n.Float64
  273. if n.IsUint {
  274. n.Uint64 = uint64(n.Float64)
  275. }
  276. }
  277. }
  278. func (n *NumberNode) String() string {
  279. return n.Text
  280. }
  281. // StringNode holds a string constant. The value has been "unquoted".
  282. type StringNode struct {
  283. NodeBase
  284. Quoted string //The original text of the string, with quotes.
  285. Text string //The string, after quote processing.
  286. }
  287. func (s *StringNode) String() string {
  288. return s.Quoted
  289. }
  290. // endNode represents an {{end}} action.
  291. // It does not appear in the final parse tree.
  292. type endNode struct {
  293. NodeBase
  294. }
  295. func (e *endNode) String() string {
  296. return "{{end}}"
  297. }
  298. // endNode represents an {{end}} action.
  299. // It does not appear in the final parse tree.
  300. type contentNode struct {
  301. NodeBase
  302. }
  303. func (e *contentNode) String() string {
  304. return "{{content}}"
  305. }
  306. // elseNode represents an {{else}} action. Does not appear in the final tree.
  307. type elseNode struct {
  308. NodeBase //The line number in the input. Deprecated: Kept for compatibility.
  309. }
  310. func (e *elseNode) String() string {
  311. return "{{else}}"
  312. }
  313. // SetNode represents a set action, ident( ',' ident)* '=' expression ( ',' expression )*
  314. type SetNode struct {
  315. NodeBase
  316. Let bool
  317. IndexExprGetLookup bool
  318. Left []Expression
  319. Right []Expression
  320. }
  321. func (set *SetNode) String() string {
  322. var s = ""
  323. for i, v := range set.Left {
  324. if i > 0 {
  325. s += ", "
  326. }
  327. s += v.String()
  328. }
  329. if set.Let {
  330. s += ":="
  331. } else {
  332. s += "="
  333. }
  334. for i, v := range set.Right {
  335. if i > 0 {
  336. s += ", "
  337. }
  338. s += v.String()
  339. }
  340. return s
  341. }
  342. // BranchNode is the common representation of if, range, and with.
  343. type BranchNode struct {
  344. NodeBase
  345. Set *SetNode
  346. Expression Expression
  347. List *ListNode
  348. ElseList *ListNode
  349. }
  350. func (b *BranchNode) String() string {
  351. if b.NodeType == NodeRange {
  352. s := ""
  353. if b.Set != nil {
  354. s = b.Set.String()
  355. } else {
  356. s = b.Expression.String()
  357. }
  358. if b.ElseList != nil {
  359. return fmt.Sprintf("{{range %s}}%s{{else}}%s{{end}}", s, b.List, b.ElseList)
  360. }
  361. return fmt.Sprintf("{{range %s}}%s{{end}}", s, b.List)
  362. } else {
  363. s := ""
  364. if b.Set != nil {
  365. s = b.Set.String() + ";"
  366. }
  367. if b.ElseList != nil {
  368. return fmt.Sprintf("{{if %s%s}}%s{{else}}%s{{end}}", s, b.Expression, b.List, b.ElseList)
  369. }
  370. return fmt.Sprintf("{{if %s%s}}%s{{end}}", s, b.Expression, b.List)
  371. }
  372. }
  373. // IfNode represents an {{if}} action and its commands.
  374. type IfNode struct {
  375. BranchNode
  376. }
  377. // RangeNode represents a {{range}} action and its commands.
  378. type RangeNode struct {
  379. BranchNode
  380. }
  381. type BlockParameter struct {
  382. Identifier string
  383. Expression Expression
  384. }
  385. type BlockParameterList struct {
  386. NodeBase
  387. List []BlockParameter
  388. }
  389. func (bplist *BlockParameterList) Param(name string) (Expression, int) {
  390. for i := 0; i < len(bplist.List); i++ {
  391. param := &bplist.List[i]
  392. if param.Identifier == name {
  393. return param.Expression, i
  394. }
  395. }
  396. return nil, -1
  397. }
  398. func (bplist *BlockParameterList) String() (str string) {
  399. buff := bytes.NewBuffer(nil)
  400. for _, bp := range bplist.List {
  401. if bp.Identifier == "" {
  402. fmt.Fprintf(buff, "%s,", bp.Expression)
  403. } else {
  404. if bp.Expression == nil {
  405. fmt.Fprintf(buff, "%s,", bp.Identifier)
  406. } else {
  407. fmt.Fprintf(buff, "%s=%s,", bp.Identifier, bp.Expression)
  408. }
  409. }
  410. }
  411. if buff.Len() > 0 {
  412. str = buff.String()[0 : buff.Len()-1]
  413. }
  414. return
  415. }
  416. // BlockNode represents a {{block }} action.
  417. type BlockNode struct {
  418. NodeBase //The line number in the input. Deprecated: Kept for compatibility.
  419. Name string //The name of the template (unquoted).
  420. Parameters *BlockParameterList
  421. Expression Expression //The command to evaluate as dot for the template.
  422. List *ListNode
  423. Content *ListNode
  424. }
  425. func (t *BlockNode) String() string {
  426. if t.Content != nil {
  427. if t.Expression == nil {
  428. return fmt.Sprintf("{{block %s(%s)}}%s{{content}}%s{{end}}", t.Name, t.Parameters, t.List, t.Content)
  429. }
  430. return fmt.Sprintf("{{block %s(%s) %s}}%s{{content}}%s{{end}}", t.Name, t.Parameters, t.Expression, t.List, t.Content)
  431. }
  432. if t.Expression == nil {
  433. return fmt.Sprintf("{{block %s(%s)}}%s{{end}}", t.Name, t.Parameters, t.List)
  434. }
  435. return fmt.Sprintf("{{block %s(%s) %s}}%s{{end}}", t.Name, t.Parameters, t.Expression, t.List)
  436. }
  437. // YieldNode represents a {{yield}} action
  438. type YieldNode struct {
  439. NodeBase //The line number in the input. Deprecated: Kept for compatibility.
  440. Name string //The name of the template (unquoted).
  441. Parameters *BlockParameterList
  442. Expression Expression //The command to evaluate as dot for the template.
  443. Content *ListNode
  444. IsContent bool
  445. }
  446. func (t *YieldNode) String() string {
  447. if t.IsContent {
  448. if t.Expression == nil {
  449. return "{{yield content}}"
  450. }
  451. return fmt.Sprintf("{{yield content %s}}", t.Expression)
  452. }
  453. if t.Content != nil {
  454. if t.Expression == nil {
  455. return fmt.Sprintf("{{yield %s(%s) content}}%s{{end}}", t.Name, t.Parameters, t.Content)
  456. }
  457. return fmt.Sprintf("{{yield %s(%s) %s content}}%s{{end}}", t.Name, t.Parameters, t.Expression, t.Content)
  458. }
  459. if t.Expression == nil {
  460. return fmt.Sprintf("{{yield %s(%s)}}", t.Name, t.Parameters)
  461. }
  462. return fmt.Sprintf("{{yield %s(%s) %s}}", t.Name, t.Parameters, t.Expression)
  463. }
  464. // IncludeNode represents a {{include }} action.
  465. type IncludeNode struct {
  466. NodeBase
  467. Name Expression
  468. Context Expression
  469. }
  470. func (t *IncludeNode) String() string {
  471. if t.Context == nil {
  472. return fmt.Sprintf("{{include %s}}", t.Name)
  473. }
  474. return fmt.Sprintf("{{include %s %s}}", t.Name, t.Context)
  475. }
  476. type binaryExprNode struct {
  477. NodeBase
  478. Operator item
  479. Left, Right Expression
  480. }
  481. func (node *binaryExprNode) String() string {
  482. return fmt.Sprintf("%s %s %s", node.Left, node.Operator.val, node.Right)
  483. }
  484. // AdditiveExprNode represents an add or subtract expression
  485. // ex: expression ( '+' | '-' ) expression
  486. type AdditiveExprNode struct {
  487. binaryExprNode
  488. }
  489. // MultiplicativeExprNode represents a multiplication, division, or module expression
  490. // ex: expression ( '*' | '/' | '%' ) expression
  491. type MultiplicativeExprNode struct {
  492. binaryExprNode
  493. }
  494. // LogicalExprNode represents a boolean expression, 'and' or 'or'
  495. // ex: expression ( '&&' | '||' ) expression
  496. type LogicalExprNode struct {
  497. binaryExprNode
  498. }
  499. // ComparativeExprNode represents a comparative expression
  500. // ex: expression ( '==' | '!=' ) expression
  501. type ComparativeExprNode struct {
  502. binaryExprNode
  503. }
  504. // NumericComparativeExprNode represents a numeric comparative expression
  505. // ex: expression ( '<' | '>' | '<=' | '>=' ) expression
  506. type NumericComparativeExprNode struct {
  507. binaryExprNode
  508. }
  509. // NotExprNode represents a negate expression
  510. // ex: '!' expression
  511. type NotExprNode struct {
  512. NodeBase
  513. Expr Expression
  514. }
  515. func (s *NotExprNode) String() string {
  516. return fmt.Sprintf("!%s", s.Expr)
  517. }
  518. // CallExprNode represents a call expression
  519. // ex: expression '(' (expression (',' expression)* )? ')'
  520. type CallExprNode struct {
  521. NodeBase
  522. BaseExpr Expression
  523. Args []Expression
  524. }
  525. func (s *CallExprNode) String() string {
  526. arguments := ""
  527. for i, expr := range s.Args {
  528. if i > 0 {
  529. arguments += ", "
  530. }
  531. arguments += expr.String()
  532. }
  533. return fmt.Sprintf("%s(%s)", s.BaseExpr, arguments)
  534. }
  535. // TernaryExprNod represents a ternary expression,
  536. // ex: expression '?' expression ':' expression
  537. type TernaryExprNode struct {
  538. NodeBase
  539. Boolean, Left, Right Expression
  540. }
  541. func (s *TernaryExprNode) String() string {
  542. return fmt.Sprintf("%s?%s:%s", s.Boolean, s.Left, s.Right)
  543. }
  544. type IndexExprNode struct {
  545. NodeBase
  546. Base Expression
  547. Index Expression
  548. }
  549. func (s *IndexExprNode) String() string {
  550. return fmt.Sprintf("%s[%s]", s.Base, s.Index)
  551. }
  552. type SliceExprNode struct {
  553. NodeBase
  554. Base Expression
  555. Index Expression
  556. EndIndex Expression
  557. }
  558. func (s *SliceExprNode) String() string {
  559. var index_string, len_string string
  560. if s.Index != nil {
  561. index_string = s.Index.String()
  562. }
  563. if s.EndIndex != nil {
  564. len_string = s.EndIndex.String()
  565. }
  566. return fmt.Sprintf("%s[%s:%s]", s.Base, index_string, len_string)
  567. }
  568. type ReturnNode struct {
  569. NodeBase
  570. Value Expression
  571. }
  572. func (n *ReturnNode) String() string {
  573. return fmt.Sprintf("return %v", n.Value)
  574. }
  575. type TryNode struct {
  576. NodeBase
  577. List *ListNode
  578. Catch *catchNode
  579. }
  580. func (n *TryNode) String() string {
  581. if n.Catch != nil {
  582. return fmt.Sprintf("{{try}}%s%s", n.List, n.Catch)
  583. }
  584. return fmt.Sprintf("{{try}}%s{{end}}", n.List)
  585. }
  586. type catchNode struct {
  587. NodeBase
  588. Err *IdentifierNode
  589. List *ListNode
  590. }
  591. func (n *catchNode) String() string {
  592. return fmt.Sprintf("{{catch %s}}%s{{end}}", n.Err, n.List)
  593. }