-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparsec4.py
1388 lines (1112 loc) · 41 KB
/
parsec4.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
# -*- coding: utf-8 -*-
import typing
from typing import *
"""
#
# This is an expansion of parsec 3.3 by He Tao. Changes include:
#
# Added Explanatory comments.
# Provided more natural English grammar for He Tao's comments. His comments
# are included. New comments are marked with a preceding and following group
# of three # characters, and the original docstrings use triple single quotes
# rather than triple double quotes.
# To the extent practical, alphabetized the functions.
# Inserted type hints.
# Added a __bool__ function to the Value class.
# Changed some string searches to exploit constants in string module rather
# than str functions that might be affected by locale.**
# Changed name of any() function to any_char() to avoid conflicts with
# Python built-in of the same name.
# Where practical, f-strings are used for formatting.
# Revised for modern Python; no longer compatible with Python 2. This version
# requires Python 3.8.
# A number of definitions of characters are provided, and they
# are named as standard symbols: TAB, NL, CR, etc.
# Many custom parsers are likely to include parsers for common programming
# elements (dates, IP addresses, timestamps). These are now included.
# There are two versions of the `string` parser. The new version consumes
# no input on failure. The older version can be activated by defining
# the environment variable PARSEC3_STRING. The value is unimportant; it
# only needs to be defined.
#
# ** A note on the use of the import statement. The import near the top of the
# file imports string, and creates an entry in the system modules table
# named 'string'. The use of the import statement inside the parser functions
# merely references this already imported module's index in the sys.modules
# table.
#
"""
###
# Credits
###
__author__ = 'George Flanagin'
__credits__ = """
He Tao, [email protected] --- original version
Alina Enikeeva, [email protected] --- documentation and testing
"""
__copyright__ = 'Copyright 2023'
__version__ = 4.0
__maintainer__ = "George Flanagin"
__email__ = ['[email protected]', '[email protected]']
__status__ = 'in progress'
__license__ = 'MIT'
###########################################################################
"""
A universal Python parser combinator library inspired by Parsec library of Haskell.
"""
min_py = (3, 8)
###
# Standard imports, starting with os and sys
###
import os
import sys
if sys.version_info < min_py:
print(f"This program requires Python {min_py[0]}.{min_py[1]}, or higher.")
sys.exit(os.EX_SOFTWARE)
###
# Other standard distro imports
###
from collections import namedtuple
from collections.abc import Callable
from collections.abc import Iterable
import datetime
from functools import wraps
import re
import string
import warnings
##########################################################################
# SECTION 0: Constants
##########################################################################
TAB = '\t'
CR = '\r'
NL = '\n'
LF = '\n'
VTAB = '\f'
BSPACE = '\b'
QUOTE1 = "'"
QUOTE2 = '"'
QUOTE3 = "`"
LBRACE = '{'
RBRACE = '}'
LBRACK = '['
RBRACK = ']'
COLON = ':'
COMMA = ','
SEMICOLON = ';'
BACKSLASH = '\\'
UNDERSCORE = '_'
OCTOTHORPE = '#'
CIRCUMFLEX = '^'
EMPTY_STR = ""
SLASH = '/'
PLUS = '+'
MINUS = '-'
STAR = '*'
EQUAL = '='
DOLLAR = '$'
AT_SIGN = '@'
BANG = '!'
PERCENT = '%'
##########################################################################
# SECTION 1: Parsec.Error
##########################################################################
class ParseError(RuntimeError):
"""
This exception is raised at the first unrecoverable syntax error.
"""
def __init__(self, expected:str, text:str, index:tuple):
"""
expected -- the text that should be present.
text -- the text that was found.
index -- where in the current text shred the error is located.
"""
self.expected = expected
self.text = text
self.index = index
@staticmethod
def loc_info(text:object, index:int) -> tuple:
'''
Location of `index` in source code `text`.
'''
if index > len(text):
raise ValueError('Invalid index.')
if isinstance(text, str):
line, last_ln = text.count('\n', 0, index), text.rfind('\n', 0, index)
else:
line, last_ln = 0, index
col = index - (last_ln + 1)
return (line, col)
def loc(self) -> int:
'''
Locate the error position in the source code text.
'''
try:
return '{}'.format(*ParseError.loc_info(self.text, self.index))
except ValueError:
return f'<out of bounds index {self.index}>'
def __str__(self) -> str:
"""
This function allows us to meaningfully print the exception.
"""
return f'expected: {self.expected} at {self.loc}'
##########################################################################
# SECTION 2: Definition the Value model.
##########################################################################
class Value: pass
class Value(namedtuple('Value', 'status index value expected')):
"""
Value represents the result of the Parser. namedtuple is a little bit of
difficult beast, adding as much syntactic complexity as it removes.
Here the types are:
status -- bool
index -- int
value -- object
expected -- str
"""
@staticmethod
def success(index:int, actual:object) -> Value:
"""
Factory to create success Value.
"""
return Value(True, index, actual, None)
@staticmethod
def failure(index:int, expected:object) -> Value:
"""
Factory to create failure Value.
"""
return Value(False, index, None, expected)
def aggregate(self, other:Value=None) -> Value:
'''
Collect the furthest failure from self and other.
'''
if not self.status: return self
if not other: return self
if not other.status: return other
return Value(True, other.index, self.value + other.value, None)
def update_index(self, index:int=None) -> Value:
"""
Change the index, and return a new object.
"""
return ( self
if index is None else
Value(self.status, index, self.value, self.expected)
)
@staticmethod
def combinate(values:Iterable) -> Value:
'''
TODO: rework this one.
Aggregate multiple values into tuple
'''
prev_v = None
for v in values:
if prev_v:
if not v:
return prev_v
if not v.status:
return v
out_values = tuple(v.value for v in values)
return Value(True, values[-1].index, out_values, None)
def __bool__(self) -> bool:
"""
This function allows for checking the status with an "if" before
the Value object. Merely syntax sugar for neater code.
"""
return bool(self.status)
def __str__(self) -> str:
"""
To allow for well-behaved printing.
"""
return f'Value: {self.status=}, {self.index=}, {self.value=}, {self.expected=}'
##########################################################################
# SECTION 3: The Parser decorator.
##########################################################################
class Parser: pass
class Parser:
'''
A Parser is an object that wraps a function to do the parsing work.
Arguments of the function should be a string to be parsed and the index on
which to begin parsing. Parser is intended to be used as a decorator.
The function should return either Value.success(next_index, value) if
parsing successfully, or Value.failure(index, expected) on the failure.
'''
def __init__(self, fn:Callable):
'''
fn -- is the function to wrap.
'''
self.fn = fn
def __call__(self, text:str, index:int) -> Value:
'''
call wrapped function.
'''
return self.fn(text, index)
def parse(self, text:str):
'''
text -- the text to be parsed.
'''
return self.parse_partial(text)[0]
def parse_partial(self, text:str) -> tuple:
'''
Parse the longest possible prefix of a given string.
Return a tuple of the result value and the rest of the string.
If failed, raise a ParseError.
'''
result = self(text, 0)
if result.status:
return result.value, text[result.index:]
raise ParseError(result.expected, text, result.index)
def parse_strict(self, text:str) -> Value:
'''
Parse the longest possible prefix of the entire given string. If the
parser worked successfully and NONE text was rested, return the
result value, else raise a ParseError.
The difference between `parse` and `parse_strict` is that the entire
given text must be used for the event to be construed as a success.
'''
# Note that < is not the gt operator, but the unconsumed end
# parser of the text shred.
return (self < eof()).parse_partial(text)[0]
def bind(self, fn:Callable) -> Parser:
'''
This is the monadic binding operation. Returns a parser which, if
parser is successful, passes the result to fn, and continues with the
parser returned from fn.
'''
@Parser
def bind_parser(text:str, index:int):
result = self(text, index)
return result if not result.status else fn(result.value)(text, result.index)
return bind_parser
def compose(self, other:Parser):
'''
(>>) Sequentially compose two actions, discarding any value produced
by the first.
'''
@Parser
def compose_parser(text:str, index:int):
result = self(text, index)
return result if not result.status else other(text, result.index)
return compose_parser
def joint(self, *parsers:Iterable):
'''
(+) Joint two or more parsers into one. Return the aggregate of two results
from this two parser.
'''
return joint(self, *parsers)
def choice(self, other:Parser) -> Value:
'''
(|) This combinator implements choice. The parser p | q first applies p.
- If it succeeds, the value of p is returned.
- If p fails **without consuming any input**, parser q is tried.
NOTICE: without backtrack.
'''
@Parser
def choice_parser(text:str, index:int):
result = self(text, index)
return result if result.status or result.index != index else other(text, index)
return choice_parser
def try_choice(self, other:Parser) -> Value:
'''
(^) Choice with backtrack. This combinator is used whenever arbitrary
look ahead is needed. The parser p ^ q first applies p, if it success,
the value of p is returned. If p fails, it pretends that it hasn't consumed
any input, and then parser q is tried.
'''
@Parser
def try_choice_parser(text:str, index:int):
result = self(text, index)
return result if result.status else other(text, index)
return try_choice_parser
def skip(self, other:Parser) -> Value:
'''
(<<) Ends with a specified parser, discarding any result from
the parser on the RHS. Typical uses might be discarding
whitespace that follows a parsed token:
a_parser << whitespace_parser
'''
@Parser
def skip_parser(text:str, index:int):
res = self(text, index)
if not res.status:
return res
end = other(text, res.index)
if end.status:
return Value.success(end.index, res.value)
else:
return Value.failure(end.index, f'ends with {end.expected}')
return skip_parser
def ends_with(self, other:Parser) -> Value:
'''
(<) Ends with a specified parser, and at the end parser hasn't consumed
any input. Typical use is with EOF, or similar.
'''
@Parser
def ends_with_parser(text:str, index:int):
res = self(text, index)
if not res.status:
return res
end = other(text, res.index)
if end.status:
return res
else:
return Value.failure(end.index, f'ends with {end.expected}')
return ends_with_parser
def excepts(self, other:Parser) -> Parser:
'''
(/) In other parser libraries, this is sometimes called the notFollowedBy
parser. In the expression p / q, p is considered to be successful only if
p succeeds, and q fails.
'''
@Parser
def excepts_parser(text, index):
res = self(text, index)
if not res.status:
return res
lookahead = other(text, res.index)
if lookahead.status:
return Value.failure(res.index, f'should not be "{lookahead.value}"')
else:
return res
return excepts_parser
def parsecmap(self, fn:Callable) -> Parser:
'''
Returns a parser that transforms the result of the current parsing
operation by invoking fn on the result. For example, if you wanted
to transform the result from a text shred to an int, you would
call xxxxxx.parsecmap(int). Note the *two* lambda functions.
'''
return self.bind(
lambda result: Parser(
lambda _, index: Value.success(index, fn(result))
)
)
def parsecapp(self, other:Parser) -> Parser:
'''
Returns a parser that applies the produced value of this parser
to the produced value of `other`.
'''
return self.bind(
lambda res: other.parsecmap(
lambda x: res(x)
)
)
def result(self, result:Value) -> Value:
'''
Return a value according to the parameter res when parse successfully.
'''
return self >> Parser(lambda _, index: Value.success(index, result))
def mark(self):
'''
Mark the line and column information of the result of this parser.
'''
def pos(text:str, index:int):
return ParseError.loc_info(text, index)
@Parser
def mark_parser(text:str, index:int):
res = self(text, index)
return ( Value.success(res.index, (pos(text, index), res.value, pos(text, res.index)))
if res.status else res )
return mark_parser
def desc(self, description):
'''
Describe a parser, when it failed, print out the description text.
'''
return self | Parser(lambda _, index: Value.failure(index, description))
###
# SECTION 3A: This section assigns function names to the overloaded operators.
###
def __or__(self, other:Parser):
'''Implements the `(|)` operator, means `choice`.'''
return self.choice(other)
def __xor__(self, other:Parser):
'''Implements the `(^)` operator, means `try_choice`.'''
return self.try_choice(other)
def __add__(self, other:Parser):
'''Implements the `(+)` operator, means `joint`.'''
return self.joint(other)
def __rshift__(self, other:Parser):
'''Implements the `(>>)` operator, means `compose`.'''
return self.compose(other)
def __gt__(self, other:Parser):
'''Implements the `(>)` operator, means `compose`.'''
return self.compose(other)
def __irshift__(self, other:Parser):
'''Implements the `(>>=)` operator, means `bind`.'''
warnings.warn("Operator >>= is deprecated. Use >= instead.",
category=DeprecationWarning)
return self.bind(other)
def __ge__(self, other:Parser):
'''Implements the `(>=)` operator, means `bind`.'''
return self.bind(other)
def __lshift__(self, other:Parser):
'''Implements the `(<<)` operator, means `skip`.'''
return self.skip(other)
def __lt__(self, other:Parser):
'''Implements the `(<)` operator, means `ends_with`.'''
return self.ends_with(other)
def __truediv__(self, other:Parser):
'''Implements the `(/)` operator, means `excepts`.'''
return self.excepts(other)
###
# SECTION 4: In this section, along with parse(), we have some of
# the class member functions exposed to the outside primarily for
# notational flexibility.
##
def bind(p, fn:Callable) -> Parser:
'''
Bind two parsers, implements the operator of `(>=)`.
'''
return p.bind(fn)
def choice(pa:Parser, pb:Parser):
'''
Choice one from two parsers, implements the operator of `(|)`.
'''
return pa.choice(pb)
def compose(pa:Parser, pb:Parser) -> Parser:
'''
Compose two parsers, implements the operator of `(>>)`, or `(>)`.
'''
return pa.compose(pb)
def desc(p, description):
'''
Describe a parser, when it failed, print out the description text.
'''
return p.desc(description)
def ends_with(pa, pb):
'''
Ends with a specified parser, and at the end parser hasn't consumed any input.
Implements the operator of `(<)`.
'''
return pa.ends_with(pb)
def excepts(pa, pb):
'''
Fail `pa` though matched when the consecutive parser `pb` success for the rest text.
'''
return pa.excepts(pb)
def joint(*parsers):
'''
Joint two or more parsers, implements the operator of `(+)`.
'''
@Parser
def joint_parser(text:str, index:int):
values = []
prev_v = None
for p in parsers:
if prev_v:
index = prev_v.index
prev_v = v = p(text, index)
if not v.status:
return v
values.append(v)
return Value.combinate(values)
return joint_parser
def mark(p:Parser):
'''
Mark the line and column information of the result of the parser `p`.
'''
return p.mark()
def parse(p:Parser, text:str, index:int=0) -> Value:
'''
Parse a string and return the result or raise a ParseError.
'''
return p.parse(text[index:])
def parsecapp(p:Parser, other:Parser) -> Parser:
'''
Returns a parser that applies the produced value of this parser to the produced
value of `other`.
There should be an operator `(<*>)`, but that is impossible in Python.
'''
return p.parsecapp(other)
def parsecmap(p:Parser, fn:Callable) -> Parser:
'''
Returns a parser that transforms the produced value of parser with `fn`.
'''
return p.parsecmap(fn)
def result(p:Parser, res:Value) -> Value:
'''
Return a value according to the parameter `res` when parse successfully.
'''
return p.result(res)
def skip(pa:Parser, pb:Parser) -> Parser:
'''
Ends with a specified parser, and at the end parser consumed the end flag.
Implements the operator of `(<<)`.
'''
return pa.skip(pb)
def try_choice(pa:Parser, pb:Parser) -> Parser:
'''
Choice one from two parsers with backtrack, implements the operator of `(^)`.
'''
return pa.try_choice(pb)
##########################################################################
# SECTION 5: The Parser Factory.
#
# The most powerful way to construct a parser is to use the @generate decorator.
# @generate creates a parser from a generator that should yield parsers.
# These parsers are applied successively and their results are sent back to the
# generator using `.send()` protocol. The generator should return the result or
# another parser, which is equivalent to applying it and returning its result.
#
# For an explanation of the .send() protocol, see the text in section 6.2.9.1
# of the official Python documentation.
#
# https://docs.python.org/3/reference/expressions.html
##########################################################################
def generate(fn:Callable) -> Parser:
'''
Parser generator. (combinator syntax).
'''
if isinstance(fn, str):
return lambda f: generate(f).desc(fn)
@wraps(fn)
@Parser
def generated(text:str, index:int) -> Value:
iterator, value = fn(), None
try:
while True:
parser = iterator.send(value)
res = parser(text, index)
if not res.status: # this parser failed.
return res
value, index = res.value, res.index # iterate
except StopIteration as stop:
###
# This is the successful termination of the parser.
# Note that we catch anything *derived* from StopIteration.
###
endval = stop.value
if isinstance(endval, Parser):
return endval(text, index)
else:
return Value.success(index, endval)
except RuntimeError as error:
###
# This is the real error.
###
stop = error.__cause__
endval = stop.value
if isinstance(endval, Parser):
return endval(text, index)
else:
return Value.success(index, endval)
return generated.desc(fn.__name__)
##########################################################################
# SECTION 6: Repeaters.
##########################################################################
def times(p:Parser, min_times:int, max_times:int=0) -> list:
'''
Repeat a parser between min_times and max_times
Execute it, and return a list containing whatever
was collected.
'''
max_times = min_times if not max_times else max_times
@Parser
def times_parser(text:str, index:int) -> Parser:
cnt, values, res = 0, [], None
while cnt < max_times:
res = p(text, index)
if res.status:
if max_times == sys.maxsize and res.index == index:
break
values.append(res.value)
index, cnt = res.index, cnt + 1
else:
if cnt >= min_times:
break
else:
return res # failed, throw exception.
if cnt >= max_times: # finish.
break
###
# If we don't have any remaining text to start next loop, we need break.
#
# We cannot put the `index < len(text)` in where because some parser can
# success even when we have no any text. We also need to detect if the
# parser consume no text.
###
if index >= len(text):
if cnt >= min_times:
break # we already have decent result to return
else:
r = p(text, index)
if index != r.index: # report error when the parser cannot success with no text
return Value.failure(index, "already at the end; no more input")
return Value.success(index, values)
return times_parser
def count(p:Parser, n:int) -> list:
'''
`count p n` parses n occurrences of p. If n is smaller or equal to zero,
the parser equals to return []. Returns a list of n values returned by p.
'''
return times(p, n, n)
def optional(p:Parser, default_value=None):
'''
Make a parser as optional. If success, return the result, otherwise return
default_value silently, without raising any exception. If default_value is not
provided None is returned instead.
'''
@Parser
def optional_parser(text:str, index:int) -> Value:
res = p(text, index)
if res.status:
return Value.success(res.index, res.value)
else:
# Return the maybe existing default value without doing anything.
return Value.success(index, default_value)
return optional_parser
def many(p) -> list:
'''
Repeat a parser 0 to infinity times. Return a list of the values
collected. This function is just a convenience, as it calls times.
'''
return times(p, 0, sys.maxsize)
def many1(p:Parser) -> list:
'''
Repeat a parser 1 to infinity times. Return a list of the values
collected. This function is just a convenience, as it calls times.
Note that it does error out if p fails to execute at least once.
'''
return times(p, 1, sys.maxsize)
###
# NOTE: the following parsers are useful for expressions in
# a language that appear like this: a, b, c, d
# Most languages have these.
###
def separated(p:Parser, sep:str, min_times:int, max_times:int=0, end=None) -> list:
'''
Repeat a parser `p` separated by `s` between `min_times` and `max_times` times.
If max_times is omitted, max_times becomes min_times, effectively
executing `p` exactly min_times.
- When `end` is None, a trailing separator is optional (default).
- When `end` is True, a trailing separator is required.
- When `end` is False, a trailing separator will not be parsed.
This algorithm is greedy, and does not give back; i.e., it is like the
splat (*) in regular expressions.
Return list of values returned by `p`.
'''
max_times = min_times if not max_times else max_times
@Parser
def sep_parser(text, index):
cnt, values_index, values, res = 0, index, [], None
while cnt < max_times:
res = p(text, index)
if res.status:
current_value_index = res.index
current_value = res.value
index, cnt = res.index, cnt + 1
else:
if cnt < min_times:
return res # error: need more elements, but no `p` found.
else:
return Value.success(values_index, values)
# consume the sep
res = sep(text, index)
if res.status: # `sep` found, consume it (advance index)
index = res.index
if end in [True, None]:
current_value_index = res.index
else:
if cnt < min_times or (cnt == min_times and end is True):
return res # error: need more elements, but no `sep` found.
else:
if end is True:
# step back
return Value.success(values_index, values)
else:
values_index = current_value_index
values.append(current_value)
return Value.success(values_index, values)
# record the new value
values_index = current_value_index
values.append(current_value)
return Value.success(values_index, values)
return sep_parser
def sepBy(p:Parser, sep:str) -> list:
'''
`sepBy(p, sep)` parses zero or more occurrences of p, separated by `sep`.
Returns a list of values returned by `p`.
'''
return separated(p, sep, 0, max_times=sys.maxsize, end=False)
def sepBy1(p:Parser, sep:str) -> list:
'''
`sepBy1(p, sep)` parses one or more occurrences of `p`, separated by
`sep`. Returns a list of values returned by `p`.
'''
return separated(p, sep, 1, max_times=sys.maxsize, end=False)
def endBy(p:Parser, sep:str) -> list:
'''
`endBy(p, sep)` parses zero or more occurrences of `p`, separated and
ended by `sep`. Returns a list of values returned by `p`.
'''
return separated(p, sep, 0, max_times=sys.maxsize, end=True)
def endBy1(p:Parser, sep:str) -> list:
'''
`endBy1(p, sep) parses one or more occurrences of `p`, separated and
ended by `sep`. Returns a list of values returned by `p`.
'''
return separated(p, sep, 1, max_times=sys.maxsize, end=True)
def sepEndBy(p:Parser, sep:str) -> list:
'''
`sepEndBy(p, sep)` parses zero or more occurrences of `p`, separated and
optionally ended by `sep`. Returns a list of
values returned by `p`.
'''
return separated(p, sep, 0, max_times=sys.maxsize)
def sepEndBy1(p:Parser, sep:str) -> list:
'''
`sepEndBy1(p, sep)` parses one or more occurrences of `p`, separated and
optionally ended by `sep`. Returns a list of values returned by `p`.
'''
return separated(p, sep, 1, max_times=sys.maxsize)
##########################################################################
# SECTION 7: Prebuilt parsers for common operations.
##########################################################################
def any_char() -> Parser:
'''
Note the change in name in this version. This function was named any(), but
any is a Python built in.
'''
@Parser
def any_parser(text:str, index=0) -> Parser:
if index < len(text):
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'a random char')
return any_parser
def one_of(s:str) -> Parser:
'''
Parses a char from specified string.
'''
@Parser
def one_of_parser(text:str, index=0) -> Parser:
if index < len(text) and text[index] in s:
return Value.success(index + 1, text[index])
else:
return Value.failure(index, f'one of {s}')
return one_of_parser
def none_of(s) -> Parser:
'''
Parses a char NOT from specified string.
'''
@Parser
def none_of_parser(text, index=0) -> Value:
if index < len(text) and text[index] not in s:
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'none of {}'.format(s))
return none_of_parser
def space() -> Parser:
'''
Parses a whitespace character.
'''
@Parser
def space_parser(text, index=0) -> Value:
import string
if index < len(text) and text[index] in string.whitespace:
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'one space')
return space_parser