-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpegparsing.py
79 lines (66 loc) · 2.06 KB
/
pegparsing.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from collections import namedtuple
Token = namedtuple("Token", ["type", "string", "line", "col"])
class BaseParser:
def __init__(self, token_generator):
self.gen = token_generator
self.tokens = []
self.token_pos = 0
self.memos = {}
def mark(self):
return self.token_pos
def reset(self, pos):
self.token_pos = pos
def peek_token(self):
if self.token_pos == len(self.tokens):
self.tokens.append(next(self.gen))
return self.tokens[self.token_pos]
def get_token(self):
token = self.peek_token()
self.token_pos += 1
return token
def expect(self, arg):
token = self.peek_token()
if token and token.type == arg:
return self.get_token()
return None
def get_last_tokens(self, n=1):
return self.tokens[-n:]
def memoise(func):
def memoise_wrapper(self, *args):
pos = self.mark()
memo = self.memos.get(pos)
if memo is None:
memo = self.memos[pos] = {}
key = (func, args)
if key in memo:
res, endpos = memo[key]
self.reset(endpos)
else:
res = func(self, *args)
endpos = self.mark()
memo[key] = res, endpos
return res
return memoise_wrapper
def memoise_left_recursive(func):
def memoise_left_rec_wrapper(self, *args):
pos = self.mark()
memo = self.memos.get(pos)
if memo is None:
memo = self.memos[pos] = {}
key = (func, args)
if key in memo:
res, endpos = memo[key]
self.reset(endpos)
else:
memo[key] = lastres, lastpos = None, pos
while True:
self.reset(pos)
res = func(self, *args)
endpos = self.mark()
if endpos <= lastpos:
break
memo[key] = lastres, lastpos = res, endpos
res = lastres
self.reset(lastpos)
return res
return memoise_left_rec_wrapper