parser.go 22 KB

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