-
Notifications
You must be signed in to change notification settings - Fork 0
/
pypeg.py
1474 lines (1273 loc) · 48.6 KB
/
pypeg.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
"""
pyPEG parsing framework
pyPEG offers a packrat parser as well as a framework to parse and output
languages for Python 2.7 and 3.x, see http://fdik.org/pyPEG2
Copyleft 2012, Volker Birk.
This program is under GNU General Public License 2.0.
"""
from __future__ import unicode_literals
try:
range = xrange
str = unicode
except NameError:
pass
__version__ = 2.15
__author__ = "Volker Birk"
__license__ = "This program is under GNU General Public License 2.0."
__url__ = "http://fdik.org/pyPEG"
import re
import sys
import weakref
if __debug__:
import warnings
from types import FunctionType
from collections import namedtuple
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
word = re.compile(r"\w+")
"""Regular expression for scanning a word."""
_RegEx = type(word)
restline = re.compile(r".*")
"""Regular expression for rest of line."""
whitespace = re.compile("(?m)\s+")
"""Regular expression for scanning whitespace."""
comment_sh = re.compile(r"\#.*")
"""Shell script style comment."""
comment_cpp = re.compile(r"//.*")
"""C++ style comment."""
comment_c = re.compile(r"(?ms)/\*.*?\*/")
"""C style comment without nesting comments."""
comment_pas = re.compile(r"(?ms)\(\*.*?\*\)")
"""Pascal style comment without nesting comments."""
def _card(n, thing):
# Reduce unnecessary recursions
if len(thing) == 1:
return n, thing[0]
else:
return n, thing
def some(*thing):
"""At least one occurrence of thing, + operator.
Inserts -2 as cardinality before thing.
"""
return _card(-2, thing)
def maybe_some(*thing):
"""No thing or some of them, * operator.
Inserts -1 as cardinality before thing.
"""
return _card(-1, thing)
def optional(*thing):
"""Thing or no thing, ? operator.
Inserts 0 as cardinality before thing.
"""
return _card(0, thing)
def _csl(separator, *thing):
# reduce unnecessary recursions
if len(thing) == 1:
L = [thing[0]]
L.extend(maybe_some(separator, blank, thing[0]))
return tuple(L)
else:
L = list(thing)
L.append(-1)
L2 = [separator, blank]
L2.extend(tuple(thing))
L.append(tuple(L2))
return tuple(L)
try:
# Python 3.x
_exec = eval("exec")
_exec('''
def csl(*thing, separator=","):
"""Generate a grammar for a simple comma separated list."""
return _csl(separator, *thing)
''')
except SyntaxError:
# Python 2.7
def csl(*thing):
"""Generate a grammar for a simple comma separated list."""
return _csl(",", *thing)
def attr(name, thing=word, subtype=None):
"""Generate an Attribute with that name, referencing the thing.
Instance variables:
Class Attribute class generated by namedtuple()
"""
# if __debug__:
# if isinstance(thing, (tuple, list)):
# warnings.warn(type(thing).__name__
# + " not recommended as grammar of attribute "
# + repr(name), SyntaxWarning)
return attr.Class(name, thing, subtype)
attr.Class = namedtuple("Attribute", ("name", "thing", "subtype"))
def flag(name, thing=None):
"""Generate an Attribute with that name which is valued True or False."""
if thing is None:
thing = Keyword(name)
return attr(name, thing, "Flag")
def attributes(grammar, invisible=False):
"""Iterates all attributes of a grammar."""
if type(grammar) == attr.Class and (invisible or grammar.name[0] != "_"):
yield grammar
elif type(grammar) == tuple:
for e in grammar:
for a in attributes(e, invisible):
yield a
class Whitespace(str):
grammar = whitespace
class RegEx(object):
"""Regular Expression.
Instance Variables:
regex pre-compiled object from re.compile()
"""
def __init__(self, value, **kwargs):
self.regex = re.compile(value, re.U)
self.search = self.regex.search
self.match = self.regex.match
self.split = self.regex.split
self.findall = self.regex.findall
self.finditer = self.regex.finditer
self.sub = self.regex.sub
self.subn = self.regex.subn
self.flags = self.regex.flags
self.groups = self.regex.groups
self.groupindex = self.regex.groupindex
self.pattern = value
for k, v in kwargs.items():
setattr(self, k, v)
def __str__(self):
return self.pattern
def __repr__(self):
result = type(self).__name__ + "(" + repr(self.pattern)
try:
result += ", name=" + repr(self.name)
except:
pass
return result + ")"
class Literal(object):
"""Literal value."""
_basic_types = (bool, int, float, complex, str, bytes, bytearray, list,
tuple, slice, set, frozenset, dict)
def __init__(self, value, **kwargs):
if isinstance(self, Literal._basic_types):
pass
else:
self.value = value
for k, v in kwargs.items():
setattr(self, k, v)
def __str__(self):
if isinstance(self, Literal._basic_types):
return super(Literal, self).__str__()
else:
return str(self.value)
def __repr__(self):
if isinstance(self, Literal._basic_types):
return type(self).__name__ + "(" + \
super(Literal, self).__repr__() + ")"
else:
return type(self).__name__ + "(" + repr(self.value) + ")"
def __eq__(self, other):
if isinstance(self, Literal._basic_types):
if type(self) == type(other) and super().__eq__(other):
return True
else:
return False
else:
if type(self) == type(other) and str(self) == str(other):
return True
else:
return False
class Plain(object):
"""A plain object"""
def __init__(self, name=None, **kwargs):
"""Construct a plain object with an optional name and optional other
attributes
"""
if name is not None:
self.name = Symbol(name)
for k, v in kwargs:
setattr(self, k, v)
def __repr__(self):
"""x.__repr__() <==> repr(x)"""
try:
return self.__class__.__name__ + "(name=" + repr(self.name) + ")"
except AttributeError:
return self.__class__.__name__ + "()"
class List(list):
"""A List of things."""
def __init__(self, *args, **kwargs):
"""Construct a List, and construct its attributes from keyword
arguments.
"""
_args = []
if len(args) == 1:
if isinstance(args[0], str):
self.append(args[0])
elif isinstance(args[0], (tuple, list)):
for e in args[0]:
if isinstance(e, attr.Class):
setattr(self, e.name, e.value)
else:
_args.append(e)
super(List, self).__init__(_args)
else:
raise ValueError("initializer of List should be collection or string")
else:
for e in args:
if isinstance(e, attr.Class):
setattr(self, e.name, e.value)
else:
_args.append(e)
super(List, self).__init__(_args)
for k, v in kwargs.items():
setattr(self, k, v)
def __repr__(self):
"""x.__repr__() <==> repr(x)"""
result = type(self).__name__ + "(" + super(List, self).__repr__()
try:
result += ", name=" + repr(self.name)
except:
pass
return result + ")"
def __eq__(self, other):
return super(List, self).__eq__(list(other))
class _UserDict(object):
# UserDict cannot be used because of metaclass conflicts
def __init__(self, *args, **kwargs):
self.data = dict(*args, **kwargs)
def __len__(self):
return len(self.data)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __delitem__(self, key):
del self.data[key]
def __iter__(self):
return self.data.keys()
def __contains__(self, item):
return item in self.data
def items(self):
return self.data.items()
def keys(self):
return self.data.keys()
def values(self):
return self.data.values()
def clear(self):
self.data.clear()
def copy(self):
return self.data.copy()
class Namespace(_UserDict):
"""A dictionary of things, indexed by their name."""
name_by = lambda value: "#" + str(id(value))
def __init__(self, *args, **kwargs):
"""Initialize an OrderedDict containing the data of the Namespace.
Arguments are being put into the Namespace, keyword arguments give the
attributes of the Namespace.
"""
if args:
self.data = OrderedDict(args)
else:
self.data = OrderedDict()
for k, v in kwargs.items():
setattr(self, k, v)
def __setitem__(self, key, value):
"""x.__setitem__(i, y) <==> x[i]=y"""
if key is None:
name = Symbol(Namespace.name_by(value))
else:
name = Symbol(key)
try:
value.name = name
except AttributeError:
pass
try:
value.namespace
except AttributeError:
try:
value.namespace = weakref.ref(self)
except AttributeError:
pass
else:
if not value.namespace:
value.namespace = weakref.ref(self)
super(Namespace, self).__setitem__(name, value)
def __delitem__(self, key):
"""x.__delitem__(y) <==> del x[y]"""
self[key].namespace = None
super(Namespace, self).__delitem__(key)
def __repr__(self):
"""x.__repr__() <==> repr(x)"""
result = type(self).__name__ + "(["
for key, value in self.data.items():
result += "(" + repr(key) + ", " + repr(value) + ")"
result += ", "
result += "]"
try:
result += ", name=" + repr(self.name)
except:
pass
return result + ")"
class Enum(Namespace):
"""A Namespace which is being treated as an Enum.
Enums can only contain Keywords or Symbols."""
def __init__(self, *things, **kwargs):
"""Construct an Enum using a tuple of things."""
self.data = OrderedDict()
for thing in things:
if type(thing) == str:
thing = Symbol(thing)
if not isinstance(thing, Symbol):
raise TypeError(repr(thing) + " is not a Symbol")
super(Enum, self).__setitem__(thing, thing)
for k, v in kwargs.items():
setattr(self, k, v)
def __repr__(self):
"""x.__repr__() <==> repr(x)"""
v = [e for e in self.values()]
result = type(self).__name__ + "(" + repr(v)
try:
result += ", name=" + repr(self.name)
except:
pass
return result + ")"
def __setitem__(self, key, value):
"""x.__setitem__(i, y) <==> x[i]=y"""
if not isinstance(value, Keyword) and not isinstance(value, Symbol):
raise TypeError("Enums can only contain Keywords or Symbols")
raise ValueError("Enums cannot be modified after creation.")
class Symbol(str):
"""Use to scan Symbols.
Class variables:
regex regular expression to scan, default r"\w+"
check_keywords flag if a Symbol is checked for not being a Keyword
default: False
"""
regex = word
check_keywords = False
def __init__(self, name, namespace=None):
"""Construct a Symbol with that name in Namespace namespace.
Raises:
ValueError if check_keywords is True and value is identical to
a Keyword
TypeError if namespace is given and not a Namespace
"""
if Symbol.check_keywords and name in Keyword.table:
raise ValueError(repr(name)
+ " is a Keyword, but is used as a Symbol")
if namespace:
if isinstance(namespace, Namespace):
namespace[name] = self
else:
raise TypeError(repr(namespace) + " is not a Namespace")
else:
self.name = name
self.namespace = None
def __repr__(self):
"""x.__repr__() <==> repr(x)"""
return type(self).__name__ + "(" + str(self).__repr__() + ")"
class Keyword(Symbol):
"""Use to access the keyword table.
Class variables:
regex regular expression to scan, default r"\w+"
table Namespace with keyword table
"""
regex = word
table = Namespace()
def __init__(self, keyword):
"""Adds keyword to the keyword table."""
if keyword not in Keyword.table:
Keyword.table[keyword] = self
self.name = keyword
K = Keyword
"""Shortcut for Keyword."""
class Concat(List):
"""Concatenation of things.
This class exists as a mutable alternative to using a tuple.
"""
def name():
"""Generate a grammar for a symbol with name."""
return attr("name", Symbol)
def ignore(grammar):
"""Ignore what matches to the grammar."""
try:
ignore.serial += 1
except AttributeError:
ignore.serial = 1
return attr("_ignore" + str(ignore.serial), grammar)
def indent(*thing):
"""Indent thing by one level.
Inserts -3 as cardinality before thing.
"""
return _card(-3, thing)
def contiguous(*thing):
"""Disable automated whitespace matching.
Inserts -4 as cardinality before thing.
"""
return _card(-4, thing)
def separated(*thing):
"""Enable automated whitespace matching.
Inserts -5 as cardinality before thing.
"""
return _card(-5, thing)
def omit(*thing):
"""Omit what matches to the grammar."""
return _card(-6, thing)
endl = lambda thing, parser: "\n"
"""End of line marker for composing text."""
blank = lambda thing, parser: " "
"""Space marker for composing text."""
class GrammarError(Exception):
"""Base class for errors in grammars."""
class GrammarTypeError(TypeError, GrammarError):
"""Raised if grammar contains an object of unkown type."""
class GrammarValueError(ValueError, GrammarError):
"""Raised if grammar contains an illegal value."""
def how_many(grammar):
"""Determines the possibly parsed objects of grammar.
Returns:
0 if there will be no objects
1 if there will be a maximum of one object
2 if there can be more than one object
Raises:
GrammarTypeError
if grammar contains an object of unkown type
GrammarValueError
if grammar contains an illegal cardinality value
"""
if grammar is None:
return 0
elif type(grammar) == int:
return grammar
elif _issubclass(grammar, Symbol) or isinstance(grammar, (RegEx, _RegEx)):
return 1
elif isinstance(grammar, (str, Literal)):
return 0
elif isinstance(grammar, attr.Class):
return 0
elif type(grammar) == FunctionType:
return 0
elif isinstance(grammar, (tuple, Concat)):
length, card = 0, 1
for e in grammar:
if type(e) == int:
if e < -6:
raise GrammarValueError(
"illegal cardinality value in grammar: " + str(e))
if e in (-5, -4, -3):
pass
elif e in (-1, -2):
card = 2
elif e == 0:
card = 1
elif e == -6:
return 0
else:
card = min(e, 2)
else:
length += card * how_many(e)
if length >= 2:
return 2
return length
elif isinstance(grammar, list):
m = 0
for e in grammar:
m = max(m, how_many(e))
if m == 2:
return m
return m
elif _issubclass(grammar, object):
return 1
else:
raise GrammarTypeError("grammar contains an illegal type: "
+ type(grammar).__name__ + ": " + repr(grammar))
def parse(text, thing, filename=None, whitespace=whitespace, comment=None,
keep_feeble_things=False):
"""Parse text following thing as grammar and return the resulting things or
raise an error.
Arguments:
text text to parse
thing grammar for things to parse
filename filename where text is origin from
whitespace regular expression to skip whitespace
default: regex "(?m)\s+"
comment grammar to parse comments
default: None
keep_feeble_things
put whitespace and comments into the .feeble_things
attribute instead of dumping them
Returns generated things.
Raises:
SyntaxError if text does not match the grammar in thing
ValueError if input does not match types
TypeError if output classes have wrong syntax for __init__()
GrammarTypeError
if grammar contains an object of unkown type
GrammarValueError
if grammar contains an illegal cardinality value
"""
parser = Parser()
parser.whitespace = whitespace
parser.comment = comment
parser.text = text
parser.filename = filename
parser.keep_feeble_things = keep_feeble_things
t, r = parser.parse(text, thing)
if t:
raise parser.last_error
return r
def compose(thing, grammar=None, indent=" ", autoblank=True):
"""Compose text using thing with grammar.
Arguments:
thing thing containing other things with grammar
grammar grammar to use to compose thing
default: thing.grammar
indent string to use to indent while composing
default: four spaces
autoblank add blanks if grammar would possibly be
violated otherwise
default: True
Returns text
Raises:
ValueError if input does not match grammar
GrammarTypeError
if grammar contains an object of unkown type
GrammarValueError
if grammar contains an illegal cardinality value
"""
parser = Parser()
parser.indent = indent
parser.autoblank = autoblank
return parser.compose(thing, grammar)
def _issubclass(obj, cls):
# If obj is not a class, just return False
try:
return issubclass(obj, cls)
except TypeError:
return False
class Parser(object):
"""Offers parsing and composing capabilities. Implements a Packrat parser.
Instance variables:
whitespace regular expression to scan whitespace
default: "(?m)\s+"
comment grammar to parse comments
last_error syntax error which ended parsing
indent string to use to indent while composing
default: four spaces
indention_level level to indent to
default: 0
text original text to parse; set for decorated syntax
errors
filename filename where text is origin from
autoblank add blanks while composing if grammar would possibly
be violated otherwise
default: True
keep_feeble_things put whitespace and comments into the .feeble_things
attribute instead of dumping them
"""
def __init__(self):
"""Initialize instance variables to their defaults."""
self.whitespace = whitespace
self.comment = None
self.last_error = None
self.indent = " "
self.indention_level = 0
self.text = None
self.filename = None
self.autoblank = True
self.keep_feeble_things = False
self._memory = {}
self._got_endl = True
self._contiguous = False
self._got_regex = False
def clear_memory(self, thing=None):
"""Clear cache memory for packrat parsing.
Arguments:
thing thing for which cache memory is cleared,
None if cache memory should be cleared for all
things
"""
if thing is None:
self._memory = {}
else:
try:
del self._memory[id(thing)]
except KeyError:
pass
def parse(self, text, thing, filename=None):
"""(Partially) parse text following thing as grammar and return the
resulting things.
Arguments:
text text to parse
thing grammar for things to parse
filename filename where text is origin from
Returns (text, result) with:
text unparsed text
result generated objects or SyntaxError object
Raises:
ValueError if input does not match types
TypeError if output classes have wrong syntax for __init__()
GrammarTypeError
if grammar contains an object of unkown type
GrammarValueError
if grammar contains an illegal cardinality value
"""
self.text = text
if filename:
self.filename = filename
pos = [1, 0]
t, skip_result = self._skip(text, pos)
t, r = self._parse(t, thing, pos)
if type(r) == SyntaxError:
raise r
else:
if self.keep_feeble_things and skip_result:
try:
r.feeble_things
except AttributeError:
try:
r.feeble_things = skip_result
except AttributeError:
pass
else:
r.feeble_things = skip_result + r.feeble_things
return t, r
def _skip(self, text, pos=None):
# Skip whitespace and comments from input text
t2 = None
t = text
result = []
while t2 != t:
if self.whitespace and not self._contiguous:
t, r = self._parse(t, Whitespace, pos)
if self.keep_feeble_things and r and not isinstance(r,
SyntaxError):
result.append(r)
t2 = t
if self.comment:
t, r = self._parse(t, self.comment, pos)
if self.keep_feeble_things and r and not isinstance(r,
SyntaxError):
result.append(r)
return t, result
def generate_syntax_error(self, msg, pos):
"""Generate a syntax error construct with
msg string with error message
pos (lineNo, charInText) with positioning information
"""
result = SyntaxError(msg)
if pos:
result.lineno = pos[0]
start = max(pos[1] - 19, 0)
end = min(pos[1] + 20, len(self.text))
result.text = self.text[start:end]
result.offset = pos[1] - start + 1
while "\n" in result.text:
lf = result.text.find("\n")
if lf >= result.offset:
result.text = result.text[:result.offset-1]
break;
else:
L = len(result.text)
result.text = result.text[lf+1:]
result.offset -= L - len(result.text)
if self.filename:
result.filename = self.filename
return result
def _parse(self, text, thing, pos=[1, 0]):
# Parser implementation
def update_pos(text, t, pos):
# Calculate where we are in the text
if not pos:
return
if text == t:
return
d_text = text[:len(text) - len(t)]
pos[0] += d_text.count("\n")
pos[1] += len(d_text)
try:
return self._memory[id(thing)][text]
except:
pass
if pos:
current_pos = tuple(pos)
else:
current_pos = None
def syntax_error(msg):
return self.generate_syntax_error(msg, pos)
try:
thing.parse
except AttributeError:
pass
else:
t, r = thing.parse(self, text, pos)
if not isinstance(r, SyntaxError):
t, skip_result = self._skip(t)
update_pos(text, t, pos)
if self.keep_feeble_things:
try:
r.feeble_things
except AttributeError:
try:
r.feeble_things = skip_result
except AttributeError:
pass
else:
r.feeble_things += skip_result
return t, r
skip_result = None
# terminal symbols
if thing is None or type(thing) == FunctionType:
result = text, None
elif isinstance(thing, Symbol):
m = type(thing).regex.match(text)
if m and m.group(0) == str(thing):
t, r = text[len(thing):], None
t, skip_result = self._skip(t)
result = t, r
update_pos(text, t, pos)
else:
result = text, syntax_error("expecting " + repr(thing))
elif isinstance(thing, (RegEx, _RegEx)):
m = thing.match(text)
if m:
t, r = text[len(m.group(0)):], m.group(0)
t, skip_result = self._skip(t)
result = t, r
update_pos(text, t, pos)
else:
result = text, syntax_error("expecting match on "
+ thing.pattern)
elif isinstance(thing, (str, Literal)):
if text.startswith(str(thing)):
t, r = text[len(str(thing)):], None
t, skip_result = self._skip(t)
result = t, r
update_pos(text, t, pos)
else:
result = text, syntax_error("expecting " + repr(thing))
elif _issubclass(thing, Symbol):
m = thing.regex.match(text)
if m:
result = None
try:
thing.grammar
except AttributeError:
pass
else:
if thing.grammar is None:
pass
elif isinstance(thing.grammar, Enum):
if not m.group(0) in thing.grammar:
result = text, syntax_error(repr(m.group(0))
+ " is not a member of " + repr(thing.grammar))
else:
raise GrammarValueError(
"Symbol " + type(thing).__name__
+ " has a grammar which is not an Enum: "
+ repr(thing.grammar))
if not result:
t, r = text[len(m.group(0)):], thing(m.group(0))
t, skip_result = self._skip(t)
result = t, r
update_pos(text, t, pos)
else:
result = text, syntax_error("expecting " + thing.__name__)
# non-terminal constructs
elif isinstance(thing, attr.Class):
t, r = self._parse(text, thing.thing, pos)
if type(r) == SyntaxError:
if thing.subtype == "Flag":
result = t, attr(thing.name, False)
else:
result = text, r
else:
if thing.subtype == "Flag":
result = t, attr(thing.name, True)
else:
result = t, attr(thing.name, r)
elif isinstance(thing, (tuple, Concat)):
if self.keep_feeble_things:
L = List()
else:
L = []
t = text
flag = True
_min, _max = 1, 1
contiguous = self._contiguous
omit = False
for e in thing:
if type(e) == int:
if e < -6:
raise GrammarValueError(
"illegal cardinality value in grammar: " + str(e))
if e == -6:
omit = True
elif e == -5:
self._contiguous = False
t, skip_result = self._skip(t)
if self.keep_feeble_things and skip_result:
try:
L.feeble_things
except AttributeError:
try:
L.feeble_things = skip_result
except AttributeError:
pass
else:
L.feeble_things += skip_result
elif e == -4:
self._contiguous = True
elif e == -3:
pass
elif e == -2:
_min, _max = 1, sys.maxsize
elif e == -1:
_min, _max = 0, sys.maxsize
elif e == 0:
_min, _max = 0, 1