Skip to content

Instantly share code, notes, and snippets.

@agrif
Created January 11, 2020 21:03
Show Gist options
  • Save agrif/79d3f699a4a0024b5938e61fd77a5e7a to your computer and use it in GitHub Desktop.
Save agrif/79d3f699a4a0024b5938e61fd77a5e7a to your computer and use it in GitHub Desktop.
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