-
Notifications
You must be signed in to change notification settings - Fork 1
/
demo_raw_grammar.py
63 lines (55 loc) · 1.49 KB
/
demo_raw_grammar.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import lrkit.canonical
from lrkit import Parser, Rule, rule, SnError
from sys import exit
specials = {
"*": "*",
"/": "/",
"%": "%",
"+": "+",
"-": "-",
"0": "0",
"(": "(",
")": ")",
",": ",",
}
rules = [
rule("Program", "Expr"),
rule("Program"),
rule("Expr", "Sum"),
rule("Sum", "Sum", "SumOp", "Product"),
rule("Sum", "Product"),
rule("Product", "Product", "ProductOp", "Term"),
rule("Product", "Term"),
rule("ProductOp", "*"),
rule("ProductOp", "/"),
rule("ProductOp", "%"),
rule("SumOp", "+"),
rule("SumOp", "-"),
rule("Term", "symbol"),
rule("Term", "(", "ExprList", ")"),
rule("ExprList"),
rule("ExprList", "Expr"),
rule("ExprList", "ExprList", ",", "Expr"),
]
def visit(rule, pos, data):
print "reduction", rule, pos, data
return None
results = lrkit.canonical.simulate(rules, "Program")
if len(results.conflicts):
lrkit.diagnose(results)
exit(1)
parser = Parser(results, visit)
from sys import stdin
while True:
try:
index = 0
source = stdin.readline()
for token in lrkit.tokenize(source, specials):
parser.step(token.start, token.stop, token.group, token.value)
index = token.stop
result = parser.step(index, index, None, None)
except SnError, e:
print "-"*20
print lrkit.snippet(e.start, e.stop, source)
print "SN ERROR:", e.message
parser.reset()