parser.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. /*
  2. * ECAL
  3. *
  4. * Copyright 2020 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. package parser
  11. import (
  12. "fmt"
  13. )
  14. /*
  15. Map of AST nodes corresponding to lexer tokens. The map determines how a given
  16. sequence of lexer tokens are organized into an AST.
  17. */
  18. var astNodeMap map[LexTokenID]*ASTNode
  19. func init() {
  20. astNodeMap = map[LexTokenID]*ASTNode{
  21. TokenEOF: {NodeEOF, nil, nil, nil, nil, 0, ndTerm, nil},
  22. // Value tokens
  23. TokenSTRING: {NodeSTRING, nil, nil, nil, nil, 0, ndTerm, nil},
  24. TokenNUMBER: {NodeNUMBER, nil, nil, nil, nil, 0, ndTerm, nil},
  25. TokenIDENTIFIER: {NodeIDENTIFIER, nil, nil, nil, nil, 0, ndIdentifier, nil},
  26. // Constructed tokens
  27. TokenSTATEMENTS: {NodeSTATEMENTS, nil, nil, nil, nil, 0, nil, nil},
  28. TokenFUNCCALL: {NodeFUNCCALL, nil, nil, nil, nil, 0, nil, nil},
  29. TokenCOMPACCESS: {NodeCOMPACCESS, nil, nil, nil, nil, 0, nil, nil},
  30. TokenLIST: {NodeLIST, nil, nil, nil, nil, 0, nil, nil},
  31. TokenMAP: {NodeMAP, nil, nil, nil, nil, 0, nil, nil},
  32. TokenPARAMS: {NodePARAMS, nil, nil, nil, nil, 0, nil, nil},
  33. TokenGUARD: {NodeGUARD, nil, nil, nil, nil, 0, nil, nil},
  34. // Condition operators
  35. TokenGEQ: {NodeGEQ, nil, nil, nil, nil, 60, nil, ldInfix},
  36. TokenLEQ: {NodeLEQ, nil, nil, nil, nil, 60, nil, ldInfix},
  37. TokenNEQ: {NodeNEQ, nil, nil, nil, nil, 60, nil, ldInfix},
  38. TokenEQ: {NodeEQ, nil, nil, nil, nil, 60, nil, ldInfix},
  39. TokenGT: {NodeGT, nil, nil, nil, nil, 60, nil, ldInfix},
  40. TokenLT: {NodeLT, nil, nil, nil, nil, 60, nil, ldInfix},
  41. // Grouping symbols
  42. TokenLPAREN: {"", nil, nil, nil, nil, 150, ndInner, nil},
  43. TokenRPAREN: {"", nil, nil, nil, nil, 0, nil, nil},
  44. TokenLBRACK: {"", nil, nil, nil, nil, 150, ndList, nil},
  45. TokenRBRACK: {"", nil, nil, nil, nil, 0, nil, nil},
  46. TokenLBRACE: {"", nil, nil, nil, nil, 150, ndMap, nil},
  47. TokenRBRACE: {"", nil, nil, nil, nil, 0, nil, nil},
  48. // Separators
  49. TokenDOT: {"", nil, nil, nil, nil, 0, nil, nil},
  50. TokenCOMMA: {"", nil, nil, nil, nil, 0, nil, nil},
  51. TokenSEMICOLON: {"", nil, nil, nil, nil, 0, nil, nil},
  52. // Grouping
  53. TokenCOLON: {NodeKVP, nil, nil, nil, nil, 60, nil, ldInfix},
  54. TokenEQUAL: {NodePRESET, nil, nil, nil, nil, 60, nil, ldInfix},
  55. // Arithmetic operators
  56. TokenPLUS: {NodePLUS, nil, nil, nil, nil, 110, ndPrefix, ldInfix},
  57. TokenMINUS: {NodeMINUS, nil, nil, nil, nil, 110, ndPrefix, ldInfix},
  58. TokenTIMES: {NodeTIMES, nil, nil, nil, nil, 120, nil, ldInfix},
  59. TokenDIV: {NodeDIV, nil, nil, nil, nil, 120, nil, ldInfix},
  60. TokenDIVINT: {NodeDIVINT, nil, nil, nil, nil, 120, nil, ldInfix},
  61. TokenMODINT: {NodeMODINT, nil, nil, nil, nil, 120, nil, ldInfix},
  62. // Assignment statement
  63. TokenASSIGN: {NodeASSIGN, nil, nil, nil, nil, 10, nil, ldInfix},
  64. // Import statement
  65. TokenIMPORT: {NodeIMPORT, nil, nil, nil, nil, 0, ndImport, nil},
  66. TokenAS: {"", nil, nil, nil, nil, 0, ndImport, nil},
  67. // Sink definition
  68. TokenSINK: {NodeSINK, nil, nil, nil, nil, 0, ndSkink, nil},
  69. TokenKINDMATCH: {NodeKINDMATCH, nil, nil, nil, nil, 150, ndPrefix, nil},
  70. TokenSCOPEMATCH: {NodeSCOPEMATCH, nil, nil, nil, nil, 150, ndPrefix, nil},
  71. TokenSTATEMATCH: {NodeSTATEMATCH, nil, nil, nil, nil, 150, ndPrefix, nil},
  72. TokenPRIORITY: {NodePRIORITY, nil, nil, nil, nil, 150, ndPrefix, nil},
  73. TokenSUPPRESSES: {NodeSUPPRESSES, nil, nil, nil, nil, 150, ndPrefix, nil},
  74. // Function definition
  75. TokenFUNC: {NodeFUNC, nil, nil, nil, nil, 0, ndFunc, nil},
  76. TokenRETURN: {NodeRETURN, nil, nil, nil, nil, 0, ndReturn, nil},
  77. // Boolean operators
  78. TokenAND: {NodeAND, nil, nil, nil, nil, 40, nil, ldInfix},
  79. TokenOR: {NodeOR, nil, nil, nil, nil, 30, nil, ldInfix},
  80. TokenNOT: {NodeNOT, nil, nil, nil, nil, 20, ndPrefix, nil},
  81. // Condition operators
  82. TokenLIKE: {NodeLIKE, nil, nil, nil, nil, 60, nil, ldInfix},
  83. TokenIN: {NodeIN, nil, nil, nil, nil, 60, nil, ldInfix},
  84. TokenHASPREFIX: {NodeHASPREFIX, nil, nil, nil, nil, 60, nil, ldInfix},
  85. TokenHASSUFFIX: {NodeHASSUFFIX, nil, nil, nil, nil, 60, nil, ldInfix},
  86. TokenNOTIN: {NodeNOTIN, nil, nil, nil, nil, 60, nil, ldInfix},
  87. // Constant terminals
  88. TokenFALSE: {NodeFALSE, nil, nil, nil, nil, 0, ndTerm, nil},
  89. TokenTRUE: {NodeTRUE, nil, nil, nil, nil, 0, ndTerm, nil},
  90. TokenNULL: {NodeNULL, nil, nil, nil, nil, 0, ndTerm, nil},
  91. // Conditional statements
  92. TokenIF: {NodeIF, nil, nil, nil, nil, 0, ndGuard, nil},
  93. TokenELIF: {"", nil, nil, nil, nil, 0, nil, nil},
  94. TokenELSE: {"", nil, nil, nil, nil, 0, nil, nil},
  95. // Loop statements
  96. TokenFOR: {NodeLOOP, nil, nil, nil, nil, 0, ndLoop, nil},
  97. TokenBREAK: {NodeBREAK, nil, nil, nil, nil, 0, ndTerm, nil},
  98. TokenCONTINUE: {NodeCONTINUE, nil, nil, nil, nil, 0, ndTerm, nil},
  99. }
  100. }
  101. // Parser
  102. // ======
  103. /*
  104. Parser data structure
  105. */
  106. type parser struct {
  107. name string // Name to identify the input
  108. node *ASTNode // Current ast node
  109. tokens *LABuffer // Buffer which is connected to the channel which contains lex tokens
  110. rp RuntimeProvider // Runtime provider which creates runtime components
  111. }
  112. /*
  113. Parse parses a given input string and returns an AST.
  114. */
  115. func Parse(name string, input string) (*ASTNode, error) {
  116. return ParseWithRuntime(name, input, nil)
  117. }
  118. /*
  119. ParseWithRuntime parses a given input string and returns an AST decorated with
  120. runtime components.
  121. */
  122. func ParseWithRuntime(name string, input string, rp RuntimeProvider) (*ASTNode, error) {
  123. // Create a new parser with a look-ahead buffer of 3
  124. p := &parser{name, nil, NewLABuffer(Lex(name, input), 3), rp}
  125. // Read and set initial AST node
  126. node, err := p.next()
  127. if err != nil {
  128. return nil, err
  129. }
  130. p.node = node
  131. n, err := p.run(0)
  132. if err == nil && hasMoreStatements(p, n) {
  133. st := astNodeMap[TokenSTATEMENTS].instance(p, nil)
  134. st.Children = append(st.Children, n)
  135. for err == nil && hasMoreStatements(p, n) {
  136. // Skip semicolons
  137. if p.node.Token.ID == TokenSEMICOLON {
  138. skipToken(p, TokenSEMICOLON)
  139. }
  140. n, err = p.run(0)
  141. st.Children = append(st.Children, n)
  142. }
  143. n = st
  144. }
  145. if err == nil && p.node != nil && p.node.Token.ID != TokenEOF {
  146. token := *p.node.Token
  147. err = p.newParserError(ErrUnexpectedEnd, fmt.Sprintf("extra token id:%v (%v)",
  148. token.ID, token), token)
  149. }
  150. return n, err
  151. }
  152. /*
  153. run models the main parser function.
  154. */
  155. func (p *parser) run(rightBinding int) (*ASTNode, error) {
  156. var err error
  157. n := p.node
  158. p.node, err = p.next()
  159. if err != nil {
  160. return nil, err
  161. }
  162. // Start with the null denotation of this statement / expression
  163. if n.nullDenotation == nil {
  164. return nil, p.newParserError(ErrImpossibleNullDenotation,
  165. n.Token.String(), *n.Token)
  166. }
  167. left, err := n.nullDenotation(p, n)
  168. if err != nil {
  169. return nil, err
  170. }
  171. // Collect left denotations as long as the left binding power is greater
  172. // than the initial right one
  173. for rightBinding < p.node.binding {
  174. var nleft *ASTNode
  175. n = p.node
  176. if n.leftDenotation == nil {
  177. if left.Token.Lline < n.Token.Lline {
  178. // If the impossible left denotation is on a new line
  179. // we might be parsing a new statement
  180. return left, nil
  181. }
  182. return nil, p.newParserError(ErrImpossibleLeftDenotation,
  183. n.Token.String(), *n.Token)
  184. }
  185. p.node, err = p.next()
  186. if err != nil {
  187. return nil, err
  188. }
  189. // Get the next left denotation
  190. nleft, err = n.leftDenotation(p, n, left)
  191. left = nleft
  192. if err != nil {
  193. return nil, err
  194. }
  195. }
  196. return left, nil
  197. }
  198. /*
  199. next retrieves the next lexer token.
  200. */
  201. func (p *parser) next() (*ASTNode, error) {
  202. var preComments []MetaData
  203. var postComments []MetaData
  204. token, more := p.tokens.Next()
  205. // Skip over pre comment token
  206. for more && token.ID == TokenPRECOMMENT {
  207. preComments = append(preComments, NewLexTokenInstance(token))
  208. token, more = p.tokens.Next()
  209. }
  210. // Skip over post comment token
  211. for more && token.ID == TokenPOSTCOMMENT {
  212. postComments = append(postComments, NewLexTokenInstance(token))
  213. token, more = p.tokens.Next()
  214. }
  215. if !more {
  216. // Unexpected end of input - the associated token is an empty error token
  217. return nil, p.newParserError(ErrUnexpectedEnd, "", token)
  218. } else if token.ID == TokenError {
  219. // There was a lexer error wrap it in a parser error
  220. return nil, p.newParserError(ErrLexicalError, token.Val, token)
  221. } else if node, ok := astNodeMap[token.ID]; ok {
  222. // We got a normal AST component
  223. ret := node.instance(p, &token)
  224. ret.Meta = append(ret.Meta, preComments...) // Attach pre comments to the next AST node
  225. if len(postComments) > 0 && p.node != nil {
  226. p.node.Meta = append(p.node.Meta, postComments...) // Attach post comments to the previous AST node
  227. }
  228. return ret, nil
  229. }
  230. return nil, p.newParserError(ErrUnknownToken, fmt.Sprintf("id:%v (%v)", token.ID, token), token)
  231. }
  232. // Standard null denotation functions
  233. // ==================================
  234. /*
  235. ndTerm is used for terminals.
  236. */
  237. func ndTerm(p *parser, self *ASTNode) (*ASTNode, error) {
  238. return self, nil
  239. }
  240. /*
  241. ndInner returns the inner expression of an enclosed block and discard the
  242. block token. This method is used for brackets.
  243. */
  244. func ndInner(p *parser, self *ASTNode) (*ASTNode, error) {
  245. // Get the inner expression
  246. exp, err := p.run(0)
  247. if err != nil {
  248. return nil, err
  249. }
  250. // We return here the inner expression - discarding the bracket tokens
  251. return exp, skipToken(p, TokenRPAREN)
  252. }
  253. /*
  254. ndPrefix is used for prefix operators.
  255. */
  256. func ndPrefix(p *parser, self *ASTNode) (*ASTNode, error) {
  257. // Make sure a prefix will only prefix the next item
  258. val, err := p.run(self.binding + 20)
  259. if err != nil {
  260. return nil, err
  261. }
  262. self.Children = append(self.Children, val)
  263. return self, nil
  264. }
  265. // Null denotation functions for specific expressions
  266. // ==================================================
  267. /*
  268. ndImport is used to parse imports.
  269. */
  270. func ndImport(p *parser, self *ASTNode) (*ASTNode, error) {
  271. // Must specify a file path
  272. err := acceptChild(p, self, TokenSTRING)
  273. if err == nil {
  274. // Must specify AS
  275. if err = skipToken(p, TokenAS); err == nil {
  276. // Must specify an identifier
  277. err = acceptChild(p, self, TokenIDENTIFIER)
  278. }
  279. }
  280. return self, err
  281. }
  282. /*
  283. ndSink is used to parse sinks.
  284. */
  285. func ndSkink(p *parser, self *ASTNode) (*ASTNode, error) {
  286. var exp, ret *ASTNode
  287. // Must specify a name
  288. err := acceptChild(p, self, TokenIDENTIFIER)
  289. if err == nil {
  290. // Parse the rest of the parameters as children until we reach the body
  291. for err == nil && IsNotEndAndNotToken(p, TokenLBRACE) {
  292. if exp, err = p.run(150); err == nil {
  293. self.Children = append(self.Children, exp)
  294. // Skip commas
  295. if p.node.Token.ID == TokenCOMMA {
  296. err = skipToken(p, TokenCOMMA)
  297. }
  298. }
  299. }
  300. if err == nil {
  301. // Parse the body
  302. ret, err = parseInnerStatements(p, self)
  303. }
  304. }
  305. return ret, err
  306. }
  307. /*
  308. ndFunc is used to parse function definitions.
  309. */
  310. func ndFunc(p *parser, self *ASTNode) (*ASTNode, error) {
  311. var exp *ASTNode
  312. var err error
  313. // Might specify a function name
  314. if p.node.Token.ID == TokenIDENTIFIER {
  315. err = acceptChild(p, self, TokenIDENTIFIER)
  316. }
  317. // Read in parameters
  318. if err == nil {
  319. err = skipToken(p, TokenLPAREN)
  320. params := astNodeMap[TokenPARAMS].instance(p, nil)
  321. self.Children = append(self.Children, params)
  322. for err == nil && IsNotEndAndNotToken(p, TokenRPAREN) {
  323. // Parse all the expressions inside
  324. if exp, err = p.run(0); err == nil {
  325. params.Children = append(params.Children, exp)
  326. if p.node.Token.ID == TokenCOMMA {
  327. err = skipToken(p, TokenCOMMA)
  328. }
  329. }
  330. }
  331. if err == nil {
  332. err = skipToken(p, TokenRPAREN)
  333. }
  334. }
  335. if err == nil {
  336. // Parse the body
  337. self, err = parseInnerStatements(p, self)
  338. }
  339. return self, err
  340. }
  341. /*
  342. ndReturn is used to parse return statements.
  343. */
  344. func ndReturn(p *parser, self *ASTNode) (*ASTNode, error) {
  345. var err error
  346. if self.Token.Lline == p.node.Token.Lline {
  347. var val *ASTNode
  348. // Consume the next expression only if it is on the same line
  349. val, err = p.run(0)
  350. if err == nil {
  351. self.Children = append(self.Children, val)
  352. }
  353. }
  354. return self, err
  355. }
  356. /*
  357. ndIdentifier is to parse identifiers and function calls.
  358. */
  359. func ndIdentifier(p *parser, self *ASTNode) (*ASTNode, error) {
  360. var parseMore, parseSegment, parseFuncCall, parseCompositionAccess func(parent *ASTNode) error
  361. parseMore = func(current *ASTNode) error {
  362. var err error
  363. if p.node.Token.ID == TokenDOT {
  364. err = parseSegment(current)
  365. } else if p.node.Token.ID == TokenLPAREN {
  366. err = parseFuncCall(current)
  367. } else if p.node.Token.ID == TokenLBRACK && p.node.Token.Lline == self.Token.Lline {
  368. // Composition access needs to be on the same line as the identifier
  369. // as we might otherwise have a list
  370. err = parseCompositionAccess(current)
  371. }
  372. return err
  373. }
  374. parseSegment = func(current *ASTNode) error {
  375. var err error
  376. var next *ASTNode
  377. if err = skipToken(p, TokenDOT); err == nil {
  378. next = p.node
  379. if err = acceptChild(p, current, TokenIDENTIFIER); err == nil {
  380. err = parseMore(next)
  381. }
  382. }
  383. return err
  384. }
  385. parseFuncCall = func(current *ASTNode) error {
  386. var exp *ASTNode
  387. err := skipToken(p, TokenLPAREN)
  388. fc := astNodeMap[TokenFUNCCALL].instance(p, nil)
  389. current.Children = append(current.Children, fc)
  390. // Read in parameters
  391. for err == nil && IsNotEndAndNotToken(p, TokenRPAREN) {
  392. // Parse all the expressions inside the directives
  393. if exp, err = p.run(0); err == nil {
  394. fc.Children = append(fc.Children, exp)
  395. if p.node.Token.ID == TokenCOMMA {
  396. err = skipToken(p, TokenCOMMA)
  397. }
  398. }
  399. }
  400. if err == nil {
  401. err = skipToken(p, TokenRPAREN)
  402. if err == nil {
  403. err = parseMore(current)
  404. }
  405. }
  406. return err
  407. }
  408. parseCompositionAccess = func(current *ASTNode) error {
  409. var exp *ASTNode
  410. err := skipToken(p, TokenLBRACK)
  411. if err == nil {
  412. ca := astNodeMap[TokenCOMPACCESS].instance(p, nil)
  413. current.Children = append(current.Children, ca)
  414. // Parse all the expressions inside the directives
  415. if exp, err = p.run(0); err == nil {
  416. ca.Children = append(ca.Children, exp)
  417. if err = skipToken(p, TokenRBRACK); err == nil {
  418. err = parseMore(current)
  419. }
  420. }
  421. }
  422. return err
  423. }
  424. return self, parseMore(self)
  425. }
  426. /*
  427. ndList is used to collect elements of a list.
  428. */
  429. func ndList(p *parser, self *ASTNode) (*ASTNode, error) {
  430. var err error
  431. var exp *ASTNode
  432. // Create a list token
  433. st := astNodeMap[TokenLIST].instance(p, self.Token)
  434. // Get the inner expression
  435. for err == nil && IsNotEndAndNotToken(p, TokenRBRACK) {
  436. // Parse all the expressions inside
  437. if exp, err = p.run(0); err == nil {
  438. st.Children = append(st.Children, exp)
  439. if p.node.Token.ID == TokenCOMMA {
  440. err = skipToken(p, TokenCOMMA)
  441. }
  442. }
  443. }
  444. if err == nil {
  445. err = skipToken(p, TokenRBRACK)
  446. }
  447. // Must have a closing bracket
  448. return st, err
  449. }
  450. /*
  451. ndMap is used to collect elements of a map.
  452. */
  453. func ndMap(p *parser, self *ASTNode) (*ASTNode, error) {
  454. var err error
  455. var exp *ASTNode
  456. // Create a map token
  457. st := astNodeMap[TokenMAP].instance(p, self.Token)
  458. // Get the inner expression
  459. for err == nil && IsNotEndAndNotToken(p, TokenRBRACE) {
  460. // Parse all the expressions inside
  461. if exp, err = p.run(0); err == nil {
  462. st.Children = append(st.Children, exp)
  463. if p.node.Token.ID == TokenCOMMA {
  464. err = skipToken(p, TokenCOMMA)
  465. }
  466. }
  467. }
  468. if err == nil {
  469. err = skipToken(p, TokenRBRACE)
  470. }
  471. // Must have a closing brace
  472. return st, err
  473. }
  474. /*
  475. ndGuard is used to parse a conditional statement.
  476. */
  477. func ndGuard(p *parser, self *ASTNode) (*ASTNode, error) {
  478. var err error
  479. parseGuardAndStatements := func() error {
  480. // The brace starts statements while parsing the expression of an if statement
  481. nodeMapEntryBak := astNodeMap[TokenLBRACE]
  482. astNodeMap[TokenLBRACE] = &ASTNode{"", nil, nil, nil, nil, 0, parseInnerStatements, nil}
  483. exp, err := p.run(0)
  484. astNodeMap[TokenLBRACE] = nodeMapEntryBak
  485. if err == nil {
  486. g := astNodeMap[TokenGUARD].instance(p, nil)
  487. g.Children = append(g.Children, exp)
  488. self.Children = append(self.Children, g)
  489. _, err = parseInnerStatements(p, self)
  490. }
  491. return err
  492. }
  493. if err = parseGuardAndStatements(); err == nil {
  494. for err == nil && IsNotEndAndToken(p, TokenELIF) {
  495. // Parse an elif
  496. if err = skipToken(p, TokenELIF); err == nil {
  497. err = parseGuardAndStatements()
  498. }
  499. }
  500. if err == nil && p.node.Token.ID == TokenELSE {
  501. // Parse else
  502. if err = skipToken(p, TokenELSE); err == nil {
  503. g := astNodeMap[TokenGUARD].instance(p, nil)
  504. g.Children = append(g.Children, astNodeMap[TokenTRUE].instance(p, nil))
  505. self.Children = append(self.Children, g)
  506. _, err = parseInnerStatements(p, self)
  507. }
  508. }
  509. }
  510. return self, err
  511. }
  512. /*
  513. ndLoop is used to parse a loop statement.
  514. */
  515. func ndLoop(p *parser, self *ASTNode) (*ASTNode, error) {
  516. // The brace starts statements while parsing the expression of a for statement
  517. nodeMapEntryBak := astNodeMap[TokenLBRACE]
  518. astNodeMap[TokenLBRACE] = &ASTNode{"", nil, nil, nil, nil, 0, parseInnerStatements, nil}
  519. exp, err := p.run(0)
  520. astNodeMap[TokenLBRACE] = nodeMapEntryBak
  521. if err == nil {
  522. g := exp
  523. if exp.Token.ID != TokenIN {
  524. g = astNodeMap[TokenGUARD].instance(p, nil)
  525. g.Children = append(g.Children, exp)
  526. }
  527. self.Children = append(self.Children, g)
  528. _, err = parseInnerStatements(p, self)
  529. }
  530. return self, err
  531. }
  532. // Standard left denotation functions
  533. // ==================================
  534. /*
  535. ldInfix is used for infix operators.
  536. */
  537. func ldInfix(p *parser, self *ASTNode, left *ASTNode) (*ASTNode, error) {
  538. right, err := p.run(self.binding)
  539. if err != nil {
  540. return nil, err
  541. }
  542. self.Children = append(self.Children, left)
  543. self.Children = append(self.Children, right)
  544. return self, nil
  545. }
  546. // Helper functions
  547. // ================
  548. /*
  549. IsNotEndAndToken checks if the next token is of a specific type or the end has been reached.
  550. */
  551. func IsNotEndAndToken(p *parser, i LexTokenID) bool {
  552. return p.node != nil && p.node.Name != NodeEOF && p.node.Token.ID == i
  553. }
  554. /*
  555. IsNotEndAndNotToken checks if the next token is not of a specific type or the end has been reached.
  556. */
  557. func IsNotEndAndNotToken(p *parser, i LexTokenID) bool {
  558. return p.node != nil && p.node.Name != NodeEOF && p.node.Token.ID != i
  559. }
  560. /*
  561. hasMoreStatements returns true if there are more statements to parse.
  562. */
  563. func hasMoreStatements(p *parser, currentNode *ASTNode) bool {
  564. nextNode := p.node
  565. if nextNode == nil || nextNode.Token.ID == TokenEOF {
  566. return false
  567. } else if nextNode.Token.ID == TokenSEMICOLON {
  568. return true
  569. }
  570. return currentNode != nil && currentNode.Token.Lline < nextNode.Token.Lline
  571. }
  572. /*
  573. skipToken skips over a given token.
  574. */
  575. func skipToken(p *parser, ids ...LexTokenID) error {
  576. var err error
  577. canSkip := func(id LexTokenID) bool {
  578. for _, i := range ids {
  579. if i == id {
  580. return true
  581. }
  582. }
  583. return false
  584. }
  585. if !canSkip(p.node.Token.ID) {
  586. if p.node.Token.ID == TokenEOF {
  587. return p.newParserError(ErrUnexpectedEnd, "", *p.node.Token)
  588. }
  589. return p.newParserError(ErrUnexpectedToken, p.node.Token.Val, *p.node.Token)
  590. }
  591. // This should never return an error unless we skip over EOF or complex tokens
  592. // like values
  593. p.node, err = p.next()
  594. return err
  595. }
  596. /*
  597. acceptChild accepts the current token as a child.
  598. */
  599. func acceptChild(p *parser, self *ASTNode, id LexTokenID) error {
  600. var err error
  601. current := p.node
  602. if p.node, err = p.next(); err == nil {
  603. if current.Token.ID == id {
  604. self.Children = append(self.Children, current)
  605. } else {
  606. err = p.newParserError(ErrUnexpectedToken, current.Token.Val, *current.Token)
  607. }
  608. }
  609. return err
  610. }
  611. /*
  612. parseInnerStatements collects the inner statements of a block statement. It
  613. is assumed that a block statement starts with a left brace '{' and ends with
  614. a right brace '}'.
  615. */
  616. func parseInnerStatements(p *parser, self *ASTNode) (*ASTNode, error) {
  617. // Must start with an opening brace
  618. if err := skipToken(p, TokenLBRACE); err != nil {
  619. return nil, err
  620. }
  621. // Always create a statements node
  622. st := astNodeMap[TokenSTATEMENTS].instance(p, nil)
  623. self.Children = append(self.Children, st)
  624. // Check if there are actually children
  625. if p.node != nil && p.node.Token.ID != TokenRBRACE {
  626. n, err := p.run(0)
  627. if p.node != nil && p.node.Token.ID != TokenEOF {
  628. st.Children = append(st.Children, n)
  629. for hasMoreStatements(p, n) {
  630. if p.node.Token.ID == TokenSEMICOLON {
  631. skipToken(p, TokenSEMICOLON)
  632. } else if p.node.Token.ID == TokenRBRACE {
  633. break
  634. }
  635. n, err = p.run(0)
  636. st.Children = append(st.Children, n)
  637. }
  638. }
  639. if err != nil {
  640. return nil, err
  641. }
  642. }
  643. // Must end with a closing brace
  644. return self, skipToken(p, TokenRBRACE)
  645. }