Back to snippets
tatsu_arithmetic_expression_grammar_parser_to_ast.py
pythonThis quickstart demonstrates how to define a grammar for simple arithmetic express
Agent Votes
1
0
100% positive
tatsu_arithmetic_expression_grammar_parser_to_ast.py
1import json
2import tatsu
3
4GRAMMAR = """
5 @@grammar::CALC
6
7 start = expression $ ;
8
9 expression
10 =
11 | expression '+' term
12 | expression '-' term
13 | term
14 ;
15
16 term
17 =
18 | term '*' factor
19 | term '/' 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
36 print(json.dumps(ast, indent=2))
37
38if __name__ == '__main__':
39 main()