Created
March 17, 2021 06:27
-
-
Save ankur0101/823e64945d620b340c5e0a85be14118d to your computer and use it in GitHub Desktop.
This file contains 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
from sly import Lexer, Parser | |
class CalcLexer(Lexer): | |
tokens = { TYPE_DECLARATION, SPACE, COLLAN, ASSIGN, NAME, TYPEOF, END, LPAREN, RPAREN } | |
ignore = ' \t' | |
# Tokens | |
NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' | |
# NUMBER = r'\d+' | |
# Special symbols | |
COLLAN = r'\:' | |
SPACE = r'\ ' | |
ASSIGN = r'=' | |
LPAREN = r'\(' | |
RPAREN = r'\)' | |
TYPE_DECLARATION = r'TYPES' | |
# Ignored pattern | |
ignore_newline = r'\n+' | |
# Extra action for newlines | |
def ignore_newline(self, t): | |
self.lineno += t.value.count('\n') | |
def error(self, t): | |
print("Illegal character '%s'" % t.value[0]) | |
self.index += 1 | |
class CalcParser(Parser): | |
tokens = CalcLexer.tokens | |
def __init__(self): | |
self.names = { } | |
@_('TYPE_DECLARATION COLLAN NAME TYPEOF NAME') | |
def statement(self, p): | |
self.names[p.NAME] = p.expr | |
@_('expr') | |
def statement(self, p): | |
print(p.expr) | |
@_('LPAREN expr RPAREN') | |
def expr(self, p): | |
return p.expr | |
@_('NAME') | |
def expr(self, p): | |
try: | |
return self.names[p.NAME] | |
except LookupError: | |
print(f'Undefined name {p.NAME!r}') | |
return 0 | |
if __name__ == '__main__': | |
lexer = CalcLexer() | |
parser = CalcParser() | |
while True: | |
try: | |
text = input('ABAP > ') | |
except EOFError: | |
break | |
if text: | |
parser.parse(lexer.tokenize(text)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment