Created
November 19, 2021 11:34
-
-
Save kelvingakuo/1bad8a1b120fa8615a4377a30f8d7a9d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Parser(self): | |
def advance(self): | |
""" Advance the tokens in use | |
""" | |
self.current_token, self.next_token = self.next_token, next(self.tokens, None) | |
def accept(self, expected, raise_err = True): | |
""" Helper function to check if the next token is what we expect | |
Params: | |
expected (str) - Either the exact token we expect e.g. "SELECT" or the token type we expect e.g. "name" | |
raise_err (bool) - Whether or not to raise an error and halt program | |
Returns: | |
(bool) - Whether the next token is what's expected | |
""" | |
if(self.next_token["token"] == expected or self.next_token["token_type"] == expected): | |
print(f"{self.next_token} == ({expected})") | |
self.advance() | |
if(self.next_token is None): | |
if(self.current_token["token_type"] == "terminal"): | |
print("No more tokens. Printing parse tree.... \n") | |
else: | |
raise ParsingErrorException(f"Semi-colon (;) expected at the end of the query") | |
return True | |
else: | |
if(raise_err): | |
raise ParsingErrorException(f"Unexpected token {self.next_token}. Expected {expected}. Please refer to the grammar {bnf}") | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment