-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path__init__.py
1977 lines (1617 loc) · 64.6 KB
/
__init__.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 argparse, codecs, unicodedata, regex as regexlib
from ply import lex, yacc
from collections import namedtuple, deque
try:
unicode
except NameError: # python 3
unicode = str
def oprex(source_code):
source_lines = sanitize(source_code)
lexer = build_lexer(source_lines)
result = parse(lexer=lexer)
cleanup(lexer=lexer)
return result
class OprexError(Exception):
def __init__(self, lineno, msg):
msg = msg.replace('\t', ' ')
if lineno:
msg = 'Line %d: %s' % (lineno, msg)
Exception.__init__(self, '\n' + msg)
class OprexSyntaxError(OprexError): pass
class OprexInternalError(OprexError): pass
def sanitize(source_code):
# oprex requires the source code to have leading and trailing blank lines to make
# "proper look of indentation" when it is a triple-quoted string
def is_blank_or_comments_only(line):
non_comments = line.split('--')[0]
return non_comments.strip() == ''
source_lines = regexlib.split('\r?\n', source_code)
first_line = source_lines[0]
last_line = source_lines[-1]
if not is_blank_or_comments_only(first_line):
raise OprexSyntaxError(1, 'First line must be blank, not: ' + first_line)
if not is_blank_or_comments_only(last_line):
raise OprexSyntaxError(len(source_lines), 'Last line must be blank, not: ' + last_line)
# at this point, first and last lines are ensured to be blanks/comments only
# we'll make them really empty so regex-for-comments does not need take into consideration first/last-line comments
source_lines[0] = source_lines[-1] = ''
return source_lines
states = (
('CHARCLASS', 'exclusive'),
('LOOKAROUND', 'inclusive'),
('ORBLOCK', 'inclusive'),
)
LexToken = namedtuple('LexToken', 'type value lineno lexpos lexer')
ExtraToken = lambda t, type, value=None, lexpos=None: LexToken(type, value or t.value, t.lexer.lineno, lexpos or t.lexpos, t.lexer)
reserved = {
'_' : 'UNDERSCORE',
'__' : 'DOUBLEUNDERSCORE',
'not' : 'NOT',
}
tokens = [
'AT',
'BAR',
'BEGIN_LOOKAROUND',
'BEGIN_ORBLOCK',
'CHAR',
'COLON',
'DEDENT',
'DOT',
'END_OF_LOOKAROUND',
'END_OF_ORBLOCK',
'EQUALSIGN',
'EXCLAMARK',
'FAIL',
'FLAGSET',
'GLOBALMARK',
'GT',
'INDENT',
'NUMBER',
'LBRACKET',
'LPAREN',
'LT',
'MINUS',
'NEWLINE',
'NON',
'OF',
'PLUS',
'QUESTMARK',
'RBRACKET',
'RPAREN',
'SLASH',
'STRING',
'VARNAME',
'WHITESPACE',
] + list(reserved.values())
GLOBALMARK = '*)'
t_AT = r'\@'
t_BAR = r'\|'
t_DOT = r'\.'
t_EQUALSIGN = r'\='
t_EXCLAMARK = r'\!'
t_GT = r'\>'
t_LBRACKET = r'\['
t_LPAREN = r'\('
t_LT = r'\<'
t_MINUS = r'\-'
t_NUMBER = r'\d+'
t_PLUS = r'\+'
t_QUESTMARK = r'\?'
t_RBRACKET = r'\]'
t_RPAREN = r'\)'
t_SLASH = r'\/'
t_ignore = '' # oprex is whitespace-significant, no ignored characters
ESCAPE_SEQUENCE_RE = regexlib.compile(r'''\\
( N\{[^}]++\} # Unicode character name
| U\d{8} # 8-digit hex escapes
| u\d{4} # 4-digit hex escapes
| x\d{2} # 2-digit hex escapes
| [0-7]{1,3} # Octal escapes
| .
)''', regexlib.VERBOSE)
OVERESCAPED_RE = regexlib.compile(r'''\\\\
( \\\\ # Escaped backslash
| ['"abfnrtv] # Single-character escapes
| N\\\{[^}]++\} # Unicode character name
| U\d{8} # 8-digit hex escapes
| u\d{4} # 4-digit hex escapes
| x\d{2} # 2-digit hex escapes
| [0-7]{1,3} # Octal escapes
)''', regexlib.VERBOSE)
class Variable(namedtuple('Variable', 'name value lineno')):
__slots__ = ()
def is_builtin(self):
return self.lineno == 0
class VariableDeclaration(object):
__slots__ = ('varname', 'lineno', 'capture')
def __init__(self, varname, lineno, capture):
self.varname = varname
self.lineno = lineno
self.capture = capture
class VariableLookup(object):
__slots__ = ('varname', 'lineno', 'optional', 'next_lookup_in_chain')
def __init__(self, varname, lineno, optional):
self.varname = varname
self.lineno = lineno
self.optional = optional
self.next_lookup_in_chain = None
def resolve(self, scope, lexer):
if self.varname in scope:
return self.get_value(scope)
elif self.varname in lexer.ongoing_declarations:
lexer.ongoing_declarations[self.varname].capture = True
return Regex(self.varname, modifier='(?&')
else:
raise OprexSyntaxError(self.lineno, "'%s' is not defined" % self.varname)
def get_value(self, scope):
value = scope[self.varname].value
if isinstance(value, NumRangeRegex) and self.next_lookup_in_chain is not None:
# the numrange is followed by something, so we can strip out the (?!\d) check
return value[:-len(r'(?!\d)')]
else:
return value
class NegatedLookup(VariableLookup):
def resolve(self, scope, lexer):
try:
return scope['non-' + self.varname].value
except KeyError:
value = VariableLookup.resolve(self, scope, lexer)
if isinstance(value, CharClass):
return value.negated()
else:
raise OprexSyntaxError(self.lineno, "'non-%s': '%s' is not a character-class" % (self.varname, self.varname))
class Backreference(VariableLookup):
def resolve(self, scope, lexer):
return Regex(self.varname, modifier='(?P=')
class MatchUntil(VariableLookup):
def resolve(self, scope, lexer):
value = '.'
limiter = self.next_lookup_in_chain
if isinstance(limiter, VariableLookup):
limiter_value = limiter.resolve(scope, lexer)
if isinstance(limiter_value, CharClass):
value = limiter_value.negated()
elif isinstance(limiter_value, StringLiteral):
prefixed = limiter_value[:2] in (r'\b', r'\B')
if prefixed:
prefix = limiter_value[:2]
limiter_value = limiter_value[2:]
if limiter_value != '':
if limiter_value.startswith('\\'):
first_char = ESCAPE_SEQUENCE_RE.match(limiter_value).group(0)
else:
first_char = limiter_value[0]
first_char_negated = CharClass(first_char, is_set_op=False).negated()
rest = limiter_value[len(first_char):]
if not rest and not prefixed: # limiter_value is single-char, note that e.g. \N{FULL STOP} is counted as single char
value = first_char_negated
else:
value = '%s++' % first_char_negated
if prefixed:
value += '|(?<!%s)%s' % (prefix, first_char)
if rest:
value += '|%s(?!%s)' % (first_char, rest)
value = '(?:%s)' % value
return Regex(value, modifier='+?' if value =='.' else '++')
class CaptureCondition(namedtuple('CaptureCondition', 'varname lineno')):
__slots__ = ()
class Quantifier(namedtuple('Quantifier', 'base modifier')):
__slots__ = ()
class Assignment(namedtuple('Assignment', 'declarations value lineno')):
__slots__ = ()
class Block(namedtuple('Block', 'variables starting_lineno')):
__slots__ = ()
def check_unused_vars(self, useds):
for var in self.variables:
if var.name == 'wordchar':
if self.variables.index(var) > 0:
raise OprexSyntaxError(var.lineno, 'Redefining wordchar: must be the first/before any other definition')
else: # varname not wordchar
if var.name not in useds:
raise OprexSyntaxError(var.lineno, "'%s' is defined but not used (by its parent expression)" % var.name)
class Scope(dict):
types = ('ROOTSCOPE', 'BLOCKSCOPE', 'FLAGSCOPE')
ROOTSCOPE, BLOCKSCOPE, FLAGSCOPE = tuple(range(3))
__slots__ = ('starting_lineno', 'type')
def __init__(self, type, starting_lineno, parent_scope):
self.starting_lineno = starting_lineno
self.type = type
if parent_scope:
self.update(parent_scope)
class Flagset(unicode):
__slots__ = ('turn_ons', 'turn_offs')
all_flags = {}
scopeds = {
'dotall' : 's',
'fullcase' : 'f',
'ignorecase' : 'i',
'multiline' : 'm',
'verbose' : 'x',
'word' : 'w',
}
globals = {
'ascii' : 'a',
'bestmatch' : 'b',
'enhancematch' : 'e',
'locale' : 'L',
'reverse' : 'r',
'unicode' : 'u',
'version0' : 'V0',
'version1' : 'V1',
}
def __new__(cls, turn_ons, turn_offs):
if turn_offs:
flags = turn_ons + '-' + turn_offs
else:
flags = turn_ons
flagset = unicode.__new__(cls, flags)
flagset.turn_ons = turn_ons
flagset.turn_offs = turn_offs
return flagset
Flagset.all_flags.update(Flagset.scopeds)
Flagset.all_flags.update(Flagset.globals)
class Expr:
def __init__(self, **attribs):
self.__dict__.update(attribs)
def apply(self, scope):
# return regex, references
raise NotImplemented
class Regex(unicode):
__slots__ = ('base_value', 'grouped', 'quantifier')
def __new__(cls, base_value, modifier=None): # modifier can be one of: quantifier, scoped flags, or grouping
value = base_value
grouped = False
quantifier = None
if modifier:
if modifier.startswith('(?'): # scoped flags/grouping -- without the closing paren
value = modifier + base_value + ')' # add the closing paren
grouped = True
else: # modifier is quantifier
quantifier = modifier
value += quantifier
expr = unicode.__new__(cls, value)
expr.base_value = base_value
expr.grouped = grouped
expr.quantifier = quantifier
return expr
def apply(self, scope):
return self, []
class Alternation(Regex):
__slots__ = ('items', 'grouping_unnecessary')
def __new__(cls, items, is_atomic):
alternation = Regex.__new__(cls, '|'.join(items), modifier='(?>' if is_atomic else None)
alternation.items = items
alternation.grouping_unnecessary = is_atomic or len(items) == 1
return alternation
class StringLiteral(Regex):
pass
class NumRangeRegex(Regex):
pass
class CharClass(Regex):
__slots__ = ('is_set_op',)
escapes = {
'[' : '\\[',
']' : '\\]',
'^' : '\\^',
'-' : '\\-',
'\\' : '\\\\',
}
def __new__(cls, value, is_set_op):
if value.startswith('[') and value.endswith(']') and value != '[ ]':
if len(value) == 3 or ESCAPE_SEQUENCE_RE.fullmatch(value[1:-1]):
value = value[1:-1]
if len(value) == 1:
value = regexlib.escape(value, special_only=True)
value = {
r'[^\d]' : r'\D',
r'[^\D]' : r'\d',
r'[^\s]' : r'\S',
r'[^\S]' : r'\s',
r'[^\w]' : r'\W',
r'[^\W]' : r'\w',
r'[^\$]' : r'[^$]',
r'[^\.]' : r'[^.]',
r'[^\|]' : r'[^|]',
r'[^\?]' : r'[^?]',
r'[^\*]' : r'[^*]',
r'[^\+]' : r'[^+]',
r'[^\(]' : r'[^(]',
r'[^\)]' : r'[^)]',
r'[^\{]' : r'[^{]',
r'[^\}]' : r'[^}]',
r'\-' : '-',
}.get(value, value)
charclass = Regex.__new__(cls, value)
charclass.is_set_op = is_set_op
return charclass
def negated(self):
if self.startswith('[^'):
negated_value = self.replace('[^', '[', 1)
elif self.startswith('['):
negated_value = self.replace('[', '[^', 1)
elif self.startswith(r'\p{'):
negated_value = self.replace(r'\p{', r'\P{', 1)
elif self.startswith(r'\P{'):
negated_value = self.replace(r'\P{', r'\p{', 1)
elif self == '-':
negated_value = r'[^\-]'
else:
negated_value = '[^%s]' % self
return CharClass(value=negated_value, is_set_op=self.is_set_op)
class CCItem(namedtuple('CCItem', 'source type value')):
__slots__ = ()
op_types = ('unary', 'binary')
UNARY_OP, BINARY_OP = tuple(range(2))
@staticmethod
def token(t, type, value):
source = t.value
if type not in ('include', 'op'): # testing these types requires parser context
try:
regexlib.compile('[' + value + ']')
except regexlib.error as e:
raise OprexSyntaxError(t.lineno,
'%s compiles to %s which is rejected by the regex engine with error message: %s' % (source, value, str(e)))
t.type = 'CHAR'
t.value = CCItem(source, type, value)
return t
Builtin = lambda name, value, modifier=None: Variable(name, Regex(value, modifier=modifier), lineno=0)
BuiltinCC = lambda name, value: Variable(name, CharClass(value, is_set_op=False), lineno=0)
BUILTINS = [
BuiltinCC('alpha', r'[a-zA-Z]'),
BuiltinCC('upper', r'[A-Z]'),
BuiltinCC('lower', r'[a-z]'),
BuiltinCC('alnum', r'[a-zA-Z0-9]'),
BuiltinCC('padchar', r'[ \t]'),
BuiltinCC('backslash', r'\\'),
BuiltinCC('tab', r'\t'),
BuiltinCC('digit', r'\d'),
BuiltinCC('whitechar', r'\s'),
BuiltinCC('wordchar', r'\w'),
Builtin('BOW', r'\m'),
Builtin('EOW', r'\M'),
Builtin('WOB', r'\b'),
Builtin('non-WOB', r'\B'),
Builtin('BOS', r'\A'),
Builtin('EOS', r'\Z'),
Builtin('uany', r'\X'),
Builtin('FAIL!', '', modifier='(?!'),
]
FLAG_DEPENDENT_BUILTINS = dict(
m = { # MULTILINE
True : [
Builtin('BOL', '^'),
Builtin('EOL', '$'),
],
False : [
Builtin('BOL', '^', modifier='(?m:'),
Builtin('EOL', '$', modifier='(?m:'),
],
},
s = { # DOTALL
True : [
Builtin('any', '.'),
Builtin('non-linechar', '.', modifier='(?-s:'),
],
False : [
Builtin('any', '.', modifier='(?s:'),
Builtin('non-linechar', '.'),
],
},
w = { # WORD
True : [
BuiltinCC('linechar', r'[\r\n\x0B\x0C]'),
],
False : [
BuiltinCC('linechar', r'\n'),
],
},
x = { # VERBOSE
True : [
BuiltinCC('space', '[ ]'),
],
False : [
BuiltinCC('space', ' '),
],
},
)
DEFAULT_FLAGS = 'w'
for flag in FLAG_DEPENDENT_BUILTINS:
for var in FLAG_DEPENDENT_BUILTINS[flag][flag in DEFAULT_FLAGS]:
BUILTINS.append(var)
def flags_redef_builtins(flags, flag_dependent_builtins, scope):
for flag in FLAG_DEPENDENT_BUILTINS:
if flag in flags:
for var in flag_dependent_builtins[flag][flag in flags.turn_ons]:
scope[var.name] = var
def t_COLON(t):
r''':'''
t.lexer.start_mode('CHARCLASS')
return t
def t_CHARCLASS_DOT(t):
r'''\.'''
return t
def t_CHARCLASS_op(t):
r'''not:|not\b|and\b'''
return CCItem.token(t, 'op', {
'not:' : '^',
'not' : '--',
'and' : '&&',
}[t.value])
def t_CHARCLASS_varname(t):
r'''\w{2,}'''
return CCItem.token(t, 'include', VariableLookup(t.value, t.lineno, optional=False))
def t_CHARCLASS_include(t):
r'''\+\w+'''
return CCItem.token(t, 'include', VariableLookup(t.value[1:], t.lineno, optional=False))
def t_CHARCLASS_prop(t):
r'''/\w+(=\w+)?'''
return CCItem.token(t, 'prop', '\p{%s}' % t.value[1:])
def t_CHARCLASS_name(t):
r''':[\w-]+'''
return CCItem.token(t, 'name', r'\N{%s}' % t.value[1:].replace('_', ' '))
def t_CHARCLASS_escape(t):
r'''(?x)\\
( [\\abfnrtv] # Single-character escapes
| N\{[^}]+\} # Unicode character name
| U[a-fA-F\d]{8} # 8-digit hex escapes
| u[a-fA-F\d]{4} # 4-digit hex escapes
| x[a-fA-F\d]{2} # 2-digit hex escapes
| [0-7]{1,3} # Octal escapes
)(?=[\s.])'''
return CCItem.token(t, 'escape', t.value)
def t_CHARCLASS_bad_escape(t):
r'''\\\S+'''
raise OprexSyntaxError(t.lineno, 'Bad escape sequence: ' + t.value)
def t_CHARCLASS_literal(t):
r'''\S'''
return CCItem.token(t, 'literal', CharClass.escapes.get(t.value, t.value))
def t_FLAGSET(t):
r'\([- \t\w]+\)'
flags = t.value[1:-1] # exclude the surrounding ( )
flags = flags.split(' ') # will contain empty strings in case of consecutive spaces, so...
flags = [flag for flag in flags if flag] # ...exclude empty strings
turn_ons = ''
turn_offs = ''
for flag in flags:
try:
if flag.startswith('-'):
turn_offs += Flagset.all_flags[flag[1:]]
else:
turn_ons += Flagset.all_flags[flag]
except KeyError:
raise OprexSyntaxError(t.lineno, "Unknown flag '%s'. Supported flags are: %s" % (flag, ' '.join(sorted(Flagset.all_flags.keys()))))
flags = Flagset(turn_ons, turn_offs)
try:
test = '(?%s)' % flags
if 'V' in flags:
regexlib.compile(test)
else:
regexlib.compile('(?V1)' + test)
except Exception as e:
raise OprexSyntaxError(t.lineno, '%s compiles to %s which is rejected by the regex engine with error message: %s' %
(t.value, test, str(e)))
else:
t.type = 'LPAREN'
t.extra_tokens = [ExtraToken(t, 'FLAGSET', value=flags), ExtraToken(t, 'RPAREN')]
return t
def t_BEGIN_LOOKAROUND(t):
r'''<@>'''
if t.lexer.mode != 'INITIAL':
raise OprexSyntaxError(t.lineno, t.lexer.mode + ' cannot contain LOOKAROUND')
t.lexer.start_mode('LOOKAROUND')
t.lexer.barpos = None
t.lexer.lookaround_parent_indent_depth = t.lexer.indent_stack[-1]
return t
def t_BEGIN_ORBLOCK(t):
r'''(<<\|)|(@\|)'''
if t.lexer.mode != 'INITIAL':
raise OprexSyntaxError(t.lineno, t.lexer.mode + ' cannot contain ORBLOCK')
t.lexer.start_mode('ORBLOCK')
t.lexer.barpos = find_column(t) + len(t.value) - 1
return t
def restore_overescaped(match):
match = match.group(1)
if match.startswith('N'):
charname = match[3:-2]
unicodedata.lookup(charname) # raise KeyError if undefined character name
return '\\N{' + charname + '}'
else:
return {
'a' : '\\x07',
'b' : '\\x08',
'f' : '\\x0C',
'v' : '\\x0B',
}.get(match, '\\' + match)
def t_STRING(t):
r'''("(\\.|[^"\\])*")|('(\\.|[^'\\])*')''' # single- or double-quoted string, with escape-quote support
value = t.value[1:-1] # remove the surrounding quotes
value = value.replace('\\"', '"').replace("\\'", "'") # apply escaped quotes
value = regexlib.escape(value, special_only=True)
try:
t.value = OVERESCAPED_RE.sub(restore_overescaped, value)
except KeyError as e:
raise OprexSyntaxError(t.lineno, str(e)[1:-1])
else:
return t
## NON and FAIL must be before VARNAME otherwise VARNAME will be produced instead
def t_NON(t):
'non-'
return t
def t_FAIL(t):
'FAIL!'
return t
def t_VARNAME(t):
r'[A-Za-z_][A-Za-z0-9_]*'
t.type = reserved.get(t.value, 'VARNAME')
return t
# Rules that contain space/tab should be written in function form and be put
# before the t_linemark rule to make PLY calls them first.
# Otherwise t_linemark will turn the spaces/tabs into WHITESPACE token.
def t_INITIAL_ORBLOCK_OF(t):
r'[ \t]+of(?=[ \t:])(?![ \t]+(--|\n))' # without this, WHITESPACE VARNAME will be produced instead, requiring making "of" a reserved keyword
t.type = 'WHITESPACE'
t.extra_tokens = [ExtraToken(t, 'OF', lexpos=t.lexpos + t.value.index('of'))]
return t
def t_ANY_comments_whitespace(t):
r'''(?mx)
(
[ \t\n]+
(--.*)? # comments
)+
(
\*\) # globalmark
[ \t]*
)*
'''
lines = t.value.split('\n')
indentation = lines[-1]
is_finale = endpos(t) == len(t.lexer.lexdata)
if is_finale: # effectively no indentation
indentation = ''
has_globalmark = GLOBALMARK in indentation
num_newlines = len(lines) - 1
has_empty_line = num_newlines > 1
t.lexer.lineno += num_newlines
t.extra_tokens = []
def add_extras():
if add_extras.END_OF_ORBLOCK:
t.extra_tokens.append(ExtraToken(t, 'END_OF_ORBLOCK'))
if add_extras.END_OF_LOOKAROUND:
t.extra_tokens.append(ExtraToken(t, 'END_OF_LOOKAROUND'))
if add_extras.INDENT:
t.extra_tokens.append(ExtraToken(t, 'INDENT'))
for _ in range(add_extras.DEDENT):
t.extra_tokens.append(ExtraToken(t, 'DEDENT'))
if add_extras.GLOBALMARK:
t.extra_tokens.append(ExtraToken(t, 'GLOBALMARK', GLOBALMARK))
add_extras.END_OF_ORBLOCK = False
add_extras.END_OF_LOOKAROUND = False
add_extras.INDENT = False
add_extras.DEDENT = 0
add_extras.GLOBALMARK = False
if num_newlines == 0:
if GLOBALMARK in t.value: # globalmark must be put at the beginning of a line, i.e. requires newline
raise OprexSyntaxError(t.lexer.lineno, 'Syntax error: ' + t.lexer.source_lines[t.lexer.lineno-1])
else:
t.type = 'WHITESPACE'
return t
# else, num_newlines > 0
t.type = 'NEWLINE'
t.value = '\n'
if t.lexer.mode == 'CHARCLASS': # NEWLINE ends the charclass-mode
t.lexer.end_mode('CHARCLASS')
if is_finale or has_empty_line: # empty line ends ORBLOCK/LOOKAROUND
if t.lexer.mode == 'ORBLOCK':
add_extras.END_OF_ORBLOCK = True
t.lexer.end_mode('ORBLOCK')
elif t.lexer.mode == 'LOOKAROUND':
add_extras.END_OF_LOOKAROUND = True
t.lexer.end_mode('LOOKAROUND')
def check_indentation_char():
if indentation == GLOBALMARK:
raise OprexSyntaxError(t.lexer.lineno, 'Syntax error: ' + indentation)
indent_using_space = ' ' in indentation
indent_using_tab = '\t' in indentation
if indent_using_space and indent_using_tab:
raise OprexSyntaxError(t.lexer.lineno, 'Cannot mix space and tab for indentation')
indentchar = ' ' if indent_using_space else '\t'
try: # all indentations must use the same character
if indentchar != t.lexer.indentchar:
raise OprexSyntaxError(t.lexer.lineno, 'Inconsistent indentation character')
except AttributeError: # this is the first indent encountered, record whether it uses space or tab -- further indents must use the same character
t.lexer.indentchar = indentchar
def strip_globalmark():
if indentation.count(GLOBALMARK) > 1:
raise OprexSyntaxError(t.lexer.lineno, 'Syntax error: ' + indentation)
if not indentation.startswith(GLOBALMARK):
raise OprexSyntaxError(t.lexer.lineno, "The GLOBALMARK %s must be put at the line's beginning" % GLOBALMARK)
return indentation.replace(GLOBALMARK, ' ' if t.lexer.indentchar == ' ' else '')
def produce_INDENT_DEDENT():
indentlen = len(indentation)
prev = t.lexer.indent_stack[-1]
if indentlen == prev: # no change in indentation depth
return
# else, there's indentation depth change
if indentlen > prev: # deeper indentation, start of a new scope
add_extras.INDENT = True
t.lexer.indent_stack.append(indentlen)
return
if indentlen < prev: # end of one or more scopes
while indentlen < prev: # close all scopes having deeper indentation
add_extras.DEDENT += 1
t.lexer.indent_stack.pop()
prev = t.lexer.indent_stack[-1]
if indentlen != prev: # the indentation tries to return to a nonexistent level
raise OprexSyntaxError(t.lexer.lineno, 'Indentation error')
if indentation:
check_indentation_char()
if has_globalmark:
add_extras.GLOBALMARK = True
indentation = strip_globalmark()
if t.lexer.mode == 'INITIAL':
produce_INDENT_DEDENT()
add_extras()
return t
def t_ANY_error(t):
raise OprexSyntaxError(t.lineno, 'Syntax error at or near: ' + t.value.split('\n')[0])
def endpos(t):
return t.lexpos + len(t.value)
def p_oprex(t):
'''oprex :
| WHITESPACE
| NEWLINE
| NEWLINE root_expression
| NEWLINE INDENT root_expression DEDENT'''
if len(t) == 3:
flags, expression = t[2]
elif len(t) == 5:
flags, expression = t[3]
else:
flags = expression = ''
for flag in DEFAULT_FLAGS:
if flag not in flags:
flags = flag + flags
if 'V' not in flags: # use V1 by default
flags = 'V1' + flags # put at the front so it can easily be trimmed-out if unwanted
t[0] = '(?%s)%s' % (flags, expression)
def p_root_expression(t):
'''root_expression : global_flags
| expression
| global_flags expression'''
if len(t) == 3:
flags = t[1]
expression = t[2]
elif len(t) == 2:
if isinstance(t[1], Regex):
expression = t[1]
flags = ''
elif isinstance(t[1], Flagset):
flags = t[1]
expression = ''
t[0] = flags, expression
def p_global_flags(t):
'''global_flags : LPAREN FLAGSET RPAREN NEWLINE'''
flags = t[2]
root_scope = t.lexer.scopes[0]
if 'u' in flags.turn_ons:
root_scope.update(
alpha = BuiltinCC('alpha', r'\p{Alphabetic}'),
upper = BuiltinCC('upper', r'\p{Uppercase}'),
lower = BuiltinCC('lower', r'\p{Lowercase}'),
alnum = BuiltinCC('alnum', r'\p{Alphanumeric}'),
linechar = BuiltinCC('linechar', r'[\r\n\x0B\x0C\x85\u2028\u2029]'),
)
t.lexer.flag_dependent_builtins = FLAG_DEPENDENT_BUILTINS.copy()
t.lexer.flag_dependent_builtins['w'] = t.lexer.flag_dependent_builtins['w'].copy()
t.lexer.flag_dependent_builtins['w'][True] = [
root_scope['linechar']
]
flags_redef_builtins(
flags = flags,
flag_dependent_builtins = t.lexer.flag_dependent_builtins,
scope = root_scope,
)
t[0] = flags
def p_expression(t):
'''expression : expr optional_subblock'''
expr = t[1]
current_scope = t.lexer.scopes[-1]
expression, references = expr.apply(current_scope)
reffed_varnames = set()
for ref in references:
if isinstance(ref, Backreference):
t.lexer.references.append(ref)
elif isinstance(ref, VariableLookup):
reffed_varnames.add(ref.varname)
optional_subblock_cleanup(t.lexer, t[2], reffed_varnames)
t[0] = expression
def p_expr(t):
'''expr : string_expr
| lookup_expr
| orblock_expr
| flagged_expr
| lookaround_expr
| quantified_expr
| numrange_shortcut
| charclass_negation'''
t[0] = t[1]
class StringExpr(Expr):
def apply(self, scope):
references = []
def process(item):
if isinstance(item, VariableLookup):
references.append(item)
return scope[item.varname].value
else:
return item
value = ''.join(map(process, self.items))
return StringLiteral(value), references
def p_string_expr(t):
'''string_expr : STRING NEWLINE
| STRING str_b NEWLINE
| str_b STRING NEWLINE
| str_b STRING str_b NEWLINE'''
t[0] = StringExpr(items=t[1:-1])
def p_str_b(t):
'''str_b : DOT
| UNDERSCORE'''
t[0] = VariableLookup({
'.' : 'WOB',
'_' : 'non-WOB',
}[t[1]], t.lineno(1), optional=False)
def p_numrange_shortcut(t):
'''numrange_shortcut : STRING DOT DOT STRING NEWLINE
| STRING DOT DOT NEWLINE'''
low = t[1]
if len(t) == 6:
high = t[4]
else:
high = 'infinity'
o_led = lambda str: str.startswith('o')
zero_led = lambda str: str.startswith('0') and str != '0'
all_zero = lambda str: all(digit == '0' for digit in str)
all_nine = lambda str: all(digit == '9' for digit in str)
is_powten = lambda str: str[0] == '1' and all_zero(str[1:])
def check_format(fmt):
if not regexlib.fullmatch(r'o*\d+', fmt):
raise OprexSyntaxError(t.lineno(0), "Bad number-range format: '%s'" % fmt)
if regexlib.match(r'o+0+\d+', fmt):
raise OprexSyntaxError(t.lineno(0), "Bad number-range format: '%s' (ambiguous leading-zero spec)" % fmt)
check_format(low)
if high == 'infinity':
if zero_led(low):
raise OprexSyntaxError(t.lineno(0), "Infinite range cannot have (non-optional) leading zero: '%s'.." % low)
if o_led(low) and low.count('o') > 1:
raise OprexSyntaxError(t.lineno(0), "Infinite range: excessive leading-o: '%s'.." % low)
else: # high != infinity
check_format(high)
# using zero-led/o-led format? len(low) must be == len(high)
if zero_led(low) or zero_led(high) or o_led(low) or o_led(high):
if len(low) != len(high):
raise OprexSyntaxError(t.lineno(0),
"Bad number-range format: '%s'..'%s' (lengths must be the same if using leading-zero/o format)" % (low, high))
# zero-led/o-led cannot be mixed
if zero_led(low) and o_led(high) or o_led(low) and zero_led(high):
raise OprexSyntaxError(t.lineno(0),
"Bad number-range format: '%s'..'%s' (one cannot be o-led while the other is zero-led)" % (low, high))
# process leading-o (if any), leading o(s) = allow optional leading zero(es)
is_o_led = o_led(low)
if is_o_led:
if high != 'infinity':
maxdigits = len(high)
defer_gen_o = low.count('o') == high.count('o') # e.g. 'oo123'..'oo456' --> we can just gen '123'..'456'
if defer_gen_o: # and prepend the 'oo' to the result later, outside of gen()
numos_deferred = low.count('o')
# if low == 0, the leading-o must be able to give back one '0' for the low to match, i.e. don't be possessive
if low.lstrip('o') == '0':
o_eagerness = '' # greedy
else:
o_eagerness = '+' # possessive
# now that leading-os have been processed, we can strip them out
low = low.lstrip('o')
high = high.lstrip('o')
if high != 'infinity' and int(high) < int(low):
raise OprexSyntaxError(t.lineno(0), "Bad number-range format: '%s'..'%s' (start > end)" % (low, high))
def gen_optzeros(numos):
return '0{,%d}%s' % (numos, o_eagerness)
def gen(low, high):
len_low = len(low)
len_high = len(high)
low_mag = len_low - 1 # e.g. order-of-magnitude of "42" is 1 (4.2 x 10^1), "1337" is 3 (1.337 x 10^3), etc
high_mag = len_high - 1
def gen_all(steppers=[], should_gen_o=False):
subsets = []
while steppers: # steppers should be in pairs (low-high-low-high etc)
subhigh = steppers.pop()
sublow = steppers.pop()
if int(sublow) > int(subhigh): # this happens when e.g. '7'..'11'
continue # the 7 produces steppers 7-9-10 and the 11 produces 9-10-11, resulting in subsets: 7-9, 10-9, and 10-11
# the 10-9 needs to be skipped
subset = gen(sublow, subhigh)
if should_gen_o and len(subhigh) < maxdigits:
numos = maxdigits - len(subhigh)
subset = gen_optzeros(numos) + subset
if subset.startswith('(?>'):