node.go 16 KB

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