parser.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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: {NodeAS, nil, nil, nil, nil, 0, nil, 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 statement
  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. // Try statement
  100. TokenTRY: {NodeTRY, nil, nil, nil, nil, 0, ndTry, nil},
  101. TokenEXCEPT: {NodeEXCEPT, nil, nil, nil, nil, 0, nil, nil},
  102. TokenFINALLY: {NodeFINALLY, nil, nil, nil, nil, 0, nil, nil},
  103. }
  104. }
  105. // Parser
  106. // ======
  107. /*
  108. Parser data structure
  109. */
  110. type parser struct {
  111. name string // Name to identify the input
  112. node *ASTNode // Current ast node
  113. tokens *LABuffer // Buffer which is connected to the channel which contains lex tokens
  114. rp RuntimeProvider // Runtime provider which creates runtime components
  115. }
  116. /*
  117. Parse parses a given input string and returns an AST.
  118. */
  119. func Parse(name string, input string) (*ASTNode, error) {
  120. return ParseWithRuntime(name, input, nil)
  121. }
  122. /*
  123. ParseWithRuntime parses a given input string and returns an AST decorated with
  124. runtime components.
  125. */
  126. func ParseWithRuntime(name string, input string, rp RuntimeProvider) (*ASTNode, error) {
  127. // Create a new parser with a look-ahead buffer of 3
  128. p := &parser{name, nil, NewLABuffer(Lex(name, input), 3), rp}
  129. // Read and set initial AST node
  130. node, err := p.next()
  131. if err != nil {
  132. return nil, err
  133. }
  134. p.node = node
  135. n, err := p.run(0)
  136. if err == nil && hasMoreStatements(p, n) {
  137. st := astNodeMap[TokenSTATEMENTS].instance(p, nil)
  138. st.Children = append(st.Children, n)
  139. for err == nil && hasMoreStatements(p, n) {
  140. // Skip semicolons
  141. if p.node.Token.ID == TokenSEMICOLON {
  142. skipToken(p, TokenSEMICOLON)
  143. }
  144. n, err = p.run(0)
  145. st.Children = append(st.Children, n)
  146. }
  147. n = st
  148. }
  149. if err == nil && p.node != nil && p.node.Token.ID != TokenEOF {
  150. token := *p.node.Token
  151. err = p.newParserError(ErrUnexpectedEnd, fmt.Sprintf("extra token id:%v (%v)",
  152. token.ID, token), token)
  153. }
  154. return n, err
  155. }
  156. /*
  157. run models the main parser function.
  158. */
  159. func (p *parser) run(rightBinding int) (*ASTNode, error) {
  160. var err error
  161. n := p.node
  162. p.node, err = p.next()
  163. if err != nil {
  164. return nil, err
  165. }
  166. // Start with the null denotation of this statement / expression
  167. if n.nullDenotation == nil {
  168. return nil, p.newParserError(ErrImpossibleNullDenotation,
  169. n.Token.String(), *n.Token)
  170. }
  171. left, err := n.nullDenotation(p, n)
  172. if err != nil {
  173. return nil, err
  174. }
  175. // Collect left denotations as long as the left binding power is greater
  176. // than the initial right one
  177. for rightBinding < p.node.binding {
  178. var nleft *ASTNode
  179. n = p.node
  180. if n.leftDenotation == nil {
  181. if left.Token.Lline < n.Token.Lline {
  182. // If the impossible left denotation is on a new line
  183. // we might be parsing a new statement
  184. return left, nil
  185. }
  186. return nil, p.newParserError(ErrImpossibleLeftDenotation,
  187. n.Token.String(), *n.Token)
  188. }
  189. p.node, err = p.next()
  190. if err != nil {
  191. return nil, err
  192. }
  193. // Get the next left denotation
  194. nleft, err = n.leftDenotation(p, n, left)
  195. left = nleft
  196. if err != nil {
  197. return nil, err
  198. }
  199. }
  200. return left, nil
  201. }
  202. /*
  203. next retrieves the next lexer token.
  204. */
  205. func (p *parser) next() (*ASTNode, error) {
  206. var preComments []MetaData
  207. var postComments []MetaData
  208. token, more := p.tokens.Next()
  209. for more && (token.ID == TokenPRECOMMENT || token.ID == TokenPOSTCOMMENT) {
  210. if token.ID == TokenPRECOMMENT {
  211. // Skip over pre comment token
  212. preComments = append(preComments, NewLexTokenInstance(token))
  213. token, more = p.tokens.Next()
  214. }
  215. if token.ID == TokenPOSTCOMMENT {
  216. // Skip over post comment token
  217. postComments = append(postComments, NewLexTokenInstance(token))
  218. token, more = p.tokens.Next()
  219. }
  220. }
  221. if !more {
  222. // Unexpected end of input - the associated token is an empty error token
  223. return nil, p.newParserError(ErrUnexpectedEnd, "", token)
  224. } else if token.ID == TokenError {
  225. // There was a lexer error wrap it in a parser error
  226. return nil, p.newParserError(ErrLexicalError, token.Val, token)
  227. } else if node, ok := astNodeMap[token.ID]; ok {
  228. // We got a normal AST component
  229. ret := node.instance(p, &token)
  230. ret.Meta = append(ret.Meta, preComments...) // Attach pre comments to the next AST node
  231. if len(postComments) > 0 && p.node != nil {
  232. p.node.Meta = append(p.node.Meta, postComments...) // Attach post comments to the previous AST node
  233. }
  234. return ret, nil
  235. }
  236. return nil, p.newParserError(ErrUnknownToken, fmt.Sprintf("id:%v (%v)", token.ID, token), token)
  237. }
  238. // Standard null denotation functions
  239. // ==================================
  240. /*
  241. ndTerm is used for terminals.
  242. */
  243. func ndTerm(p *parser, self *ASTNode) (*ASTNode, error) {
  244. return self, nil
  245. }
  246. /*
  247. ndInner returns the inner expression of an enclosed block and discard the
  248. block token. This method is used for brackets.
  249. */
  250. func ndInner(p *parser, self *ASTNode) (*ASTNode, error) {
  251. // Get the inner expression
  252. exp, err := p.run(0)
  253. if err != nil {
  254. return nil, err
  255. }
  256. // We return here the inner expression - discarding the bracket tokens
  257. return exp, skipToken(p, TokenRPAREN)
  258. }
  259. /*
  260. ndPrefix is used for prefix operators.
  261. */
  262. func ndPrefix(p *parser, self *ASTNode) (*ASTNode, error) {
  263. // Make sure a prefix will only prefix the next item
  264. val, err := p.run(self.binding + 20)
  265. if err != nil {
  266. return nil, err
  267. }
  268. self.Children = append(self.Children, val)
  269. return self, nil
  270. }
  271. // Null denotation functions for specific expressions
  272. // ==================================================
  273. /*
  274. ndImport is used to parse imports.
  275. */
  276. func ndImport(p *parser, self *ASTNode) (*ASTNode, error) {
  277. // Must specify a file path
  278. err := acceptChild(p, self, TokenSTRING)
  279. if err == nil {
  280. // Must specify AS
  281. if err = skipToken(p, TokenAS); err == nil {
  282. // Must specify an identifier
  283. err = acceptChild(p, self, TokenIDENTIFIER)
  284. }
  285. }
  286. return self, err
  287. }
  288. /*
  289. ndSink is used to parse sinks.
  290. */
  291. func ndSkink(p *parser, self *ASTNode) (*ASTNode, error) {
  292. var exp, ret *ASTNode
  293. // Must specify a name
  294. err := acceptChild(p, self, TokenIDENTIFIER)
  295. if err == nil {
  296. // Parse the rest of the parameters as children until we reach the body
  297. for err == nil && IsNotEndAndNotToken(p, TokenLBRACE) {
  298. if exp, err = p.run(150); err == nil {
  299. self.Children = append(self.Children, exp)
  300. // Skip commas
  301. if p.node.Token.ID == TokenCOMMA {
  302. err = skipToken(p, TokenCOMMA)
  303. }
  304. }
  305. }
  306. if err == nil {
  307. // Parse the body
  308. ret, err = parseInnerStatements(p, self)
  309. }
  310. }
  311. return ret, err
  312. }
  313. /*
  314. ndFunc is used to parse function definitions.
  315. */
  316. func ndFunc(p *parser, self *ASTNode) (*ASTNode, error) {
  317. var exp *ASTNode
  318. var err error
  319. // Might specify a function name
  320. if p.node.Token.ID == TokenIDENTIFIER {
  321. err = acceptChild(p, self, TokenIDENTIFIER)
  322. }
  323. // Read in parameters
  324. if err == nil {
  325. err = skipToken(p, TokenLPAREN)
  326. params := astNodeMap[TokenPARAMS].instance(p, nil)
  327. self.Children = append(self.Children, params)
  328. for err == nil && IsNotEndAndNotToken(p, TokenRPAREN) {
  329. // Parse all the expressions inside
  330. if exp, err = p.run(0); err == nil {
  331. params.Children = append(params.Children, exp)
  332. if p.node.Token.ID == TokenCOMMA {
  333. err = skipToken(p, TokenCOMMA)
  334. }
  335. }
  336. }
  337. if err == nil {
  338. err = skipToken(p, TokenRPAREN)
  339. }
  340. }
  341. if err == nil {
  342. // Parse the body
  343. self, err = parseInnerStatements(p, self)
  344. }
  345. return self, err
  346. }
  347. /*
  348. ndReturn is used to parse return statements.
  349. */
  350. func ndReturn(p *parser, self *ASTNode) (*ASTNode, error) {
  351. var err error
  352. if self.Token.Lline == p.node.Token.Lline {
  353. var val *ASTNode
  354. // Consume the next expression only if it is on the same line
  355. val, err = p.run(0)
  356. if err == nil {
  357. self.Children = append(self.Children, val)
  358. }
  359. }
  360. return self, err
  361. }
  362. /*
  363. ndIdentifier is to parse identifiers and function calls.
  364. */
  365. func ndIdentifier(p *parser, self *ASTNode) (*ASTNode, error) {
  366. var parseMore, parseSegment, parseFuncCall, parseCompositionAccess func(parent *ASTNode) error
  367. parseMore = func(current *ASTNode) error {
  368. var err error
  369. if p.node.Token.ID == TokenDOT {
  370. err = parseSegment(current)
  371. } else if p.node.Token.ID == TokenLPAREN {
  372. err = parseFuncCall(current)
  373. } else if p.node.Token.ID == TokenLBRACK && p.node.Token.Lline == self.Token.Lline {
  374. // Composition access needs to be on the same line as the identifier
  375. // as we might otherwise have a list
  376. err = parseCompositionAccess(current)
  377. }
  378. return err
  379. }
  380. parseSegment = func(current *ASTNode) error {
  381. var err error
  382. var next *ASTNode
  383. if err = skipToken(p, TokenDOT); err == nil {
  384. next = p.node
  385. if err = acceptChild(p, current, TokenIDENTIFIER); err == nil {
  386. err = parseMore(next)
  387. }
  388. }
  389. return err
  390. }
  391. parseFuncCall = func(current *ASTNode) error {
  392. var exp *ASTNode
  393. err := skipToken(p, TokenLPAREN)
  394. fc := astNodeMap[TokenFUNCCALL].instance(p, nil)
  395. current.Children = append(current.Children, fc)
  396. // Read in parameters
  397. for err == nil && IsNotEndAndNotToken(p, TokenRPAREN) {
  398. // Parse all the expressions inside the directives
  399. if exp, err = p.run(0); err == nil {
  400. fc.Children = append(fc.Children, exp)
  401. if p.node.Token.ID == TokenCOMMA {
  402. err = skipToken(p, TokenCOMMA)
  403. }
  404. }
  405. }
  406. if err == nil {
  407. err = skipToken(p, TokenRPAREN)
  408. if err == nil {
  409. err = parseMore(current)
  410. }
  411. }
  412. return err
  413. }
  414. parseCompositionAccess = func(current *ASTNode) error {
  415. var exp *ASTNode
  416. err := skipToken(p, TokenLBRACK)
  417. if err == nil {
  418. ca := astNodeMap[TokenCOMPACCESS].instance(p, nil)
  419. current.Children = append(current.Children, ca)
  420. // Parse all the expressions inside the directives
  421. if exp, err = p.run(0); err == nil {
  422. ca.Children = append(ca.Children, exp)
  423. if err = skipToken(p, TokenRBRACK); err == nil {
  424. err = parseMore(current)
  425. }
  426. }
  427. }
  428. return err
  429. }
  430. return self, parseMore(self)
  431. }
  432. /*
  433. ndList is used to collect elements of a list.
  434. */
  435. func ndList(p *parser, self *ASTNode) (*ASTNode, error) {
  436. var err error
  437. var exp *ASTNode
  438. // Create a list token
  439. st := astNodeMap[TokenLIST].instance(p, self.Token)
  440. // Get the inner expression
  441. for err == nil && IsNotEndAndNotToken(p, TokenRBRACK) {
  442. // Parse all the expressions inside
  443. if exp, err = p.run(0); err == nil {
  444. st.Children = append(st.Children, exp)
  445. if p.node.Token.ID == TokenCOMMA {
  446. err = skipToken(p, TokenCOMMA)
  447. }
  448. }
  449. }
  450. if err == nil {
  451. err = skipToken(p, TokenRBRACK)
  452. }
  453. // Must have a closing bracket
  454. return st, err
  455. }
  456. /*
  457. ndMap is used to collect elements of a map.
  458. */
  459. func ndMap(p *parser, self *ASTNode) (*ASTNode, error) {
  460. var err error
  461. var exp *ASTNode
  462. // Create a map token
  463. st := astNodeMap[TokenMAP].instance(p, self.Token)
  464. // Get the inner expression
  465. for err == nil && IsNotEndAndNotToken(p, TokenRBRACE) {
  466. // Parse all the expressions inside
  467. if exp, err = p.run(0); err == nil {
  468. st.Children = append(st.Children, exp)
  469. if p.node.Token.ID == TokenCOMMA {
  470. err = skipToken(p, TokenCOMMA)
  471. }
  472. }
  473. }
  474. if err == nil {
  475. err = skipToken(p, TokenRBRACE)
  476. }
  477. // Must have a closing brace
  478. return st, err
  479. }
  480. /*
  481. ndGuard is used to parse a conditional statement.
  482. */
  483. func ndGuard(p *parser, self *ASTNode) (*ASTNode, error) {
  484. var err error
  485. parseGuardAndStatements := func() error {
  486. // The brace starts statements while parsing the expression of an if statement
  487. nodeMapEntryBak := astNodeMap[TokenLBRACE]
  488. astNodeMap[TokenLBRACE] = &ASTNode{"", nil, nil, nil, nil, 0, parseInnerStatements, nil}
  489. exp, err := p.run(0)
  490. astNodeMap[TokenLBRACE] = nodeMapEntryBak
  491. if err == nil {
  492. g := astNodeMap[TokenGUARD].instance(p, nil)
  493. g.Children = append(g.Children, exp)
  494. self.Children = append(self.Children, g)
  495. _, err = parseInnerStatements(p, self)
  496. }
  497. return err
  498. }
  499. if err = parseGuardAndStatements(); err == nil {
  500. for err == nil && IsNotEndAndToken(p, TokenELIF) {
  501. // Parse an elif
  502. if err = skipToken(p, TokenELIF); err == nil {
  503. err = parseGuardAndStatements()
  504. }
  505. }
  506. if err == nil && p.node.Token.ID == TokenELSE {
  507. // Parse else
  508. if err = skipToken(p, TokenELSE); err == nil {
  509. g := astNodeMap[TokenGUARD].instance(p, nil)
  510. g.Children = append(g.Children, astNodeMap[TokenTRUE].instance(p, nil))
  511. self.Children = append(self.Children, g)
  512. _, err = parseInnerStatements(p, self)
  513. }
  514. }
  515. }
  516. return self, err
  517. }
  518. /*
  519. ndLoop is used to parse a loop statement.
  520. */
  521. func ndLoop(p *parser, self *ASTNode) (*ASTNode, error) {
  522. // The brace starts statements while parsing the expression of a for statement
  523. nodeMapEntryBak := astNodeMap[TokenLBRACE]
  524. astNodeMap[TokenLBRACE] = &ASTNode{"", nil, nil, nil, nil, 0, parseInnerStatements, nil}
  525. exp, err := p.run(0)
  526. astNodeMap[TokenLBRACE] = nodeMapEntryBak
  527. if err == nil {
  528. g := exp
  529. if exp.Token.ID != TokenIN {
  530. g = astNodeMap[TokenGUARD].instance(p, nil)
  531. g.Children = append(g.Children, exp)
  532. }
  533. self.Children = append(self.Children, g)
  534. _, err = parseInnerStatements(p, self)
  535. }
  536. return self, err
  537. }
  538. /*
  539. ndTry is used to parse a try block.
  540. */
  541. func ndTry(p *parser, self *ASTNode) (*ASTNode, error) {
  542. try, err := parseInnerStatements(p, self)
  543. if p.node.Token.ID != TokenFINALLY {
  544. for err == nil && IsNotEndAndToken(p, TokenEXCEPT) {
  545. except := p.node
  546. err = acceptChild(p, try, TokenEXCEPT)
  547. if err == nil {
  548. for err == nil &&
  549. IsNotEndAndNotToken(p, TokenAS) &&
  550. IsNotEndAndNotToken(p, TokenIDENTIFIER) &&
  551. IsNotEndAndNotToken(p, TokenLBRACE) {
  552. if err = acceptChild(p, except, TokenSTRING); err == nil {
  553. // Skip commas
  554. if p.node.Token.ID == TokenCOMMA {
  555. err = skipToken(p, TokenCOMMA)
  556. }
  557. }
  558. }
  559. if err == nil {
  560. if p.node.Token.ID == TokenAS {
  561. as := p.node
  562. err = acceptChild(p, except, TokenAS)
  563. if err == nil {
  564. err = acceptChild(p, as, TokenIDENTIFIER)
  565. }
  566. } else if p.node.Token.ID == TokenIDENTIFIER {
  567. err = acceptChild(p, except, TokenIDENTIFIER)
  568. }
  569. }
  570. if err == nil {
  571. _, err = parseInnerStatements(p, except)
  572. }
  573. }
  574. }
  575. }
  576. if err == nil && p.node.Token.ID == TokenFINALLY {
  577. finally := p.node
  578. if err = acceptChild(p, try, TokenFINALLY); err == nil {
  579. _, err = parseInnerStatements(p, finally)
  580. }
  581. }
  582. return try, err
  583. }
  584. // Standard left denotation functions
  585. // ==================================
  586. /*
  587. ldInfix is used for infix operators.
  588. */
  589. func ldInfix(p *parser, self *ASTNode, left *ASTNode) (*ASTNode, error) {
  590. right, err := p.run(self.binding)
  591. if err != nil {
  592. return nil, err
  593. }
  594. self.Children = append(self.Children, left)
  595. self.Children = append(self.Children, right)
  596. return self, nil
  597. }
  598. // Helper functions
  599. // ================
  600. /*
  601. IsNotEndAndToken checks if the next token is of a specific type or the end has been reached.
  602. */
  603. func IsNotEndAndToken(p *parser, i LexTokenID) bool {
  604. return p.node != nil && p.node.Name != NodeEOF && p.node.Token.ID == i
  605. }
  606. /*
  607. IsNotEndAndNotToken checks if the next token is not of a specific type or the end has been reached.
  608. */
  609. func IsNotEndAndNotToken(p *parser, i LexTokenID) bool {
  610. return p.node != nil && p.node.Name != NodeEOF && p.node.Token.ID != i
  611. }
  612. /*
  613. hasMoreStatements returns true if there are more statements to parse.
  614. */
  615. func hasMoreStatements(p *parser, currentNode *ASTNode) bool {
  616. nextNode := p.node
  617. if nextNode == nil || nextNode.Token.ID == TokenEOF {
  618. return false
  619. } else if nextNode.Token.ID == TokenSEMICOLON {
  620. return true
  621. }
  622. return currentNode != nil && currentNode.Token.Lline < nextNode.Token.Lline
  623. }
  624. /*
  625. skipToken skips over a given token.
  626. */
  627. func skipToken(p *parser, ids ...LexTokenID) error {
  628. var err error
  629. canSkip := func(id LexTokenID) bool {
  630. for _, i := range ids {
  631. if i == id {
  632. return true
  633. }
  634. }
  635. return false
  636. }
  637. if !canSkip(p.node.Token.ID) {
  638. if p.node.Token.ID == TokenEOF {
  639. return p.newParserError(ErrUnexpectedEnd, "", *p.node.Token)
  640. }
  641. return p.newParserError(ErrUnexpectedToken, p.node.Token.Val, *p.node.Token)
  642. }
  643. // This should never return an error unless we skip over EOF or complex tokens
  644. // like values
  645. p.node, err = p.next()
  646. return err
  647. }
  648. /*
  649. acceptChild accepts the current token as a child.
  650. */
  651. func acceptChild(p *parser, self *ASTNode, id LexTokenID) error {
  652. var err error
  653. current := p.node
  654. if p.node, err = p.next(); err == nil {
  655. if current.Token.ID == id {
  656. self.Children = append(self.Children, current)
  657. } else {
  658. err = p.newParserError(ErrUnexpectedToken, current.Token.Val, *current.Token)
  659. }
  660. }
  661. return err
  662. }
  663. /*
  664. parseInnerStatements collects the inner statements of a block statement. It
  665. is assumed that a block statement starts with a left brace '{' and ends with
  666. a right brace '}'.
  667. */
  668. func parseInnerStatements(p *parser, self *ASTNode) (*ASTNode, error) {
  669. // Must start with an opening brace
  670. if err := skipToken(p, TokenLBRACE); err != nil {
  671. return nil, err
  672. }
  673. // Always create a statements node
  674. st := astNodeMap[TokenSTATEMENTS].instance(p, nil)
  675. self.Children = append(self.Children, st)
  676. // Check if there are actually children
  677. if p.node != nil && p.node.Token.ID != TokenRBRACE {
  678. n, err := p.run(0)
  679. if p.node != nil && p.node.Token.ID != TokenEOF {
  680. st.Children = append(st.Children, n)
  681. for hasMoreStatements(p, n) {
  682. if p.node.Token.ID == TokenSEMICOLON {
  683. skipToken(p, TokenSEMICOLON)
  684. } else if p.node.Token.ID == TokenRBRACE {
  685. break
  686. }
  687. n, err = p.run(0)
  688. st.Children = append(st.Children, n)
  689. }
  690. }
  691. if err != nil {
  692. return nil, err
  693. }
  694. }
  695. // Must end with a closing brace
  696. return self, skipToken(p, TokenRBRACE)
  697. }