Created
January 11, 2020 21:03
-
-
Save agrif/79d3f699a4a0024b5938e61fd77a5e7a 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
lex = Lexer() | |
lex['WS'] = regex.compile(r'\s+') | |
lex.ignore('WS') | |
lex['N'] = regex.compile(r'\d+') | |
for c in '+*()': | |
lex[c] = c | |
class MathBuilder(Builder): | |
""" | |
e.wrap -> t; | |
e.add -> e + t; | |
t.wrap -> f; | |
t.mul -> t * f; | |
f.lit -> N; | |
f.paren -> ( e ); | |
""" | |
def wrap(self, x): | |
return x | |
def paren(self, _0, x, _1): | |
return x | |
def lit(self, n): | |
return int(n.value) | |
def add(self, a, _, b): | |
return a + b | |
def mul(self, a, _, b): | |
return a * b | |
if __name__ == '__main__': | |
parser = make_parser(SLR1, MathBuilder) | |
for tok in lex.feed('1 + (2 * 3)', end=True): | |
parser.feed(tok) | |
print(parser.feed(EOF)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment