Skip to content

Commit e1bf754

Browse files
committed
Adds parser example
1 parent aaae532 commit e1bf754

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

examples/parser.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from syntactes import Grammar, Rule, Token
2+
from syntactes.parser import ParserError, SLRParser, execute_on
3+
4+
EOF = Token.eof()
5+
S = Token("S", is_terminal=False)
6+
E = Token("E", False)
7+
T = Token("T", False)
8+
x = Token("x", True, 1) # value of token is 1
9+
PLUS = Token("+", True)
10+
11+
tokens = {EOF, S, E, T, x, PLUS}
12+
13+
# 0. S -> E $
14+
# 1. E -> T + E
15+
# 2. E -> T
16+
# 3. T -> x
17+
rule_1 = Rule(0, S, E, EOF)
18+
rule_2 = Rule(1, E, T, PLUS, E)
19+
rule_3 = Rule(2, E, T)
20+
rule_4 = Rule(4, T, x)
21+
22+
rules = (rule_1, rule_2, rule_3, rule_4)
23+
24+
grammar = Grammar(rule_1, rules, tokens)
25+
26+
parser = SLRParser.from_grammar(grammar)
27+
28+
29+
@execute_on(rule_4)
30+
def push_value(x_token):
31+
# Add and argument for every token on the right-hand side of the rule.
32+
print(
33+
f"received token {x_token} with value: {x_token.value}, reducing by rule: {rule_4}"
34+
)
35+
36+
37+
@execute_on(rule_2)
38+
def add(left, plus, right):
39+
print(f"received tokens {left}, {plus}, {right}, reducing by rule: {rule_2}")
40+
41+
42+
print("Parsing stream: x + x + x $\n")
43+
parser.parse([x, PLUS, x, PLUS, x, EOF])
44+
45+
print("\nParsing stream: x + $\n")
46+
try:
47+
parser.parse([x, PLUS, EOF])
48+
except ParserError as e:
49+
print("ParserError:", e)

0 commit comments

Comments
 (0)