-
Notifications
You must be signed in to change notification settings - Fork 0
/
sp.py
1273 lines (1090 loc) · 36.1 KB
/
sp.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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Simple Parser
# Copyright (C) 2009-2010 Christophe Delord
# http://cdsoft.fr/sp
""" Simple Parser
Simple Parser is a simple parser generator for Python.
Parsers are:
- recursive descendent: the rules are easy to read and understand
- written in pure Python: the rules are simple Python expressions
Parsers are made of Python classes and operators. A parser is a
Python expression that produces a callable object.
Example: a simple 4 operation calculator
----------------------------------------
>>> def calc_parser():
... def applyall(x, fs):
... for f in fs: x = f(x)
... return x
... num = R(r'\d+') / int
... with Separator(r'\s+'):
... expr = Rule()
... atom = num | '(' & expr & ')'
... fact = Rule()
... fact |= atom
... fact |= ('+' & fact) / (lambda x: +x)
... fact |= ('-' & fact) / (lambda x: -x)
... term = ( fact & ( ('*' & fact) / (lambda y: lambda x: x*y)
... | ('/' & fact) / (lambda y: lambda x: x/y)
... )[:]
... ) * applyall
... expr |= ( term & ( ('+' & term) / (lambda y: lambda x: x+y)
... | ('-' & term) / (lambda y: lambda x: x-y)
... )[:]
... ) * applyall
... return expr
>>> calc1 = calc_parser()
>>> calc1("1 + 2+3")
6
>>> calc1("1 + (2*3)")
7
>>> calc1("1 - (2*3)")
-5
Example: another calculator using the SP language
-------------------------------------------------
>>> from operator import add, sub, mul, truediv as div, mod
>>> op2 = lambda f, y: lambda x: f(x, y)
>>> op1 = lambda f, x: f(0, x)
>>> def red(x, fs):
... for f in fs: x = f(x)
... return x
>>> calc2 = compile(r'''
... number = number.r'\d+' : `int`;
... addop = '+' `add` | '-' `sub` ;
... mulop = '*' `mul` | '/' `div` | '%' `mod`;
...
... separator: r'\s+';
...
... !expr = term (addop term :: `op2`)* :: `red`;
... term = fact (mulop fact :: `op2`)* :: `red`;
... fact = addop fact :: `op1` | '(' expr ')' | number;
... ''')
>>> calc2("1 + 2+3")
6
>>> calc2("1 + (2*3)")
7
>>> calc2("1 - (2*3)")
-5
"""
__license__ = """
This file is part of Simple Parser.
Simple Parser is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Simple Parser is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Simple Parser. If not, see <http://www.gnu.org/licenses/>.
"""
import re
import sys
# "from sp import *" only imports objects for hand written parsers
__all__ = ['R', 'K', 'C', 'At', 'D', 'Rule', 'Separator']
class _Caches(list):
def add(self, cache):
self.append(cache)
def clear(self):
for cache in self:
cache.clear()
_caches = _Caches()
def clean():
""" clears the SP internal caches
>>> clean(); sum(len(cache) for cache in _caches) == 0
True
>>> with Separator(' '): p = K('A') | 'B'
>>> p('A')
nil
>>> p('B')
nil
>>> sum(len(cache) for cache in _caches) > 0
True
>>> clean(); sum(len(cache) for cache in _caches) == 0
True
"""
_caches.clear()
def _memoize_self_s_i(f):
""" creates a memoized parser method
arguments self, s and i are memoized.
"""
cache = {}
def _f(self, s, i):
try:
r = cache[self, s, i]
except KeyError:
r = cache[self, s, i] = f(self, s, i)
return r
_f.__doc__ = f.__doc__
_f.__name__ = f.__name__
_caches.add(cache)
return _f
def _memoize_self_s_i_e(f):
""" creates a memoized parser method
arguments self, s and i are memoized.
The error argument (e) is not indexed.
"""
cache = {}
def _f(self, s, i, e):
try:
r = cache[self, s, i]
except KeyError:
r = cache[self, s, i] = f(self, s, i, e)
return r
_f.__doc__ = f.__doc__
_f.__name__ = f.__name__
_caches.add(cache)
return _f
class _pos:
""" computes the position in a string
"""
def __init__(self, s, i):
self.index = i
self.line = s.count('\n', 0, i) + 1
self.column = i - s.rfind('\n', 0, i)
def __str__(self): return "[%d:%d]"%(self.line, self.column)
class _err:
""" stores the maximal position of the detected errors
"""
def __init__(self, i, *ts):
self.i = i
self.ts = tuple(ts)
def max(self, other):
if self.i > other.i:
return self
elif self.i < other.i:
return other
else:
return _err(self.i, *(self.ts + tuple(t for t in other.ts if t not in self.ts)))
def msg(self, s):
""" returns a message with the location of the error
>>> num = R('\d+')
>>> ident = R('\w+')
>>> begin = 'begin'
>>> with Separator('\s+'):
... s = begin & ( num | ident )
>>> s('18')
Traceback (most recent call last):
....
SyntaxError: [1:1] expected: begin...
>>> s('begin +18')
Traceback (most recent call last):
....
SyntaxError: [1:7] expected: \d+ \w+...
"""
p = _pos(s, self.i)
msg = "[%d:%d] expected:"%(p.line, p.column)
for t in self.ts:
if t.startswith(r'\b'): t = t[2:]
if t.endswith(r'\b'): t = t[:-2]
msg += " "+t
err = SyntaxError(msg)
err.lineno = p.line
return err
def _p(obj):
""" converts 'obj' to a parser object
A parser is not changed:
>>> word = K('Ham') | K('Spam')
>>> id(_p(word)) == id(word)
True
A string is translated into a single Keyword parser.
>>> num = _p(r'\d+')
>>> num.parse("42 43", 0, _err(0))[:2]
(fail, 0)
>>> num.parse(r"\d+ 42 43", 0, _err(0))[:2]
(nil, 3)
>>> kw = _p('foo')
>>> kw.parse("foo bar", 0, _err(0))[:2]
(nil, 3)
>>> kw.parse("foobar", 0, _err(0))[:2]
(fail, 0)
Other types raise an exception:
>>> _p(None)
Traceback (most recent call last):
...
TypeError: None is not a valid parser
"""
if isinstance(obj, Parser): return obj
if isinstance(obj, str): return K(obj)
raise TypeError("%s is not a valid parser"%obj)
class Parser:
""" A parser shall have a parse method that:
- trims separator before and after parsing (to allow different
separators in a single parser)
- recursively calls the child parsers
- returns a tuple (value, index, error) in case of success
if value is nil, it will be later ignored
- returns a tuple (fail, "initial index", error) in case of failure
error is the latest error detected.
"""
def __init__(self):
global _separator
self.separator = _separator
def __call__(self, s):
""" removes separators before and after parsing and returns the object parsed
>>> with Separator(r'\s+'):
... num = R('\d+') / int
... num[:](" 42 43 ")
[42, 43]
raises a SyntaxError exception when the string can not be parsed:
>>> num("\\nSpam")
Traceback (most recent call last):
...
SyntaxError: [2:1] expected: \d+...
or when their are remaining stuff not parseable:
>>> num("\\n\\n42\\n...")
Traceback (most recent call last):
...
SyntaxError: [4:1] expected:...
"""
i = self.skipsep(s, 0)
x, i, e = self.parse(s, i, _err(i))
i = self.skipsep(s, i)
if x is fail or i < len(s):
raise e.msg(s)
return x
@_memoize_self_s_i
def skipsep(self, s, i):
""" removes separators from a string
>>> with Separator(r'\s'):
... p = Parser()
>>> p.skipsep(" spam ", 0)
3
"""
if self.separator is None: return i
while True:
sep, i, e = self.separator.parse(s, i, _err(i))
if sep is fail: return i
def __and__(self, other):
""" returns a sequence parser
>>> with Separator(" "): ab = R("a") & "b"
>>> ab.parse("a b c", 0, _err(0))[:2]
('a', 4)
>>> ab.parse("b a c", 0, _err(0))[:2]
(fail, 0)
"""
return And(self, other)
def __rand__(self, other):
""" returns a sequence parser
>>> with Separator(" "): ab = "a" & R("b")
>>> ab.parse("a b c", 0, _err(0))[:2]
('b', 4)
>>> ab.parse("b a c", 0, _err(0))[:2]
(fail, 0)
"""
return And(other, self)
def __or__(self, other):
""" returns an alternative parser
>>> with Separator(" "): ab = R("a") | "b"
>>> ab.parse("a b c", 0, _err(0))[:2]
('a', 2)
>>> ab.parse("b a c", 0, _err(0))[:2]
(nil, 2)
>>> ab.parse("c a b", 0, _err(0))[:2]
(fail, 0)
"""
return Or(self, other)
def __ror__(self, other):
""" returns an alternative parser
>>> with Separator(" "): ab = "a" | R("b")
>>> ab.parse("a b c", 0, _err(0))[:2]
(nil, 2)
>>> ab.parse("b a c", 0, _err(0))[:2]
('b', 2)
>>> ab.parse("c a b", 0, _err(0))[:2]
(fail, 0)
"""
return Or(other, self)
def __getitem__(self, slice):
""" returns a repetition parser
Repetition is a slice:
- start is the minimal occurrence number (default is 0)
- stop is the maximal occurrence number (default is infinite)
- step is the separator between each object (default is no separator)
>>> with Separator('\s'):
... item = R(r'\d+') / int
>>> item[:].parse("1 2 3 4", 0, _err(0))[:2]
([1, 2, 3, 4], 7)
>>> item[:2].parse("1 2 3 4", 0, _err(0))[:2]
([1, 2], 4)
>>> item[::","].parse("1, 2, 3, 4", 0, _err(0))[:2]
([1, 2, 3, 4], 10)
"""
return Rep(self, slice.start, slice.stop, slice.step)
def __truediv__(self, func):
""" returns a parser that applies a function to the result of another parser
The argument of the function is a single object.
>>> sum = lambda xy: xy[0]+xy[1]
>>> num = R(r'\d+') / int # parses an integer
>>> add = (num & '+' & num) / sum # returns the sum of two integers
>>> add.parse("1+2+4", 0, _err(0))[:2]
(3, 3)
"""
return Apply(self, func)
# Python 2 fallback
if sys.version_info[0] < 3: __div__ = __truediv__
def __mul__(self, func):
""" returns a parser that applies a function to the result of another parser
The arguments of the function are in a list or a tuple,
each item being given to the function as a separate argument.
>>> sum = lambda x,y: x+y
>>> num = R(r'\d+') / int # parses an integer
>>> add = (num & '+' & num) * sum # returns the sum of two integers
>>> add.parse("1+2+4", 0, _err(0))[:2]
(3, 3)
"""
return ApplyStar(self, func)
class Separator:
""" defines the current separator
A classical usage is to define tokens outside a separator block
and rules inside a separator block (for instance to discard spaces and comments).
The separator is defined by a parser or a single string containing a regular expression.
It is designed to be used within a 'with' block:
>>> num = R(r'\d+')
>>> nums = num[:]
>>> nums.parse(" 42 43 ", 0, _err(0))[:2] # matches nothing at the very beginning of the input
([], 0)
>>> with Separator(r'\s'):
... nums = num[:]
>>> nums.parse(" 42 43 ", 0, _err(0))[:2] # can match numbers after discarding spaces
(['42', '43'], 7)
"""
def __init__(self, parser=None):
if isinstance(parser, str): parser = R(parser)
elif parser is not None: parser = _p(parser)
self.parser = parser
def __enter__(self):
global _separator
self.previous_parser = _separator
_separator = self.parser
def __exit__(self, type=None, value=None, traceback=None):
global _separator
_separator = self.previous_parser
_separator = None
class R(Parser):
""" is a single token parser
The token is defined by a regular expression.
The token returns the string matched by the regular expression.
>>> t = R(r'ham|spam')
>>> with Separator(r'\s'): t[:]("ham ham spam")
['ham', 'ham', 'spam']
If the regular expression defines groups, the parser returns
a tuple of these groups.
>>> t = R('<(\d+)-(\d+)>')
>>> t("<42-43>")
('42', '43')
If the regular expression defines only one group, the parser
returns the value of this group.
>>> t = R('<(\d+)-\d+>')
>>> t("<42-43>")
'42'
"""
def __init__(self, pattern, flags=0, name=None):
Parser.__init__(self)
self.pattern = name or pattern
self.re = re.compile(pattern, flags)
def parse(self, s, i, e):
i1 = self.skipsep(s, i)
token = self.re.match(s, i1)
if not token: return fail, i, e.max(_err(i1, self.pattern))
matched = token.group(0)
if token.lastindex:
value = token.groups()
if len(value) == 1: value = value[0]
else:
value = matched
rest = self.skipsep(s, i1 + len(matched))
return value, rest, e.max(_err(rest))
class K(R):
""" is a keyword parser
Works a bit as R.
If the pattern is a keyword (\w+)
word boundaries are expected around the token.
>>> t = K('ham') & C('ok')
>>> with Separator(r'\s'): t[:].parse("ham ham hammm", 0, _err(0))[:2]
(['ok', 'ok'], 8)
Otherwise the pattern is escaped.
>>> t = K('++') & C('pp')
>>> with Separator(r'\s'): t[:].parse("++ ++ +++", 0, _err(0))[:2]
(['pp', 'pp', 'pp'], 8)
"""
def __init__(self, pattern, flags=0, name=None):
Parser.__init__(self)
self.pattern = name or pattern
if pattern.isalnum(): pattern = r"\b%s\b"%pattern
else: pattern = re.escape(pattern)
self.re = re.compile(pattern, flags)
def parse(self, s, i, e):
obj, rest, e = R.parse(self, s, i, e)
if obj is fail: return fail, rest, e
else: return nil, rest, e
class C(Parser):
""" is a constant parser
C parses nothing, simply returns a constant.
>>> c = C('foo')
>>> c.parse("spam", 0, _err(0))[:2]
('foo', 0)
"""
def __init__(self, val):
Parser.__init__(self)
self.val = val
def parse(self, s, i, e):
i = self.skipsep(s, i)
return self.val, i, e.max(_err(i))
class At(Parser):
r""" returns the current position
>>> with Separator('\s'): p = K('a')[:] & At() & 'b'
>>> p = p * (lambda a, p: (p.index, p.line, p.column))
>>> p('b')
(0, 1, 1)
>>> p('\nb')
(1, 2, 1)
>>> p('a b')
(2, 1, 3)
>>> p('a\nb')
(2, 2, 1)
>>> p('a a b')
(4, 1, 5)
>>> p('a\na\nb')
(4, 3, 1)
"""
def parse(self, s, i, e):
i = self.skipsep(s, i)
return _pos(s, i), i, e.max(_err(i))
class D(Parser):
""" parses something and replaces the value by 'nil'
Used to discard some items returned by a sequence parser.
The sequence parser will ignore 'nil' items.
>>> num = R(r'\d+') / int
>>> expr = R(r'\(') & num & R(r'\)')
>>> expr("(42)")
('(', 42, ')')
>>> expr = D(R(r'\(')) & num & D(R(r'\)'))
>>> expr("(42)")
42
"""
def __init__(self, parser):
Parser.__init__(self)
self.parser = _p(parser)
def parse(self, s, i, e):
rest = self.skipsep(s, i)
x, rest, e = self.parser.parse(s, rest, e)
if x is fail: return fail, i, e.max(_err(rest))
rest = self.skipsep(s, rest)
return nil, rest, e.max(_err(rest))
class And(Parser):
""" parses a sequence.
Takes parsers as arguments.
If these arguments are also sequences, the sequence is flatten.
And(And(x,y),z) <=> And(x,And(y,z)) <=> And(x,y,z)
or (x & y) & z <=> x & (y & z) <=> x & y & z
The sequence returns a tuple containing the values returned by the subparsers.
>>> s = R('a') & R('b') & R('c')
>>> s("abc")
('a', 'b', 'c')
>>> s = (R('a') & R('b')) & R('c')
>>> s("abc")
('a', 'b', 'c')
>>> s = R('a') & (R('b') & R('c'))
>>> s("abc")
('a', 'b', 'c')
Arguments may return 'nil'. Their values will be ignored.
>>> s = R('a') & D(R('b')) & R('c')
>>> s("abc")
('a', 'c')
If the sequence returns only one argument, it is not returned in a tuple.
>>> s = D(R('a')) & D(R('b')) & R('c')
>>> s("abc")
'c'
"""
def __init__(self, *parsers):
Parser.__init__(self)
self.items = []
for parser in parsers:
if isinstance(parser, And): self.items.extend(parser.items)
else: self.items.append(_p(parser))
@_memoize_self_s_i_e
def parse(self, s, i, e):
tokens = []
rest = self.skipsep(s, i)
for item in self.items:
token, rest, e = item.parse(s, rest, e)
if token is fail: return fail, i, e.max(_err(rest))
if token is not nil: tokens.append(token)
rest = self.skipsep(s, rest)
if len(tokens) == 1: return tokens[0], rest, e.max(_err(rest))
return tuple(tokens), rest, e.max(_err(rest))
class _Singleton:
def __init__(self, name): self.name = name
def __repr__(self): return self.name
nil = _Singleton("nil")
fail = _Singleton("fail")
class Or(Parser):
""" parses an alternative.
Takes parsers as arguments.
If these arguments are also alternatives, the alternative is flatten.
Or(Or(x,y),z) <=> Or(x,Or(y,z)) <=> Or(x,y,z)
or (x | y) | z <=> x | (y | z) <=> x | y | z
The alternative returns the value returns by the first longest matching subparser.
>>> s = R('a') | R('b') | R('c')
>>> s("b")
'b'
>>> s = (R('a') | R('b')) | R('c')
>>> s("b")
'b'
>>> s = R('a') | (R('b') | R('c'))
>>> s("b")
'b'
>>> s = R('a')[:] | R('b')[:]
>>> s('aa')
['a', 'a']
>>> s('bb')
['b', 'b']
>>> s('')
[]
>>> s('ba')
Traceback (most recent call last):
...
SyntaxError: [1:2] expected: b...
>>> s = R('a')[:] & C('branch 1') | R('a')[:] & R('b')[:] & C('branch 2')
>>> s('aa')
(['a', 'a'], 'branch 1')
>>> s('aab')
(['a', 'a'], ['b'], 'branch 2')
"""
def __init__(self, *parsers):
Parser.__init__(self)
self.items = []
for parser in parsers:
if isinstance(parser, Or): self.items.extend(parser.items)
else: self.items.append(_p(parser))
@_memoize_self_s_i_e
def parse(self, s, i, e):
i1 = self.skipsep(s, i)
e = e.max(_err(i1))
longest = (None, -1)
for item in self.items:
token, rest, e = item.parse(s, i1, e)
if token is not fail:
rest = self.skipsep(s, rest)
e = e.max(_err(rest))
if rest > longest[1]:
longest = (token, rest)
if longest[1] > -1:
# Returns the longest match
return longest + (e,)
else:
return fail, i, e
class Rule(Parser):
""" returns an empty parser that can be later enriched.
Used to define recursive rules.
The symbol can be used even before the rule is defined.
Alternatives are added by the |= operator.
>>> As = Rule()
>>> A = R('A')
>>> As |= A & As
>>> As |= C(())
>>> As("AAA")
('A', ('A', ('A', ())))
"""
def __init__(self):
Parser.__init__(self)
self.parser = None
def __ior__(self, parser):
if self.parser is None: self.parser = _p(parser)
else: self.parser = Or(self.parser, parser)
return self
def parse(self, s, i, e):
i1 = self.skipsep(s, i)
x, rest, e = self.parser.parse(s, i1, e)
if x is fail: return fail, i, e.max(_err(rest))
rest = self.skipsep(s, rest)
return x, rest, e.max(_err(rest))
class Rep(Parser):
""" parses repetitions.
Arguments:
min is the minimal number of iterations (default is 0)
max is the maximal number of iterations (default is infinite)
step is the separator parser (default is none)
Classical repetition can be coded this way:
A* <=> A[:] (zero or more A)
A+ <=> A[1:] (one or more A)
A? <=> A[:1] (zero or one A)
>>> A = R('A')
>>> As = A[:]
>>> As('')
[]
>>> As('A')
['A']
>>> As('AAA')
['A', 'A', 'A']
>>> As = A[1:]
>>> As('')
Traceback (most recent call last):
...
SyntaxError: [1:1] expected: A...
>>> As('A')
['A']
>>> As('AAA')
['A', 'A', 'A']
>>> As = A[:1]
>>> As('')
[]
>>> As('A')
['A']
>>> As('AAA')
Traceback (most recent call last):
...
SyntaxError: [1:2] expected:...
The separator provides a convenient way to parse comma separated lists for instance.
>>> t = R(r'\w')
>>> lst = t[::',']
>>> lst("a,b,c")
['a', 'b', 'c']
"""
def __init__(self, parser, min, max, sep):
Parser.__init__(self)
self.parser = parser
if min is None: min = 0
if max is None: max = -1
self.min = min
self.max = max
if sep is None: self.parse = self._parse_no_sep
else:
self.parse = self._parse_with_sep
self.sep = _p(sep)
def _parse_no_sep(self, s, i, e):
items = []
n = 0
rest = self.skipsep(s, i)
while n != self.max:
n += 1
item, rest, e = self.parser.parse(s, rest, e)
if item is fail:
if n <= self.min: return fail, i, e.max(_err(rest))
return items, rest, e.max(_err(rest))
items.append(item)
rest = self.skipsep(s, rest)
return items, rest, e.max(_err(rest))
def _parse_with_sep(self, s, i, e):
rest = self.skipsep(s, i)
item, rest, e = self.parser.parse(s, rest, e)
if item is fail:
if 1 <= self.min: return fail, i, e.max(_err(rest))
rest = self.skipsep(s, rest)
return [], rest, e.max(_err(rest))
items = [item]
n = 1
rest = self.skipsep(s, rest)
while n != self.max:
n += 1
sep, rest, e = self.sep.parse(s, rest, e)
if sep is fail:
if n <= self.min: return fail, i, e.max(_err(rest))
return items, rest, e.max(_err(rest))
rest = self.skipsep(s, rest)
item, rest, e = self.parser.parse(s, rest, e)
if item is fail:
if n <= self.min: return fail, i, e.max(_err(rest))
return items, rest, e.max(_err(rest))
items.append(item)
rest = self.skipsep(s, rest)
return items, rest, e.max(_err(rest))
class Apply(Parser):
""" applies a function to the result of a parser
The function has one argument.
>>> num = Apply(R(r'\d+'), int)
>>> a = Apply(num, int)
>>> a("42")
42
>>> a = Apply(num&','&num&','&num, (lambda xs: xs[0]+xs[1]+xs[2]))
>>> a("1,2,3")
6
"""
def __init__(self, parser, func):
Parser.__init__(self)
self.parser = _p(parser)
self.func = func
def parse(self, s, i, e):
i1 = self.skipsep(s, i)
token, rest, e = self.parser.parse(s, i1, e)
if token is fail: return fail, i, e.max(_err(rest))
rest = self.skipsep(s, rest)
return self.func(token), rest, e.max(_err(rest))
class ApplyStar(Apply):
""" applies a function to the result of some parsers
The function may have several arguments.
>>> num = Apply(R(r'\d+'), int)
>>> a = ApplyStar(num&','&num&','&num, (lambda x,y,z: x+y+z))
>>> a("1,2,3")
6
>>> a = ApplyStar(num[::','], (lambda *xs: sum(xs)))
>>> a("1,2,3")
6
"""
def parse(self, s, i, e):
i1 = self.skipsep(s, i)
token, rest, e = self.parser.parse(s, i1, e)
if token is fail: return fail, i, e.max(_err(rest))
rest = self.skipsep(s, rest)
return self.func(*token), rest, e.max(_err(rest))
def _compile_string(source, frame):
r""" defines a parser from a grammar
Token definition
----------------
>>> test = compile('''
... name = r'\w+' ;
... !S = name ;
... ''')
>>> test('foo')
'foo'
>>> test(':foo')
Traceback (most recent call last):
...
SyntaxError: [1:1] expected: \w+...
With specific lexer options:
>>> test = compile('''
... lexer: VERBOSE, IGNORECASE;
... string = r" ' ( [^']* ) ' ";
... lexer: IGNORECASE;
... begin = "begin";
... !S = string | begin;
... ''')
>>> test("'this is a string'")
'this is a string'
>>> test("BeGiN")
nil
Keyword definition
------------------
>>> test = compile('''
... kw = 'begin' ;
... !S = kw ;
... ''')
>>> test('begin')
nil
>>> test('end')
Traceback (most recent call last):
...
SyntaxError: [1:1] expected: begin...
Position computation
--------------------
>>> test = compile('''
... separator: r'\s+';
... !S = 'a'* @ 'b' :: `lambda a, p: (p.index, p.line, p.column)`;
... ''')
>>> test('b')
(0, 1, 1)
>>> test('\nb')
(1, 2, 1)
>>> test('a b')
(2, 1, 3)
>>> test('a\nb')
(2, 2, 1)
>>> test('a a b')
(4, 1, 5)
>>> test('a\na\nb')
(4, 3, 1)
Repetitions
-----------
>>> test = compile('''
... separator: ' ' ;
... item = r'\w+' ;
... !S = item* ;
... ''')
>>> test(' ')
[]
>>> test(' abc ')
['abc']
>>> test(' abc def ')
['abc', 'def']
>>> test(' abc def ghi')
['abc', 'def', 'ghi']
>>> test = compile('''
... separator: ' ' ;
... item = r'\w+' ;
... !S = item+ ;
... ''')
>>> test(' ')
Traceback (most recent call last):
...
SyntaxError: [1:2] expected: \w+...
>>> test(' abc ')
['abc']
>>> test(' abc def ')
['abc', 'def']
>>> test(' abc def ghi')
['abc', 'def', 'ghi']
>>> test = compile('''
... separator: ' ' ;
... item = r'\w+' ;
... !S = item? ;
... ''')
>>> test(' ')
[]
>>> test(' abc ')
['abc']
>>> test(' abc def ')
Traceback (most recent call last):
...
SyntaxError: [1:6] expected:...
>>> test = compile('''
... separator: ' ';
... item = r'\w+';
... !S = [item / ',']*;
... ''')
>>> test(' ')
[]
>>> test('a')
['a']
>>> test('a, b')
['a', 'b']
>>> test('a, b, c')
['a', 'b', 'c']
>>> test = compile('''
... separator: ' ';
... item = r'\w+';
... !S = [item / ',']+;
... ''')
>>> test(' ')
Traceback (most recent call last):
...
SyntaxError: [1:2] expected: \w+...