parser.go 22 KB

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