-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtextparser.py
926 lines (612 loc) · 20.8 KB
/
textparser.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
# A text parser.
import re
from collections import namedtuple
from operator import itemgetter
__author__ = 'Erik Moqvist'
__version__ = '0.24.0'
class _Mismatch(object):
pass
MISMATCH = _Mismatch()
"""Returned by :func:`~textparser.Pattern.match()` on mismatch.
"""
class _String(object):
"""Matches a specific token kind.
"""
def __init__(self, kind):
self.kind = kind
def match(self, tokens):
if self.kind == tokens.peek().kind:
return tokens.get_value()
else:
return MISMATCH
class _Tokens(object):
def __init__(self, tokens):
self._tokens = tokens
self._pos = 0
self._max_pos = -1
self._stack = []
def get_value(self):
pos = self._pos
self._pos += 1
return self._tokens[pos]
def peek(self):
return self._tokens[self._pos]
def peek_max(self):
pos = self._pos
if self._max_pos > pos:
pos = self._max_pos
if pos >= len(self._tokens):
return self._tokens[-1]
else:
return self._tokens[pos]
def save(self):
self._stack.append(self._pos)
def restore(self):
self._pos = self._stack.pop()
def update(self):
self._stack[-1] = self._pos
def mark_max_restore(self):
if self._pos > self._max_pos:
self._max_pos = self._pos
self._pos = self._stack.pop()
def mark_max_load(self):
if self._pos > self._max_pos:
self._max_pos = self._pos
self._pos = self._stack[-1]
def drop(self):
self._stack.pop()
def __repr__(self):
return str(self._tokens[self._pos:self._pos + 2])
class _StringTokens(_Tokens):
def get_value(self):
pos = self._pos
self._pos += 1
return self._tokens[pos].value
def _wrap_string(item):
if isinstance(item, str):
item = _String(item)
return item
def _wrap_strings(items):
return [_wrap_string(item) for item in items]
def _format_invalid_syntax(text, offset):
return 'Invalid syntax at line {}, column {}: "{}"'.format(
line(text, offset),
column(text, offset),
markup_line(text, offset))
class Error(Exception):
"""General textparser exception.
"""
pass
class TokenizeError(Error):
"""This exception is raised when the text cannot be converted into
tokens.
"""
def __init__(self, text, offset):
self._text = text
self._offset = offset
message = _format_invalid_syntax(text, offset)
super(TokenizeError, self).__init__(message)
@property
def text(self):
"""The input text to the tokenizer.
"""
return self._text
@property
def offset(self):
"""Offset into the text where the tokenizer failed.
"""
return self._offset
class GrammarError(Error):
"""This exception is raised when the tokens cannot be converted into a
parse tree.
"""
def __init__(self, offset):
self._offset = offset
message = 'Invalid syntax at offset {}.'.format(offset)
super(GrammarError, self).__init__(message)
@property
def offset(self):
"""Offset into the text where the parser failed.
"""
return self._offset
class ParseError(Error):
"""This exception is raised when the parser fails to parse the text.
"""
def __init__(self, text, offset):
self._text = text
self._offset = offset
self._line = line(text, offset)
self._column = column(text, offset)
message = _format_invalid_syntax(text, offset)
super(ParseError, self).__init__(message)
@property
def text(self):
"""The input text to the parser.
"""
return self._text
@property
def offset(self):
"""Offset into the text where the parser failed.
"""
return self._offset
@property
def line(self):
"""Line where the parser failed.
"""
return self._line
@property
def column(self):
"""Column where the parser failed.
"""
return self._column
Token = namedtuple('Token', ['kind', 'value', 'offset'])
class Pattern(object):
"""Base class of all patterns.
"""
def match(self, tokens):
"""Returns :data:`~textparser.MISMATCH` on mismatch, and anything else
on match.
"""
raise NotImplementedError('To be implemented by subclasses.')
class Sequence(Pattern):
"""Matches a sequence of patterns. Becomes a list in the parse tree.
"""
def __init__(self, *patterns):
self.patterns = _wrap_strings(patterns)
def match(self, tokens):
matched = []
for pattern in self.patterns:
mo = pattern.match(tokens)
if mo is MISMATCH:
return MISMATCH
matched.append(mo)
return matched
class Choice(Pattern):
"""Matches any of given ordered patterns `patterns`. The first pattern
in the list has highest priority, and the last lowest.
"""
def __init__(self, *patterns):
self._patterns = _wrap_strings(patterns)
def match(self, tokens):
tokens.save()
for pattern in self._patterns:
tokens.mark_max_load()
mo = pattern.match(tokens)
if mo is not MISMATCH:
tokens.drop()
return mo
tokens.restore()
return MISMATCH
class ChoiceDict(Pattern):
"""Matches any of given patterns. The first token kind of all patterns
must be unique, otherwise and :class:`~textparser.Error` exception
is raised.
This class is faster than :class:`~textparser.Choice`, and should
be used if the grammar allows it.
"""
def __init__(self, *patterns):
self._patterns_map = {}
patterns = _wrap_strings(patterns)
for pattern in patterns:
self._check_pattern(pattern, pattern)
@property
def patterns_map(self):
return self._patterns_map
def _check_pattern(self, inner, outer):
if isinstance(inner, _String):
self._add_pattern(inner.kind, outer)
elif isinstance(inner, Sequence):
self._check_pattern(inner.patterns[0], outer)
elif isinstance(inner, (Tag, Forward)):
self._check_pattern(inner.pattern, outer)
elif isinstance(inner, ChoiceDict):
for pattern in inner.patterns_map.values():
self._check_pattern(pattern, outer)
else:
raise Error(
'Unsupported pattern type {}.'.format(type(inner)))
def _add_pattern(self, kind, pattern):
if kind in self._patterns_map:
raise Error(
"First token kind must be unique, but {} isn't.".format(
kind))
self._patterns_map[kind] = pattern
def match(self, tokens):
kind = tokens.peek().kind
if kind in self._patterns_map:
return self._patterns_map[kind].match(tokens)
else:
return MISMATCH
class Repeated(Pattern):
"""Matches `pattern` at least `minimum` times. Any match becomes a
list in the parse tree.
"""
def __init__(self, pattern, minimum=0):
self._pattern = _wrap_string(pattern)
self._minimum = minimum
def match(self, tokens):
matched = []
tokens.save()
while True:
mo = self._pattern.match(tokens)
if mo is MISMATCH:
tokens.mark_max_restore()
break
matched.append(mo)
tokens.update()
if len(matched) >= self._minimum:
return matched
else:
return MISMATCH
class RepeatedDict(Repeated):
"""Same as :class:`~textparser.Repeated`, but becomes a dictionary
instead of a list in the parse tree.
`key` is a function taking the match as input and returning the
dictionary key. By default the first element in the match is used
as key.
"""
def __init__(self, pattern, minimum=0, key=None):
super(RepeatedDict, self).__init__(pattern, minimum)
if key is None:
key = itemgetter(0)
self._key = key
def match(self, tokens):
matched = {}
tokens.save()
while True:
mo = self._pattern.match(tokens)
if mo is MISMATCH:
tokens.mark_max_restore()
break
key = self._key(mo)
try:
matched[key].append(mo)
except KeyError:
matched[key] = [mo]
tokens.update()
if len(matched) >= self._minimum:
return matched
else:
return MISMATCH
class ZeroOrMore(Repeated):
"""Matches `pattern` zero or more times.
See :class:`~textparser.Repeated` for more details.
"""
def __init__(self, pattern):
super(ZeroOrMore, self).__init__(pattern, 0)
class ZeroOrMoreDict(RepeatedDict):
"""Matches `pattern` zero or more times.
See :class:`~textparser.RepeatedDict` for more details.
"""
def __init__(self, pattern, key=None):
super(ZeroOrMoreDict, self).__init__(pattern, 0, key)
class OneOrMore(Repeated):
"""Matches `pattern` one or more times.
See :class:`~textparser.Repeated` for more details.
"""
def __init__(self, pattern):
super(OneOrMore, self).__init__(pattern, 1)
class OneOrMoreDict(RepeatedDict):
"""Matches `pattern` one or more times.
See :class:`~textparser.RepeatedDict` for more details.
"""
def __init__(self, pattern, key=None):
super(OneOrMoreDict, self).__init__(pattern, 1, key)
class DelimitedList(Pattern):
"""Matches a delimented list of `pattern` separated by
`delim`. `pattern` must be matched at least once. Any match
becomes a list in the parse tree, excluding the delimiters.
"""
def __init__(self, pattern, delim=','):
self._pattern = _wrap_string(pattern)
self._delim = _wrap_string(delim)
def match(self, tokens):
# First pattern.
mo = self._pattern.match(tokens)
if mo is MISMATCH:
return MISMATCH
matched = [mo]
tokens.save()
while True:
# Discard the delimiter.
mo = self._delim.match(tokens)
if mo is MISMATCH:
break
# Pattern.
mo = self._pattern.match(tokens)
if mo is MISMATCH:
break
matched.append(mo)
tokens.update()
tokens.restore()
return matched
class Optional(Pattern):
"""Matches `pattern` zero or one times. Becomes a list in the parse
tree, empty on mismatch.
"""
def __init__(self, pattern):
self._pattern = _wrap_string(pattern)
def match(self, tokens):
tokens.save()
mo = self._pattern.match(tokens)
if mo is MISMATCH:
tokens.mark_max_restore()
return []
else:
tokens.drop()
return [mo]
class Any(Pattern):
"""Matches any token.
"""
def match(self, tokens):
if tokens.peek().kind == '__EOF__':
return MISMATCH
else:
return tokens.get_value()
class AnyUntil(Pattern):
"""Matches any token until given pattern is found. Becomes a list in
the parse tree, not including the given pattern match.
"""
def __init__(self, pattern):
self._pattern = _wrap_string(pattern)
def match(self, tokens):
matched = []
while True:
tokens.save()
mo = self._pattern.match(tokens)
if mo is not MISMATCH:
break
tokens.restore()
matched.append(tokens.get_value())
tokens.restore()
return matched
class And(Pattern):
"""Matches `pattern`, without consuming any tokens. Any match becomes
an empty list in the parse tree.
"""
def __init__(self, pattern):
self._pattern = _wrap_string(pattern)
def match(self, tokens):
tokens.save()
mo = self._pattern.match(tokens)
tokens.restore()
if mo is MISMATCH:
return MISMATCH
else:
return []
class Not(Pattern):
"""Matches if `pattern` does not match. Any match becomes an empty
list in the parse tree.
Just like :class:`~textparser.And`, no tokens are consumed.
"""
def __init__(self, pattern):
self._pattern = _wrap_string(pattern)
def match(self, tokens):
tokens.save()
mo = self._pattern.match(tokens)
tokens.restore()
if mo is MISMATCH:
return []
else:
return MISMATCH
class NoMatch(Pattern):
"""Never matches anything.
"""
def match(self, tokens):
return MISMATCH
class Tag(Pattern):
"""Tags any matched `pattern` with name `name`. Becomes a two-tuple of
`name` and match in the parse tree.
"""
def __init__(self, name, pattern):
self._name = name
self._pattern = _wrap_string(pattern)
@property
def pattern(self):
return self._pattern
def match(self, tokens):
mo = self._pattern.match(tokens)
if mo is not MISMATCH:
return (self._name, mo)
else:
return MISMATCH
class Forward(Pattern):
"""Forward declaration of a pattern.
.. code-block:: python
>>> foo = Forward()
>>> foo <<= Sequence('NUMBER')
"""
def __init__(self):
self._pattern = None
@property
def pattern(self):
return self._pattern
def __ilshift__(self, other):
self._pattern = _wrap_string(other)
return self
def match(self, tokens):
return self._pattern.match(tokens)
class Grammar(object):
"""Creates a tree of given tokens using the grammar `grammar`.
"""
def __init__(self, grammar):
if isinstance(grammar, str):
grammar = _wrap_string(grammar)
self._root = grammar
def parse(self, tokens, token_tree=False):
if token_tree:
tokens = _Tokens(tokens)
else:
tokens = _StringTokens(tokens)
parsed = self._root.match(tokens)
if parsed is not MISMATCH and tokens.peek_max().kind == '__EOF__':
return parsed
else:
raise GrammarError(tokens.peek_max().offset)
def choice(*patterns):
"""Returns an instance of the fastest choice class for given patterns
`patterns`. It is recommended to use this function instead of
instantiate :class:`~textparser.Choice` or
:class:`~textparser.ChoiceDict` directly.
"""
try:
return ChoiceDict(*patterns)
except Error:
return Choice(*patterns)
def markup_line(text, offset, marker='>>!<<'):
"""Insert `marker` at `offset` into `text`, and return the marked
line.
.. code-block:: python
>>> markup_line('0\\n1234\\n56', 3)
1>>!<<234
"""
begin = text.rfind('\n', 0, offset)
begin += 1
end = text.find('\n', offset)
if end == -1:
end = len(text)
return text[begin:offset] + marker + text[offset:end]
def line(text, offset):
return text[:offset].count('\n') + 1
def column(text, offset):
line_start = text.rfind('\n', 0, offset)
return offset - line_start
def tokenize_init(spec):
"""Initialize a tokenizer. Should only be called by the
:func:`~textparser.Parser.tokenize` method in the parser.
"""
tokens = [Token('__SOF__', '__SOF__', 0)]
re_token = '|'.join([
'(?P<{}>{})'.format(name, regex) for name, regex in spec
])
return tokens, re_token
class Parser(object):
"""The abstract base class of all text parsers.
.. code-block:: python
>>> from textparser import Parser, Sequence
>>> class MyParser(Parser):
... def token_specs(self):
... return [
... ('SKIP', r'[ \\r\\n\\t]+'),
... ('WORD', r'\\w+'),
... ('EMARK', '!', r'!'),
... ('COMMA', ',', r','),
... ('MISMATCH', r'.')
... ]
... def grammar(self):
... return Sequence('WORD', ',', 'WORD', '!')
"""
def _unpack_token_specs(self):
names = {}
specs = []
for spec in self.token_specs():
if len(spec) == 2:
specs.append(spec)
else:
specs.append((spec[0], spec[2]))
names[spec[0]] = spec[1]
return names, specs
def keywords(self):
"""A set of keywords in the text.
.. code-block:: python
def keywords(self):
return set(['if', 'else'])
"""
return set()
def token_specs(self):
"""The token specifications with token name, regular expression, and
optionally a user friendly name.
Two token specification forms are available; ``(kind, re)`` or
``(kind, name, re)``. If the second form is used, the grammar
should use `name` instead of `kind`.
See :class:`~textparser.Parser` for an example usage.
"""
return [
('SKIP', r'[ \r\n\t]+'),
('NUMBER', r'-?\d+(\.\d+)?([eE][+-]?\d+)?'),
('WORD', r'[A-Za-z0-9_]+'),
('ESCAPED_STRING', r'"(\\"|[^"])*?"'),
('MISMATCH', r'.')
]
def tokenize(self, text):
"""Tokenize given string `text`, and return a list of tokens. Raises
:class:`~textparser.TokenizeError` on failure.
This method should only be called by
:func:`~textparser.Parser.parse()`, but may very well be
overridden if the default implementation does not match the
parser needs.
"""
names, specs = self._unpack_token_specs()
keywords = self.keywords()
tokens, re_token = tokenize_init(specs)
for mo in re.finditer(re_token, text, re.DOTALL):
kind = mo.lastgroup
if kind == 'SKIP':
pass
elif kind != 'MISMATCH':
value = mo.group(kind)
if value in keywords:
kind = value
if kind in names:
kind = names[kind]
tokens.append(Token(kind, value, mo.start()))
else:
raise TokenizeError(text, mo.start())
return tokens
def grammar(self):
"""The text grammar is used to create a parse tree out of a list of
tokens.
See :class:`~textparser.Parser` for an example usage.
"""
raise NotImplementedError('No grammar defined.')
def parse(self, text, token_tree=False, match_sof=False):
"""Parse given string `text` and return the parse tree. Raises
:class:`~textparser.ParseError` on failure.
Returns a parse tree of tokens if `token_tree` is ``True``.
.. code-block:: python
>>> MyParser().parse('Hello, World!')
['Hello', ',', 'World', '!']
>>> tree = MyParser().parse('Hello, World!', token_tree=True)
>>> from pprint import pprint
>>> pprint(tree)
[Token(kind='WORD', value='Hello', offset=0),
Token(kind=',', value=',', offset=5),
Token(kind='WORD', value='World', offset=7),
Token(kind='!', value='!', offset=12)]
"""
try:
tokens = self.tokenize(text)
if len(tokens) == 0 or tokens[-1].kind != '__EOF__':
tokens.append(Token('__EOF__', '__EOF__', len(text)))
if not match_sof:
if len(tokens) > 0 and tokens[0].kind == '__SOF__':
del tokens[0]
return Grammar(self.grammar()).parse(tokens, token_tree)
except (TokenizeError, GrammarError) as e:
raise ParseError(text, e.offset)
def replace_blocks(string, start='{', end='}'):
"""Replace all blocks starting with `start` and ending with `end` with
spaces (not including `start` and `end`).
"""
chunks = []
begin = 0
depth = 0
start_length = len(start)
pattern = r'({}|{})'.format(re.escape(start), re.escape(end))
for mo in re.finditer(pattern, string):
pos = mo.start()
if mo.group() == start:
if depth == 0:
chunks.append(string[begin:pos + start_length])
begin = (pos + start_length)
depth += 1
elif depth > 0:
depth -= 1
if depth == 0:
for chunk in string[begin:pos].split('\n'):
chunks.append(' ' * len(chunk))
chunks.append('\n')
chunks.pop()
begin = pos
chunks.append(string[begin:])
return ''.join(chunks)