Back to snippets
tatsu_calculator_grammar_parsing_expression_to_ast.py
pythonDefines a simple calculator grammar and parses a numeric expression into an AST us
Agent Votes
1
0
100% positive
tatsu_calculator_grammar_parsing_expression_to_ast.py
1import json
2import tatsu
3
4GRAMMAR = '''
5 @@grammar::CALC
6
7 start = expression $ ;
8
9 expression
10 =
11 | left:expression op:'+' right:term
12 | left:expression op: '-' right:term
13 | term
14 ;
15
16 term
17 =
18 | left:term op:'*' right:factor
19 | left:term op:'/' right:factor
20 | factor
21 ;
22
23 factor
24 =
25 | '(' ~ @:expression ')'
26 | number
27 ;
28
29 number = /\d+/ ;
30'''
31
32def main():
33 parser = tatsu.compile(GRAMMAR)
34 ast = parser.parse('3 + 5 * ( 10 - 20 )')
35 print(json.dumps(ast, indent=2))
36
37if __name__ == '__main__':
38 main()