node.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. // Package ast provides structures to represent a handlebars Abstract Syntax Tree, and a Visitor interface to visit that tree.
  2. package ast
  3. import (
  4. "fmt"
  5. "strconv"
  6. )
  7. // References:
  8. // - https://github.com/wycats/handlebars.js/blob/master/lib/handlebars/compiler/ast.js
  9. // - https://github.com/wycats/handlebars.js/blob/master/docs/compiler-api.md
  10. // - https://github.com/golang/go/blob/master/src/text/template/parse/node.go
  11. // Node is an element in the AST.
  12. type Node interface {
  13. // node type
  14. Type() NodeType
  15. // location of node in original input string
  16. Location() Loc
  17. // string representation, used for debugging
  18. String() string
  19. // accepts visitor
  20. Accept(Visitor) interface{}
  21. }
  22. // Visitor is the interface to visit an AST.
  23. type Visitor interface {
  24. VisitProgram(*Program) interface{}
  25. // statements
  26. VisitMustache(*MustacheStatement) interface{}
  27. VisitBlock(*BlockStatement) interface{}
  28. VisitPartial(*PartialStatement) interface{}
  29. VisitContent(*ContentStatement) interface{}
  30. VisitComment(*CommentStatement) interface{}
  31. // expressions
  32. VisitExpression(*Expression) interface{}
  33. VisitSubExpression(*SubExpression) interface{}
  34. VisitPath(*PathExpression) interface{}
  35. // literals
  36. VisitString(*StringLiteral) interface{}
  37. VisitBoolean(*BooleanLiteral) interface{}
  38. VisitNumber(*NumberLiteral) interface{}
  39. // miscellaneous
  40. VisitHash(*Hash) interface{}
  41. VisitHashPair(*HashPair) interface{}
  42. }
  43. // NodeType represents an AST Node type.
  44. type NodeType int
  45. // Type returns itself, and permits struct includers to satisfy that part of Node interface.
  46. func (t NodeType) Type() NodeType {
  47. return t
  48. }
  49. const (
  50. // NodeProgram is the program node
  51. NodeProgram NodeType = iota
  52. // NodeMustache is the mustache statement node
  53. NodeMustache
  54. // NodeBlock is the block statement node
  55. NodeBlock
  56. // NodePartial is the partial statement node
  57. NodePartial
  58. // NodeContent is the content statement node
  59. NodeContent
  60. // NodeComment is the comment statement node
  61. NodeComment
  62. // NodeExpression is the expression node
  63. NodeExpression
  64. // NodeSubExpression is the subexpression node
  65. NodeSubExpression
  66. // NodePath is the expression path node
  67. NodePath
  68. // NodeBoolean is the literal boolean node
  69. NodeBoolean
  70. // NodeNumber is the literal number node
  71. NodeNumber
  72. // NodeString is the literal string node
  73. NodeString
  74. // NodeHash is the hash node
  75. NodeHash
  76. // NodeHashPair is the hash pair node
  77. NodeHashPair
  78. )
  79. // Loc represents the position of a parsed node in source file.
  80. type Loc struct {
  81. Pos int // Byte position
  82. Line int // Line number
  83. }
  84. // Location returns itself, and permits struct includers to satisfy that part of Node interface.
  85. func (l Loc) Location() Loc {
  86. return l
  87. }
  88. // Strip describes node whitespace management.
  89. type Strip struct {
  90. Open bool
  91. Close bool
  92. OpenStandalone bool
  93. CloseStandalone bool
  94. InlineStandalone bool
  95. }
  96. // NewStrip instanciates a Strip for given open and close mustaches.
  97. func NewStrip(openStr, closeStr string) *Strip {
  98. return &Strip{
  99. Open: (len(openStr) > 2) && openStr[2] == '~',
  100. Close: (len(closeStr) > 2) && closeStr[len(closeStr)-3] == '~',
  101. }
  102. }
  103. // NewStripForStr instanciates a Strip for given tag.
  104. func NewStripForStr(str string) *Strip {
  105. return &Strip{
  106. Open: (len(str) > 2) && str[2] == '~',
  107. Close: (len(str) > 2) && str[len(str)-3] == '~',
  108. }
  109. }
  110. // String returns a string representation of receiver that can be used for debugging.
  111. func (s *Strip) String() string {
  112. return fmt.Sprintf("Open: %t, Close: %t, OpenStandalone: %t, CloseStandalone: %t, InlineStandalone: %t", s.Open, s.Close, s.OpenStandalone, s.CloseStandalone, s.InlineStandalone)
  113. }
  114. //
  115. // Program
  116. //
  117. // Program represents a program node.
  118. type Program struct {
  119. NodeType
  120. Loc
  121. Body []Node // [ Statement ... ]
  122. BlockParams []string
  123. Chained bool
  124. // whitespace management
  125. Strip *Strip
  126. }
  127. // NewProgram instanciates a new program node.
  128. func NewProgram(pos int, line int) *Program {
  129. return &Program{
  130. NodeType: NodeProgram,
  131. Loc: Loc{pos, line},
  132. }
  133. }
  134. // String returns a string representation of receiver that can be used for debugging.
  135. func (node *Program) String() string {
  136. return fmt.Sprintf("Program{Pos: %d}", node.Loc.Pos)
  137. }
  138. // Accept is the receiver entry point for visitors.
  139. func (node *Program) Accept(visitor Visitor) interface{} {
  140. return visitor.VisitProgram(node)
  141. }
  142. // AddStatement adds given statement to program.
  143. func (node *Program) AddStatement(statement Node) {
  144. node.Body = append(node.Body, statement)
  145. }
  146. //
  147. // Mustache Statement
  148. //
  149. // MustacheStatement represents a mustache node.
  150. type MustacheStatement struct {
  151. NodeType
  152. Loc
  153. Unescaped bool
  154. Expression *Expression
  155. // whitespace management
  156. Strip *Strip
  157. }
  158. // NewMustacheStatement instanciates a new mustache node.
  159. func NewMustacheStatement(pos int, line int, unescaped bool) *MustacheStatement {
  160. return &MustacheStatement{
  161. NodeType: NodeMustache,
  162. Loc: Loc{pos, line},
  163. Unescaped: unescaped,
  164. }
  165. }
  166. // String returns a string representation of receiver that can be used for debugging.
  167. func (node *MustacheStatement) String() string {
  168. return fmt.Sprintf("Mustache{Pos: %d}", node.Loc.Pos)
  169. }
  170. // Accept is the receiver entry point for visitors.
  171. func (node *MustacheStatement) Accept(visitor Visitor) interface{} {
  172. return visitor.VisitMustache(node)
  173. }
  174. //
  175. // Block Statement
  176. //
  177. // BlockStatement represents a block node.
  178. type BlockStatement struct {
  179. NodeType
  180. Loc
  181. Expression *Expression
  182. Program *Program
  183. Inverse *Program
  184. // whitespace management
  185. OpenStrip *Strip
  186. InverseStrip *Strip
  187. CloseStrip *Strip
  188. }
  189. // NewBlockStatement instanciates a new block node.
  190. func NewBlockStatement(pos int, line int) *BlockStatement {
  191. return &BlockStatement{
  192. NodeType: NodeBlock,
  193. Loc: Loc{pos, line},
  194. }
  195. }
  196. // String returns a string representation of receiver that can be used for debugging.
  197. func (node *BlockStatement) String() string {
  198. return fmt.Sprintf("Block{Pos: %d}", node.Loc.Pos)
  199. }
  200. // Accept is the receiver entry point for visitors.
  201. func (node *BlockStatement) Accept(visitor Visitor) interface{} {
  202. return visitor.VisitBlock(node)
  203. }
  204. //
  205. // Partial Statement
  206. //
  207. // PartialStatement represents a partial node.
  208. type PartialStatement struct {
  209. NodeType
  210. Loc
  211. Name Node // PathExpression | SubExpression
  212. Params []Node // [ Expression ... ]
  213. Hash *Hash
  214. // whitespace management
  215. Strip *Strip
  216. Indent string
  217. }
  218. // NewPartialStatement instanciates a new partial node.
  219. func NewPartialStatement(pos int, line int) *PartialStatement {
  220. return &PartialStatement{
  221. NodeType: NodePartial,
  222. Loc: Loc{pos, line},
  223. }
  224. }
  225. // String returns a string representation of receiver that can be used for debugging.
  226. func (node *PartialStatement) String() string {
  227. return fmt.Sprintf("Partial{Name:%s, Pos:%d}", node.Name, node.Loc.Pos)
  228. }
  229. // Accept is the receiver entry point for visitors.
  230. func (node *PartialStatement) Accept(visitor Visitor) interface{} {
  231. return visitor.VisitPartial(node)
  232. }
  233. //
  234. // Content Statement
  235. //
  236. // ContentStatement represents a content node.
  237. type ContentStatement struct {
  238. NodeType
  239. Loc
  240. Value string
  241. Original string
  242. // whitespace management
  243. RightStripped bool
  244. LeftStripped bool
  245. }
  246. // NewContentStatement instanciates a new content node.
  247. func NewContentStatement(pos int, line int, val string) *ContentStatement {
  248. return &ContentStatement{
  249. NodeType: NodeContent,
  250. Loc: Loc{pos, line},
  251. Value: val,
  252. Original: val,
  253. }
  254. }
  255. // String returns a string representation of receiver that can be used for debugging.
  256. func (node *ContentStatement) String() string {
  257. return fmt.Sprintf("Content{Value:'%s', Pos:%d}", node.Value, node.Loc.Pos)
  258. }
  259. // Accept is the receiver entry point for visitors.
  260. func (node *ContentStatement) Accept(visitor Visitor) interface{} {
  261. return visitor.VisitContent(node)
  262. }
  263. //
  264. // Comment Statement
  265. //
  266. // CommentStatement represents a comment node.
  267. type CommentStatement struct {
  268. NodeType
  269. Loc
  270. Value string
  271. // whitespace management
  272. Strip *Strip
  273. }
  274. // NewCommentStatement instanciates a new comment node.
  275. func NewCommentStatement(pos int, line int, val string) *CommentStatement {
  276. return &CommentStatement{
  277. NodeType: NodeComment,
  278. Loc: Loc{pos, line},
  279. Value: val,
  280. }
  281. }
  282. // String returns a string representation of receiver that can be used for debugging.
  283. func (node *CommentStatement) String() string {
  284. return fmt.Sprintf("Comment{Value:'%s', Pos:%d}", node.Value, node.Loc.Pos)
  285. }
  286. // Accept is the receiver entry point for visitors.
  287. func (node *CommentStatement) Accept(visitor Visitor) interface{} {
  288. return visitor.VisitComment(node)
  289. }
  290. //
  291. // Expression
  292. //
  293. // Expression represents an expression node.
  294. type Expression struct {
  295. NodeType
  296. Loc
  297. Path Node // PathExpression | StringLiteral | BooleanLiteral | NumberLiteral
  298. Params []Node // [ Expression ... ]
  299. Hash *Hash
  300. }
  301. // NewExpression instanciates a new expression node.
  302. func NewExpression(pos int, line int) *Expression {
  303. return &Expression{
  304. NodeType: NodeExpression,
  305. Loc: Loc{pos, line},
  306. }
  307. }
  308. // String returns a string representation of receiver that can be used for debugging.
  309. func (node *Expression) String() string {
  310. return fmt.Sprintf("Expr{Path:%s, Pos:%d}", node.Path, node.Loc.Pos)
  311. }
  312. // Accept is the receiver entry point for visitors.
  313. func (node *Expression) Accept(visitor Visitor) interface{} {
  314. return visitor.VisitExpression(node)
  315. }
  316. // HelperName returns helper name, or an empty string if this expression can't be a helper.
  317. func (node *Expression) HelperName() string {
  318. path, ok := node.Path.(*PathExpression)
  319. if !ok {
  320. return ""
  321. }
  322. if path.Data || (len(path.Parts) != 1) || (path.Depth > 0) || path.Scoped {
  323. return ""
  324. }
  325. return path.Parts[0]
  326. }
  327. // FieldPath returns path expression representing a field path, or nil if this is not a field path.
  328. func (node *Expression) FieldPath() *PathExpression {
  329. path, ok := node.Path.(*PathExpression)
  330. if !ok {
  331. return nil
  332. }
  333. return path
  334. }
  335. // LiteralStr returns the string representation of literal value, with a boolean set to false if this is not a literal.
  336. func (node *Expression) LiteralStr() (string, bool) {
  337. return LiteralStr(node.Path)
  338. }
  339. // Canonical returns the canonical form of expression node as a string.
  340. func (node *Expression) Canonical() string {
  341. if str, ok := HelperNameStr(node.Path); ok {
  342. return str
  343. }
  344. return ""
  345. }
  346. // HelperNameStr returns the string representation of a helper name, with a boolean set to false if this is not a valid helper name.
  347. //
  348. // helperName : path | dataName | STRING | NUMBER | BOOLEAN | UNDEFINED | NULL
  349. func HelperNameStr(node Node) (string, bool) {
  350. // PathExpression
  351. if str, ok := PathExpressionStr(node); ok {
  352. return str, ok
  353. }
  354. // Literal
  355. if str, ok := LiteralStr(node); ok {
  356. return str, ok
  357. }
  358. return "", false
  359. }
  360. // PathExpressionStr returns the string representation of path expression value, with a boolean set to false if this is not a path expression.
  361. func PathExpressionStr(node Node) (string, bool) {
  362. if path, ok := node.(*PathExpression); ok {
  363. result := path.Original
  364. // "[foo bar]"" => "foo bar"
  365. if (len(result) >= 2) && (result[0] == '[') && (result[len(result)-1] == ']') {
  366. result = result[1 : len(result)-1]
  367. }
  368. return result, true
  369. }
  370. return "", false
  371. }
  372. // LiteralStr returns the string representation of literal value, with a boolean set to false if this is not a literal.
  373. func LiteralStr(node Node) (string, bool) {
  374. if lit, ok := node.(*StringLiteral); ok {
  375. return lit.Value, true
  376. }
  377. if lit, ok := node.(*BooleanLiteral); ok {
  378. return lit.Canonical(), true
  379. }
  380. if lit, ok := node.(*NumberLiteral); ok {
  381. return lit.Canonical(), true
  382. }
  383. return "", false
  384. }
  385. //
  386. // SubExpression
  387. //
  388. // SubExpression represents a subexpression node.
  389. type SubExpression struct {
  390. NodeType
  391. Loc
  392. Expression *Expression
  393. }
  394. // NewSubExpression instanciates a new subexpression node.
  395. func NewSubExpression(pos int, line int) *SubExpression {
  396. return &SubExpression{
  397. NodeType: NodeSubExpression,
  398. Loc: Loc{pos, line},
  399. }
  400. }
  401. // String returns a string representation of receiver that can be used for debugging.
  402. func (node *SubExpression) String() string {
  403. return fmt.Sprintf("Sexp{Path:%s, Pos:%d}", node.Expression.Path, node.Loc.Pos)
  404. }
  405. // Accept is the receiver entry point for visitors.
  406. func (node *SubExpression) Accept(visitor Visitor) interface{} {
  407. return visitor.VisitSubExpression(node)
  408. }
  409. //
  410. // Path Expression
  411. //
  412. // PathExpression represents a path expression node.
  413. type PathExpression struct {
  414. NodeType
  415. Loc
  416. Original string
  417. Depth int
  418. Parts []string
  419. Data bool
  420. Scoped bool
  421. }
  422. // NewPathExpression instanciates a new path expression node.
  423. func NewPathExpression(pos int, line int, data bool) *PathExpression {
  424. result := &PathExpression{
  425. NodeType: NodePath,
  426. Loc: Loc{pos, line},
  427. Data: data,
  428. }
  429. if data {
  430. result.Original = "@"
  431. }
  432. return result
  433. }
  434. // String returns a string representation of receiver that can be used for debugging.
  435. func (node *PathExpression) String() string {
  436. return fmt.Sprintf("Path{Original:'%s', Pos:%d}", node.Original, node.Loc.Pos)
  437. }
  438. // Accept is the receiver entry point for visitors.
  439. func (node *PathExpression) Accept(visitor Visitor) interface{} {
  440. return visitor.VisitPath(node)
  441. }
  442. // Part adds path part.
  443. func (node *PathExpression) Part(part string) {
  444. node.Original += part
  445. switch part {
  446. case "..":
  447. node.Depth++
  448. node.Scoped = true
  449. case ".", "this":
  450. node.Scoped = true
  451. default:
  452. node.Parts = append(node.Parts, part)
  453. }
  454. }
  455. // Sep adds path separator.
  456. func (node *PathExpression) Sep(separator string) {
  457. node.Original += separator
  458. }
  459. // IsDataRoot returns true if path expression is @root.
  460. func (node *PathExpression) IsDataRoot() bool {
  461. return node.Data && (node.Parts[0] == "root")
  462. }
  463. //
  464. // String Literal
  465. //
  466. // StringLiteral represents a string node.
  467. type StringLiteral struct {
  468. NodeType
  469. Loc
  470. Value string
  471. }
  472. // NewStringLiteral instanciates a new string node.
  473. func NewStringLiteral(pos int, line int, val string) *StringLiteral {
  474. return &StringLiteral{
  475. NodeType: NodeString,
  476. Loc: Loc{pos, line},
  477. Value: val,
  478. }
  479. }
  480. // String returns a string representation of receiver that can be used for debugging.
  481. func (node *StringLiteral) String() string {
  482. return fmt.Sprintf("String{Value:'%s', Pos:%d}", node.Value, node.Loc.Pos)
  483. }
  484. // Accept is the receiver entry point for visitors.
  485. func (node *StringLiteral) Accept(visitor Visitor) interface{} {
  486. return visitor.VisitString(node)
  487. }
  488. //
  489. // Boolean Literal
  490. //
  491. // BooleanLiteral represents a boolean node.
  492. type BooleanLiteral struct {
  493. NodeType
  494. Loc
  495. Value bool
  496. Original string
  497. }
  498. // NewBooleanLiteral instanciates a new boolean node.
  499. func NewBooleanLiteral(pos int, line int, val bool, original string) *BooleanLiteral {
  500. return &BooleanLiteral{
  501. NodeType: NodeBoolean,
  502. Loc: Loc{pos, line},
  503. Value: val,
  504. Original: original,
  505. }
  506. }
  507. // String returns a string representation of receiver that can be used for debugging.
  508. func (node *BooleanLiteral) String() string {
  509. return fmt.Sprintf("Boolean{Value:%s, Pos:%d}", node.Canonical(), node.Loc.Pos)
  510. }
  511. // Accept is the receiver entry point for visitors.
  512. func (node *BooleanLiteral) Accept(visitor Visitor) interface{} {
  513. return visitor.VisitBoolean(node)
  514. }
  515. // Canonical returns the canonical form of boolean node as a string (ie. "true" | "false").
  516. func (node *BooleanLiteral) Canonical() string {
  517. if node.Value {
  518. return "true"
  519. }
  520. return "false"
  521. }
  522. //
  523. // Number Literal
  524. //
  525. // NumberLiteral represents a number node.
  526. type NumberLiteral struct {
  527. NodeType
  528. Loc
  529. Value float64
  530. IsInt bool
  531. Original string
  532. }
  533. // NewNumberLiteral instanciates a new number node.
  534. func NewNumberLiteral(pos int, line int, val float64, isInt bool, original string) *NumberLiteral {
  535. return &NumberLiteral{
  536. NodeType: NodeNumber,
  537. Loc: Loc{pos, line},
  538. Value: val,
  539. IsInt: isInt,
  540. Original: original,
  541. }
  542. }
  543. // String returns a string representation of receiver that can be used for debugging.
  544. func (node *NumberLiteral) String() string {
  545. return fmt.Sprintf("Number{Value:%s, Pos:%d}", node.Canonical(), node.Loc.Pos)
  546. }
  547. // Accept is the receiver entry point for visitors.
  548. func (node *NumberLiteral) Accept(visitor Visitor) interface{} {
  549. return visitor.VisitNumber(node)
  550. }
  551. // Canonical returns the canonical form of number node as a string (eg: "12", "-1.51").
  552. func (node *NumberLiteral) Canonical() string {
  553. prec := -1
  554. if node.IsInt {
  555. prec = 0
  556. }
  557. return strconv.FormatFloat(node.Value, 'f', prec, 64)
  558. }
  559. // Number returns an integer or a float.
  560. func (node *NumberLiteral) Number() interface{} {
  561. if node.IsInt {
  562. return int(node.Value)
  563. }
  564. return node.Value
  565. }
  566. //
  567. // Hash
  568. //
  569. // Hash represents a hash node.
  570. type Hash struct {
  571. NodeType
  572. Loc
  573. Pairs []*HashPair
  574. }
  575. // NewHash instanciates a new hash node.
  576. func NewHash(pos int, line int) *Hash {
  577. return &Hash{
  578. NodeType: NodeHash,
  579. Loc: Loc{pos, line},
  580. }
  581. }
  582. // String returns a string representation of receiver that can be used for debugging.
  583. func (node *Hash) String() string {
  584. result := fmt.Sprintf("Hash{[%d", node.Loc.Pos)
  585. for i, p := range node.Pairs {
  586. if i > 0 {
  587. result += ", "
  588. }
  589. result += p.String()
  590. }
  591. return result + fmt.Sprintf("], Pos:%d}", node.Loc.Pos)
  592. }
  593. // Accept is the receiver entry point for visitors.
  594. func (node *Hash) Accept(visitor Visitor) interface{} {
  595. return visitor.VisitHash(node)
  596. }
  597. //
  598. // HashPair
  599. //
  600. // HashPair represents a hash pair node.
  601. type HashPair struct {
  602. NodeType
  603. Loc
  604. Key string
  605. Val Node // Expression
  606. }
  607. // NewHashPair instanciates a new hash pair node.
  608. func NewHashPair(pos int, line int) *HashPair {
  609. return &HashPair{
  610. NodeType: NodeHashPair,
  611. Loc: Loc{pos, line},
  612. }
  613. }
  614. // String returns a string representation of receiver that can be used for debugging.
  615. func (node *HashPair) String() string {
  616. return node.Key + "=" + node.Val.String()
  617. }
  618. // Accept is the receiver entry point for visitors.
  619. func (node *HashPair) Accept(visitor Visitor) interface{} {
  620. return visitor.VisitHashPair(node)
  621. }