-
Notifications
You must be signed in to change notification settings - Fork 3
/
packrat.py
411 lines (333 loc) · 13.1 KB
/
packrat.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
"""
Packrat Parsing
"""
# NOTE: attempting to use exceptions instead of FAIL codes resulted in
# almost a 2x slowdown, so it's probably not a good idea
from typing import List, Dict, Callable, Iterable, Any, Optional
from collections import defaultdict
import re
import inspect
from pe._constants import (
FAIL,
MAX_MEMO_SIZE,
DEL_MEMO_SIZE,
Operator,
Flag,
)
from pe._errors import Error, ParseError
from pe._definition import Definition
from pe._match import Match, determine
from pe._types import RawMatch, Memo
from pe._grammar import Grammar
from pe._parser import Parser
from pe._optimize import optimize, regex
from pe._autoignore import autoignore
from pe._debug import debug
from pe._misc import ansicolor
from pe.actions import Action
from pe.patterns import DEFAULT_IGNORE
_Matcher = Callable[[str, int, Memo], RawMatch]
class PackratParser(Parser):
def __init__(
self,
grammar: Grammar,
ignore: Optional[Definition] = DEFAULT_IGNORE,
flags: Flag = Flag.NONE
):
super().__init__(grammar, flags=flags)
grammar = autoignore(grammar, ignore)
grammar = optimize(grammar,
inline=flags & Flag.INLINE,
common=flags & Flag.COMMON,
regex=flags & Flag.REGEX)
if flags & Flag.DEBUG:
grammar = debug(grammar)
self.modified_grammar = grammar
self._exprs: Dict[str, Callable] = {}
self._grammar_to_packrat(grammar)
@property
def start(self):
return self.grammar.start
def __contains__(self, name: str) -> bool:
return name in self._exprs
def match(self,
s: str,
pos: int = 0,
flags: Flag = Flag.MEMOIZE | Flag.STRICT) -> Optional[Match]:
memo: Optional[Memo] = None
if flags & Flag.MEMOIZE:
memo = defaultdict(dict)
end, args, kwargs = self._exprs[self.start](s, pos, memo)
if end < 0:
if flags & Flag.STRICT:
failpos, message = _get_furthest_fail(args, memo)
if failpos >= 0:
exc = ParseError.from_pos(failpos, s, message=message)
else:
exc = ParseError(message=message)
raise exc
else:
return None
args = tuple(args or ())
if kwargs is None:
kwargs = {}
return Match(s, pos, end, self.grammar[self.start], args, kwargs)
def _grammar_to_packrat(self, grammar):
exprs = self._exprs
for name, _def in grammar.definitions.items():
expr = self._def_to_expr(_def)
# if name is already in exprs, that means it was seen as a
# nonterminal in some other rule, so don't replace the object
# or the call chain will break.
if name in exprs:
if isinstance(expr, Rule):
action = expr.action
expr = expr.expression
else:
action = None
exprs[name].expression = expr
exprs[name].action = action
else:
exprs[name] = expr
# ensure all symbols are defined
for name, expr in exprs.items():
if expr is None or (isinstance(expr, Rule)
and expr.expression is None):
raise Error(f'undefined rule: {name}')
return exprs
def _def_to_expr(self, definition: Definition):
op = definition.op
if op == Operator.SYM:
name = definition.args[0]
return self._exprs.setdefault(name, Rule(name))
else:
if op in self._op_map:
return self._op_map[op](self, definition)
else:
raise Error(f'invalid definition: {definition!r}')
def _terminal(self, definition: Definition) -> _Matcher:
definition = regex(definition)
_re = re.compile(definition.args[0], flags=definition.args[1])
def _match(s: str, pos: int, memo: Memo) -> RawMatch:
m = _re.match(s, pos)
retval: RawMatch
if m:
retval = m.end(), (), None
else:
retval = FAIL, (pos, definition), None
if memo is not None:
memo[pos][id(_match)] = retval
return retval
return _match
def _sequence(self, definition: Definition) -> _Matcher:
items: Iterable[Definition] = definition.args[0]
expressions = [self._def_to_expr(defn) for defn in items]
def _match(s: str, pos: int, memo: Memo) -> RawMatch:
args: List = []
kwargs: Dict[str, Any] = {}
for expr in expressions:
end, _args, _kwargs = expr(s, pos, memo)
if end < 0:
return FAIL, _args, None
else:
args.extend(_args)
if _kwargs:
kwargs.update(_kwargs)
pos = end
return pos, tuple(args), kwargs
return _match
def _choice(self, definition: Definition) -> _Matcher:
items: Iterable[Definition] = definition.args[0]
expressions = [self._def_to_expr(defn) for defn in items]
def _match(s: str, pos: int, memo: Memo) -> RawMatch:
_id = id(_match)
if memo and pos in memo and _id in memo[pos]:
# packrat memoization check
end, args, kwargs = memo[pos][_id]
else:
# clear memo beyond size limit
if memo and len(memo) > MAX_MEMO_SIZE:
for _pos in sorted(memo)[:DEL_MEMO_SIZE]:
del memo[_pos]
for e in expressions:
end, args, kwargs = e(s, pos, memo)
if end >= 0:
break
if memo is not None:
memo[pos][_id] = (end, args, kwargs)
return end, args, kwargs # end may be FAIL
return _match
def _repeat(self, definition: Definition, min: int) -> _Matcher:
expression = self._def_to_expr(definition)
def _match(s: str, pos: int, memo: Memo) -> RawMatch:
guard = len(s) - pos # simple guard against runaway left-recursion
args: List = []
kwargs: Dict[str, Any] = {}
ext = args.extend
upd = kwargs.update
end, _args, _kwargs = expression(s, pos, memo)
if end < 0 and min > 0:
return FAIL, _args, None
while end >= 0 and guard > 0:
ext(_args)
if _kwargs:
upd(_kwargs)
pos = end
guard -= 1
end, _args, _kwargs = expression(s, pos, memo)
return pos, tuple(args), kwargs
return _match
def _star(self, definition: Definition) -> _Matcher:
return self._repeat(definition.args[0], 0)
def _plus(self, definition: Definition) -> _Matcher:
return self._repeat(definition.args[0], 1)
def _optional(self, definition: Definition) -> _Matcher:
expression = self._def_to_expr(definition.args[0])
def _match(s: str, pos: int, memo: Memo) -> RawMatch:
end, args, kwargs = expression(s, pos, memo)
if end < 0:
return pos, (), None
return end, args, kwargs
return _match
def _lookahead(self, definition: Definition, polarity: bool) -> _Matcher:
"""An expression that may match but consumes no input."""
expression = self._def_to_expr(definition)
def _match(s: str, pos: int, memo: Memo) -> RawMatch:
end, args, kwargs = expression(s, pos, memo)
passed = end >= 0
if polarity ^ passed:
if passed: # negative lookahead failed
return FAIL, (pos, expression), None
else: # positive lookahead failed
return FAIL, args, None
return pos, (), None
return _match
def _and(self, definition: Definition) -> _Matcher:
return self._lookahead(definition.args[0], True)
def _not(self, definition: Definition) -> _Matcher:
return self._lookahead(definition.args[0], False)
def _capture(self, definition: Definition) -> _Matcher:
expression = self._def_to_expr(definition.args[0])
def _match(s: str, pos: int, memo: Memo) -> RawMatch:
end, args, kwargs = expression(s, pos, memo)
if end < 0:
return FAIL, args, None
return end, (s[pos:end],), None
return _match
def _bind(self, definition: Definition) -> _Matcher:
bound: Definition = definition.args[0]
expression = self._def_to_expr(bound)
name: str = definition.args[1]
def _match(s: str, pos: int, memo: Memo) -> RawMatch:
end, args, kwargs = expression(s, pos, memo)
if end < 0:
return FAIL, args, None
if not kwargs:
kwargs = {}
kwargs[name] = determine(args)
return end, (), kwargs
return _match
def _rule(self, definition: Definition) -> _Matcher:
subdef: Definition
action: Action
name: str
subdef, action, name = definition.args
expression = self._def_to_expr(subdef)
return Rule(name, expression, action)
@staticmethod
def _format_snippet(text: str) -> str:
"""Escape any characters that create large amounts of whitespace,
mainly line breaking characters like newlines but also tabs.
"""
offending_characters = str.maketrans({
"\n": r"\n", # newline
"\r": r"\r", # carriage return
"\v": r"\v", # vertical tab
"\t": r"\t", # horizontal tab
"\f": r"\f", # form feed
"\u0085": r"\u0085", # NEL next line
"\u2028": r"\u2028", # \N{LINE SEPARATOR}
"\u2029": r"\u2029", # \N{PARAGRAPH SEPARATOR}
})
return text.translate(offending_characters)
def _debug(self, definition: Definition) -> _Matcher:
subdef: Definition = definition.args[0]
expression = self._def_to_expr(subdef)
def _match(s: str, pos: int, memo: Memo) -> RawMatch:
# for proper printing, only terminals can print after
# knowing the result
snippet = self._format_snippet(s[pos:pos+10])[:10].ljust(12)
if subdef.op.precedence == 6 and subdef.op != Operator.SYM:
end, args, kwargs = expression(s, pos, memo)
indent = ' ' * len(inspect.stack(0))
color = 'green' if end >= 0 else 'red'
defstr = ansicolor(color, str(subdef))
print(f'{snippet} | {indent}{defstr}')
else:
print('{} | {}{!s}'.format(
snippet,
' ' * len(inspect.stack(0)),
str(subdef)))
end, args, kwargs = expression(s, pos, memo)
return end, args, kwargs
return _match
_op_map = {
Operator.DOT: _terminal,
Operator.LIT: _terminal,
Operator.CLS: _terminal,
Operator.RGX: _terminal,
# Operator.SYM: _,
Operator.OPT: _optional,
Operator.STR: _star,
Operator.PLS: _plus,
Operator.AND: _and,
Operator.NOT: _not,
Operator.CAP: _capture,
Operator.BND: _bind,
Operator.SEQ: _sequence,
Operator.CHC: _choice,
Operator.RUL: _rule,
Operator.DBG: _debug,
}
# Recursion and Rules
class Rule:
"""
A grammar rule is a named expression with an optional action.
The *name* field is more relevant for the grammar than the rule
itself, but it helps with debugging.
"""
def __init__(self,
name: str,
expression: Optional[_Matcher] = None,
action: Optional[Action] = None):
self.name = name
self.expression = expression
self.action = action
def __call__(self, s: str, pos: int, memo: Memo) -> RawMatch:
expression = self.expression
if expression:
end, args, kwargs = expression(s, pos, memo)
action = self.action
if end >= 0 and action:
if not kwargs:
kwargs = {}
args, kwargs = action(s, pos, end, args, kwargs)
return end, args, kwargs
else:
raise NotImplementedError
def _get_furthest_fail(args, memo):
failpos = -1
message = 'failed to parse; use memoization for more details'
# assuming we're here because of a failure, the max memo position
# should be the furthest failure
if memo:
memopos = max(memo)
fails = []
if memopos > failpos:
fails = [args[1]
for pos, args, _ in memo[memopos].values()
if pos < 0]
if fails:
failpos = memopos
message = ', '.join(map(str, fails))
return failpos, message