Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

sre_parse.py 38 KB

You have to be logged in to leave a comment. Sign In
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
  1. #
  2. # Secret Labs' Regular Expression Engine
  3. #
  4. # convert re-style regular expression to sre pattern
  5. #
  6. # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
  7. #
  8. # See the sre.py file for information on usage and redistribution.
  9. #
  10. """Internal support module for sre"""
  11. # XXX: show string offset and offending character for all errors
  12. from sre_constants import *
  13. SPECIAL_CHARS = ".\\[{()*+?^$|"
  14. REPEAT_CHARS = "*+?{"
  15. DIGITS = frozenset("0123456789")
  16. OCTDIGITS = frozenset("01234567")
  17. HEXDIGITS = frozenset("0123456789abcdefABCDEF")
  18. ASCIILETTERS = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  19. WHITESPACE = frozenset(" \t\n\r\v\f")
  20. _REPEATCODES = frozenset({MIN_REPEAT, MAX_REPEAT})
  21. _UNITCODES = frozenset({ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY})
  22. ESCAPES = {
  23. r"\a": (LITERAL, ord("\a")),
  24. r"\b": (LITERAL, ord("\b")),
  25. r"\f": (LITERAL, ord("\f")),
  26. r"\n": (LITERAL, ord("\n")),
  27. r"\r": (LITERAL, ord("\r")),
  28. r"\t": (LITERAL, ord("\t")),
  29. r"\v": (LITERAL, ord("\v")),
  30. r"\\": (LITERAL, ord("\\"))
  31. }
  32. CATEGORIES = {
  33. r"\A": (AT, AT_BEGINNING_STRING), # start of string
  34. r"\b": (AT, AT_BOUNDARY),
  35. r"\B": (AT, AT_NON_BOUNDARY),
  36. r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
  37. r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
  38. r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
  39. r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
  40. r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
  41. r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
  42. r"\Z": (AT, AT_END_STRING), # end of string
  43. }
  44. FLAGS = {
  45. # standard flags
  46. "i": SRE_FLAG_IGNORECASE,
  47. "L": SRE_FLAG_LOCALE,
  48. "m": SRE_FLAG_MULTILINE,
  49. "s": SRE_FLAG_DOTALL,
  50. "x": SRE_FLAG_VERBOSE,
  51. # extensions
  52. "a": SRE_FLAG_ASCII,
  53. "t": SRE_FLAG_TEMPLATE,
  54. "u": SRE_FLAG_UNICODE,
  55. }
  56. TYPE_FLAGS = SRE_FLAG_ASCII | SRE_FLAG_LOCALE | SRE_FLAG_UNICODE
  57. GLOBAL_FLAGS = SRE_FLAG_DEBUG | SRE_FLAG_TEMPLATE
  58. class Verbose(Exception):
  59. pass
  60. class Pattern:
  61. # master pattern object. keeps track of global attributes
  62. def __init__(self):
  63. self.flags = 0
  64. self.groupdict = {}
  65. self.groupwidths = [None] # group 0
  66. self.lookbehindgroups = None
  67. @property
  68. def groups(self):
  69. return len(self.groupwidths)
  70. def opengroup(self, name=None):
  71. gid = self.groups
  72. self.groupwidths.append(None)
  73. if self.groups > MAXGROUPS:
  74. raise error("too many groups")
  75. if name is not None:
  76. ogid = self.groupdict.get(name, None)
  77. if ogid is not None:
  78. raise error("redefinition of group name %r as group %d; "
  79. "was group %d" % (name, gid, ogid))
  80. self.groupdict[name] = gid
  81. return gid
  82. def closegroup(self, gid, p):
  83. self.groupwidths[gid] = p.getwidth()
  84. def checkgroup(self, gid):
  85. return gid < self.groups and self.groupwidths[gid] is not None
  86. def checklookbehindgroup(self, gid, source):
  87. if self.lookbehindgroups is not None:
  88. if not self.checkgroup(gid):
  89. raise source.error('cannot refer to an open group')
  90. if gid >= self.lookbehindgroups:
  91. raise source.error('cannot refer to group defined in the same '
  92. 'lookbehind subpattern')
  93. class SubPattern:
  94. # a subpattern, in intermediate form
  95. def __init__(self, pattern, data=None):
  96. self.pattern = pattern
  97. if data is None:
  98. data = []
  99. self.data = data
  100. self.width = None
  101. def dump(self, level=0):
  102. nl = True
  103. seqtypes = (tuple, list)
  104. for op, av in self.data:
  105. print(level*" " + str(op), end='')
  106. if op is IN:
  107. # member sublanguage
  108. print()
  109. for op, a in av:
  110. print((level+1)*" " + str(op), a)
  111. elif op is BRANCH:
  112. print()
  113. for i, a in enumerate(av[1]):
  114. if i:
  115. print(level*" " + "OR")
  116. a.dump(level+1)
  117. elif op is GROUPREF_EXISTS:
  118. condgroup, item_yes, item_no = av
  119. print('', condgroup)
  120. item_yes.dump(level+1)
  121. if item_no:
  122. print(level*" " + "ELSE")
  123. item_no.dump(level+1)
  124. elif isinstance(av, seqtypes):
  125. nl = False
  126. for a in av:
  127. if isinstance(a, SubPattern):
  128. if not nl:
  129. print()
  130. a.dump(level+1)
  131. nl = True
  132. else:
  133. if not nl:
  134. print(' ', end='')
  135. print(a, end='')
  136. nl = False
  137. if not nl:
  138. print()
  139. else:
  140. print('', av)
  141. def __repr__(self):
  142. return repr(self.data)
  143. def __len__(self):
  144. return len(self.data)
  145. def __delitem__(self, index):
  146. del self.data[index]
  147. def __getitem__(self, index):
  148. if isinstance(index, slice):
  149. return SubPattern(self.pattern, self.data[index])
  150. return self.data[index]
  151. def __setitem__(self, index, code):
  152. self.data[index] = code
  153. def insert(self, index, code):
  154. self.data.insert(index, code)
  155. def append(self, code):
  156. self.data.append(code)
  157. def getwidth(self):
  158. # determine the width (min, max) for this subpattern
  159. if self.width is not None:
  160. return self.width
  161. lo = hi = 0
  162. for op, av in self.data:
  163. if op is BRANCH:
  164. i = MAXREPEAT - 1
  165. j = 0
  166. for av in av[1]:
  167. l, h = av.getwidth()
  168. i = min(i, l)
  169. j = max(j, h)
  170. lo = lo + i
  171. hi = hi + j
  172. elif op is CALL:
  173. i, j = av.getwidth()
  174. lo = lo + i
  175. hi = hi + j
  176. elif op is SUBPATTERN:
  177. i, j = av[-1].getwidth()
  178. lo = lo + i
  179. hi = hi + j
  180. elif op in _REPEATCODES:
  181. i, j = av[2].getwidth()
  182. lo = lo + i * av[0]
  183. hi = hi + j * av[1]
  184. elif op in _UNITCODES:
  185. lo = lo + 1
  186. hi = hi + 1
  187. elif op is GROUPREF:
  188. i, j = self.pattern.groupwidths[av]
  189. lo = lo + i
  190. hi = hi + j
  191. elif op is GROUPREF_EXISTS:
  192. i, j = av[1].getwidth()
  193. if av[2] is not None:
  194. l, h = av[2].getwidth()
  195. i = min(i, l)
  196. j = max(j, h)
  197. else:
  198. i = 0
  199. lo = lo + i
  200. hi = hi + j
  201. elif op is SUCCESS:
  202. break
  203. self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
  204. return self.width
  205. class Tokenizer:
  206. def __init__(self, string):
  207. self.istext = isinstance(string, str)
  208. self.string = string
  209. if not self.istext:
  210. string = str(string, 'latin1')
  211. self.decoded_string = string
  212. self.index = 0
  213. self.next = None
  214. self.__next()
  215. def __next(self):
  216. index = self.index
  217. try:
  218. char = self.decoded_string[index]
  219. except IndexError:
  220. self.next = None
  221. return
  222. if char == "\\":
  223. index += 1
  224. try:
  225. char += self.decoded_string[index]
  226. except IndexError:
  227. raise error("bad escape (end of pattern)",
  228. self.string, len(self.string) - 1) from None
  229. self.index = index + 1
  230. self.next = char
  231. def match(self, char):
  232. if char == self.next:
  233. self.__next()
  234. return True
  235. return False
  236. def get(self):
  237. this = self.next
  238. self.__next()
  239. return this
  240. def getwhile(self, n, charset):
  241. result = ''
  242. for _ in range(n):
  243. c = self.next
  244. if c not in charset:
  245. break
  246. result += c
  247. self.__next()
  248. return result
  249. def getuntil(self, terminator):
  250. result = ''
  251. while True:
  252. c = self.next
  253. self.__next()
  254. if c is None:
  255. if not result:
  256. raise self.error("missing group name")
  257. raise self.error("missing %s, unterminated name" % terminator,
  258. len(result))
  259. if c == terminator:
  260. if not result:
  261. raise self.error("missing group name", 1)
  262. break
  263. result += c
  264. return result
  265. @property
  266. def pos(self):
  267. return self.index - len(self.next or '')
  268. def tell(self):
  269. return self.index - len(self.next or '')
  270. def seek(self, index):
  271. self.index = index
  272. self.__next()
  273. def error(self, msg, offset=0):
  274. return error(msg, self.string, self.tell() - offset)
  275. def _class_escape(source, escape):
  276. # handle escape code inside character class
  277. code = ESCAPES.get(escape)
  278. if code:
  279. return code
  280. code = CATEGORIES.get(escape)
  281. if code and code[0] is IN:
  282. return code
  283. try:
  284. c = escape[1:2]
  285. if c == "x":
  286. # hexadecimal escape (exactly two digits)
  287. escape += source.getwhile(2, HEXDIGITS)
  288. if len(escape) != 4:
  289. raise source.error("incomplete escape %s" % escape, len(escape))
  290. return LITERAL, int(escape[2:], 16)
  291. elif c == "u" and source.istext:
  292. # unicode escape (exactly four digits)
  293. escape += source.getwhile(4, HEXDIGITS)
  294. if len(escape) != 6:
  295. raise source.error("incomplete escape %s" % escape, len(escape))
  296. return LITERAL, int(escape[2:], 16)
  297. elif c == "U" and source.istext:
  298. # unicode escape (exactly eight digits)
  299. escape += source.getwhile(8, HEXDIGITS)
  300. if len(escape) != 10:
  301. raise source.error("incomplete escape %s" % escape, len(escape))
  302. c = int(escape[2:], 16)
  303. chr(c) # raise ValueError for invalid code
  304. return LITERAL, c
  305. elif c in OCTDIGITS:
  306. # octal escape (up to three digits)
  307. escape += source.getwhile(2, OCTDIGITS)
  308. c = int(escape[1:], 8)
  309. if c > 0o377:
  310. raise source.error('octal escape value %s outside of '
  311. 'range 0-0o377' % escape, len(escape))
  312. return LITERAL, c
  313. elif c in DIGITS:
  314. raise ValueError
  315. if len(escape) == 2:
  316. if c in ASCIILETTERS:
  317. raise source.error('bad escape %s' % escape, len(escape))
  318. return LITERAL, ord(escape[1])
  319. except ValueError:
  320. pass
  321. raise source.error("bad escape %s" % escape, len(escape))
  322. def _escape(source, escape, state):
  323. # handle escape code in expression
  324. code = CATEGORIES.get(escape)
  325. if code:
  326. return code
  327. code = ESCAPES.get(escape)
  328. if code:
  329. return code
  330. try:
  331. c = escape[1:2]
  332. if c == "x":
  333. # hexadecimal escape
  334. escape += source.getwhile(2, HEXDIGITS)
  335. if len(escape) != 4:
  336. raise source.error("incomplete escape %s" % escape, len(escape))
  337. return LITERAL, int(escape[2:], 16)
  338. elif c == "u" and source.istext:
  339. # unicode escape (exactly four digits)
  340. escape += source.getwhile(4, HEXDIGITS)
  341. if len(escape) != 6:
  342. raise source.error("incomplete escape %s" % escape, len(escape))
  343. return LITERAL, int(escape[2:], 16)
  344. elif c == "U" and source.istext:
  345. # unicode escape (exactly eight digits)
  346. escape += source.getwhile(8, HEXDIGITS)
  347. if len(escape) != 10:
  348. raise source.error("incomplete escape %s" % escape, len(escape))
  349. c = int(escape[2:], 16)
  350. chr(c) # raise ValueError for invalid code
  351. return LITERAL, c
  352. elif c == "0":
  353. # octal escape
  354. escape += source.getwhile(2, OCTDIGITS)
  355. return LITERAL, int(escape[1:], 8)
  356. elif c in DIGITS:
  357. # octal escape *or* decimal group reference (sigh)
  358. if source.next in DIGITS:
  359. escape += source.get()
  360. if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
  361. source.next in OCTDIGITS):
  362. # got three octal digits; this is an octal escape
  363. escape += source.get()
  364. c = int(escape[1:], 8)
  365. if c > 0o377:
  366. raise source.error('octal escape value %s outside of '
  367. 'range 0-0o377' % escape,
  368. len(escape))
  369. return LITERAL, c
  370. # not an octal escape, so this is a group reference
  371. group = int(escape[1:])
  372. if group < state.groups:
  373. if not state.checkgroup(group):
  374. raise source.error("cannot refer to an open group",
  375. len(escape))
  376. state.checklookbehindgroup(group, source)
  377. return GROUPREF, group
  378. raise source.error("invalid group reference %d" % group, len(escape) - 1)
  379. if len(escape) == 2:
  380. if c in ASCIILETTERS:
  381. raise source.error("bad escape %s" % escape, len(escape))
  382. return LITERAL, ord(escape[1])
  383. except ValueError:
  384. pass
  385. raise source.error("bad escape %s" % escape, len(escape))
  386. def _uniq(items):
  387. if len(set(items)) == len(items):
  388. return items
  389. newitems = []
  390. for item in items:
  391. if item not in newitems:
  392. newitems.append(item)
  393. return newitems
  394. def _parse_sub(source, state, verbose, nested):
  395. # parse an alternation: a|b|c
  396. items = []
  397. itemsappend = items.append
  398. sourcematch = source.match
  399. start = source.tell()
  400. while True:
  401. itemsappend(_parse(source, state, verbose, nested + 1,
  402. not nested and not items))
  403. if not sourcematch("|"):
  404. break
  405. if len(items) == 1:
  406. return items[0]
  407. subpattern = SubPattern(state)
  408. # check if all items share a common prefix
  409. while True:
  410. prefix = None
  411. for item in items:
  412. if not item:
  413. break
  414. if prefix is None:
  415. prefix = item[0]
  416. elif item[0] != prefix:
  417. break
  418. else:
  419. # all subitems start with a common "prefix".
  420. # move it out of the branch
  421. for item in items:
  422. del item[0]
  423. subpattern.append(prefix)
  424. continue # check next one
  425. break
  426. # check if the branch can be replaced by a character set
  427. set = []
  428. for item in items:
  429. if len(item) != 1:
  430. break
  431. op, av = item[0]
  432. if op is LITERAL:
  433. set.append((op, av))
  434. elif op is IN and av[0][0] is not NEGATE:
  435. set.extend(av)
  436. else:
  437. break
  438. else:
  439. # we can store this as a character set instead of a
  440. # branch (the compiler may optimize this even more)
  441. subpattern.append((IN, _uniq(set)))
  442. return subpattern
  443. subpattern.append((BRANCH, (None, items)))
  444. return subpattern
  445. def _parse(source, state, verbose, nested, first=False):
  446. # parse a simple pattern
  447. subpattern = SubPattern(state)
  448. # precompute constants into local variables
  449. subpatternappend = subpattern.append
  450. sourceget = source.get
  451. sourcematch = source.match
  452. _len = len
  453. _ord = ord
  454. while True:
  455. this = source.next
  456. if this is None:
  457. break # end of pattern
  458. if this in "|)":
  459. break # end of subpattern
  460. sourceget()
  461. if verbose:
  462. # skip whitespace and comments
  463. if this in WHITESPACE:
  464. continue
  465. if this == "#":
  466. while True:
  467. this = sourceget()
  468. if this is None or this == "\n":
  469. break
  470. continue
  471. if this[0] == "\\":
  472. code = _escape(source, this, state)
  473. subpatternappend(code)
  474. elif this not in SPECIAL_CHARS:
  475. subpatternappend((LITERAL, _ord(this)))
  476. elif this == "[":
  477. here = source.tell() - 1
  478. # character set
  479. set = []
  480. setappend = set.append
  481. ## if sourcematch(":"):
  482. ## pass # handle character classes
  483. if source.next == '[':
  484. import warnings
  485. warnings.warn(
  486. 'Possible nested set at position %d' % source.tell(),
  487. FutureWarning, stacklevel=nested + 6
  488. )
  489. negate = sourcematch("^")
  490. # check remaining characters
  491. while True:
  492. this = sourceget()
  493. if this is None:
  494. raise source.error("unterminated character set",
  495. source.tell() - here)
  496. if this == "]" and set:
  497. break
  498. elif this[0] == "\\":
  499. code1 = _class_escape(source, this)
  500. else:
  501. if set and this in '-&~|' and source.next == this:
  502. import warnings
  503. warnings.warn(
  504. 'Possible set %s at position %d' % (
  505. 'difference' if this == '-' else
  506. 'intersection' if this == '&' else
  507. 'symmetric difference' if this == '~' else
  508. 'union',
  509. source.tell() - 1),
  510. FutureWarning, stacklevel=nested + 6
  511. )
  512. code1 = LITERAL, _ord(this)
  513. if sourcematch("-"):
  514. # potential range
  515. that = sourceget()
  516. if that is None:
  517. raise source.error("unterminated character set",
  518. source.tell() - here)
  519. if that == "]":
  520. if code1[0] is IN:
  521. code1 = code1[1][0]
  522. setappend(code1)
  523. setappend((LITERAL, _ord("-")))
  524. break
  525. if that[0] == "\\":
  526. code2 = _class_escape(source, that)
  527. else:
  528. if that == '-':
  529. import warnings
  530. warnings.warn(
  531. 'Possible set difference at position %d' % (
  532. source.tell() - 2),
  533. FutureWarning, stacklevel=nested + 6
  534. )
  535. code2 = LITERAL, _ord(that)
  536. if code1[0] != LITERAL or code2[0] != LITERAL:
  537. msg = "bad character range %s-%s" % (this, that)
  538. raise source.error(msg, len(this) + 1 + len(that))
  539. lo = code1[1]
  540. hi = code2[1]
  541. if hi < lo:
  542. msg = "bad character range %s-%s" % (this, that)
  543. raise source.error(msg, len(this) + 1 + len(that))
  544. setappend((RANGE, (lo, hi)))
  545. else:
  546. if code1[0] is IN:
  547. code1 = code1[1][0]
  548. setappend(code1)
  549. set = _uniq(set)
  550. # XXX: <fl> should move set optimization to compiler!
  551. if _len(set) == 1 and set[0][0] is LITERAL:
  552. # optimization
  553. if negate:
  554. subpatternappend((NOT_LITERAL, set[0][1]))
  555. else:
  556. subpatternappend(set[0])
  557. else:
  558. if negate:
  559. set.insert(0, (NEGATE, None))
  560. # charmap optimization can't be added here because
  561. # global flags still are not known
  562. subpatternappend((IN, set))
  563. elif this in REPEAT_CHARS:
  564. # repeat previous item
  565. here = source.tell()
  566. if this == "?":
  567. min, max = 0, 1
  568. elif this == "*":
  569. min, max = 0, MAXREPEAT
  570. elif this == "+":
  571. min, max = 1, MAXREPEAT
  572. elif this == "{":
  573. if source.next == "}":
  574. subpatternappend((LITERAL, _ord(this)))
  575. continue
  576. min, max = 0, MAXREPEAT
  577. lo = hi = ""
  578. while source.next in DIGITS:
  579. lo += sourceget()
  580. if sourcematch(","):
  581. while source.next in DIGITS:
  582. hi += sourceget()
  583. else:
  584. hi = lo
  585. if not sourcematch("}"):
  586. subpatternappend((LITERAL, _ord(this)))
  587. source.seek(here)
  588. continue
  589. if lo:
  590. min = int(lo)
  591. if min >= MAXREPEAT:
  592. raise OverflowError("the repetition number is too large")
  593. if hi:
  594. max = int(hi)
  595. if max >= MAXREPEAT:
  596. raise OverflowError("the repetition number is too large")
  597. if max < min:
  598. raise source.error("min repeat greater than max repeat",
  599. source.tell() - here)
  600. else:
  601. raise AssertionError("unsupported quantifier %r" % (char,))
  602. # figure out which item to repeat
  603. if subpattern:
  604. item = subpattern[-1:]
  605. else:
  606. item = None
  607. if not item or item[0][0] is AT:
  608. raise source.error("nothing to repeat",
  609. source.tell() - here + len(this))
  610. if item[0][0] in _REPEATCODES:
  611. raise source.error("multiple repeat",
  612. source.tell() - here + len(this))
  613. if item[0][0] is SUBPATTERN:
  614. group, add_flags, del_flags, p = item[0][1]
  615. if group is None and not add_flags and not del_flags:
  616. item = p
  617. if sourcematch("?"):
  618. subpattern[-1] = (MIN_REPEAT, (min, max, item))
  619. else:
  620. subpattern[-1] = (MAX_REPEAT, (min, max, item))
  621. elif this == ".":
  622. subpatternappend((ANY, None))
  623. elif this == "(":
  624. start = source.tell() - 1
  625. group = True
  626. name = None
  627. add_flags = 0
  628. del_flags = 0
  629. if sourcematch("?"):
  630. # options
  631. char = sourceget()
  632. if char is None:
  633. raise source.error("unexpected end of pattern")
  634. if char == "P":
  635. # python extensions
  636. if sourcematch("<"):
  637. # named group: skip forward to end of name
  638. name = source.getuntil(">")
  639. if not name.isidentifier():
  640. msg = "bad character in group name %r" % name
  641. raise source.error(msg, len(name) + 1)
  642. elif sourcematch("="):
  643. # named backreference
  644. name = source.getuntil(")")
  645. if not name.isidentifier():
  646. msg = "bad character in group name %r" % name
  647. raise source.error(msg, len(name) + 1)
  648. gid = state.groupdict.get(name)
  649. if gid is None:
  650. msg = "unknown group name %r" % name
  651. raise source.error(msg, len(name) + 1)
  652. if not state.checkgroup(gid):
  653. raise source.error("cannot refer to an open group",
  654. len(name) + 1)
  655. state.checklookbehindgroup(gid, source)
  656. subpatternappend((GROUPREF, gid))
  657. continue
  658. else:
  659. char = sourceget()
  660. if char is None:
  661. raise source.error("unexpected end of pattern")
  662. raise source.error("unknown extension ?P" + char,
  663. len(char) + 2)
  664. elif char == ":":
  665. # non-capturing group
  666. group = None
  667. elif char == "#":
  668. # comment
  669. while True:
  670. if source.next is None:
  671. raise source.error("missing ), unterminated comment",
  672. source.tell() - start)
  673. if sourceget() == ")":
  674. break
  675. continue
  676. elif char in "=!<":
  677. # lookahead assertions
  678. dir = 1
  679. if char == "<":
  680. char = sourceget()
  681. if char is None:
  682. raise source.error("unexpected end of pattern")
  683. if char not in "=!":
  684. raise source.error("unknown extension ?<" + char,
  685. len(char) + 2)
  686. dir = -1 # lookbehind
  687. lookbehindgroups = state.lookbehindgroups
  688. if lookbehindgroups is None:
  689. state.lookbehindgroups = state.groups
  690. p = _parse_sub(source, state, verbose, nested + 1)
  691. if dir < 0:
  692. if lookbehindgroups is None:
  693. state.lookbehindgroups = None
  694. if not sourcematch(")"):
  695. raise source.error("missing ), unterminated subpattern",
  696. source.tell() - start)
  697. if char == "=":
  698. subpatternappend((ASSERT, (dir, p)))
  699. else:
  700. subpatternappend((ASSERT_NOT, (dir, p)))
  701. continue
  702. elif char == "(":
  703. # conditional backreference group
  704. condname = source.getuntil(")")
  705. if condname.isidentifier():
  706. condgroup = state.groupdict.get(condname)
  707. if condgroup is None:
  708. msg = "unknown group name %r" % condname
  709. raise source.error(msg, len(condname) + 1)
  710. else:
  711. try:
  712. condgroup = int(condname)
  713. if condgroup < 0:
  714. raise ValueError
  715. except ValueError:
  716. msg = "bad character in group name %r" % condname
  717. raise source.error(msg, len(condname) + 1) from None
  718. if not condgroup:
  719. raise source.error("bad group number",
  720. len(condname) + 1)
  721. if condgroup >= MAXGROUPS:
  722. msg = "invalid group reference %d" % condgroup
  723. raise source.error(msg, len(condname) + 1)
  724. state.checklookbehindgroup(condgroup, source)
  725. item_yes = _parse(source, state, verbose, nested + 1)
  726. if source.match("|"):
  727. item_no = _parse(source, state, verbose, nested + 1)
  728. if source.next == "|":
  729. raise source.error("conditional backref with more than two branches")
  730. else:
  731. item_no = None
  732. if not source.match(")"):
  733. raise source.error("missing ), unterminated subpattern",
  734. source.tell() - start)
  735. subpatternappend((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
  736. continue
  737. elif char in FLAGS or char == "-":
  738. # flags
  739. flags = _parse_flags(source, state, char)
  740. if flags is None: # global flags
  741. if not first or subpattern:
  742. import warnings
  743. warnings.warn(
  744. 'Flags not at the start of the expression %r%s' % (
  745. source.string[:20], # truncate long regexes
  746. ' (truncated)' if len(source.string) > 20 else '',
  747. ),
  748. DeprecationWarning, stacklevel=nested + 6
  749. )
  750. if (state.flags & SRE_FLAG_VERBOSE) and not verbose:
  751. raise Verbose
  752. continue
  753. add_flags, del_flags = flags
  754. group = None
  755. else:
  756. raise source.error("unknown extension ?" + char,
  757. len(char) + 1)
  758. # parse group contents
  759. if group is not None:
  760. try:
  761. group = state.opengroup(name)
  762. except error as err:
  763. raise source.error(err.msg, len(name) + 1) from None
  764. sub_verbose = ((verbose or (add_flags & SRE_FLAG_VERBOSE)) and
  765. not (del_flags & SRE_FLAG_VERBOSE))
  766. p = _parse_sub(source, state, sub_verbose, nested + 1)
  767. if not source.match(")"):
  768. raise source.error("missing ), unterminated subpattern",
  769. source.tell() - start)
  770. if group is not None:
  771. state.closegroup(group, p)
  772. subpatternappend((SUBPATTERN, (group, add_flags, del_flags, p)))
  773. elif this == "^":
  774. subpatternappend((AT, AT_BEGINNING))
  775. elif this == "$":
  776. subpatternappend((AT, AT_END))
  777. else:
  778. raise AssertionError("unsupported special character %r" % (char,))
  779. # unpack non-capturing groups
  780. for i in range(len(subpattern))[::-1]:
  781. op, av = subpattern[i]
  782. if op is SUBPATTERN:
  783. group, add_flags, del_flags, p = av
  784. if group is None and not add_flags and not del_flags:
  785. subpattern[i: i+1] = p
  786. return subpattern
  787. def _parse_flags(source, state, char):
  788. sourceget = source.get
  789. add_flags = 0
  790. del_flags = 0
  791. if char != "-":
  792. while True:
  793. flag = FLAGS[char]
  794. if source.istext:
  795. if char == 'L':
  796. msg = "bad inline flags: cannot use 'L' flag with a str pattern"
  797. raise source.error(msg)
  798. else:
  799. if char == 'u':
  800. msg = "bad inline flags: cannot use 'u' flag with a bytes pattern"
  801. raise source.error(msg)
  802. add_flags |= flag
  803. if (flag & TYPE_FLAGS) and (add_flags & TYPE_FLAGS) != flag:
  804. msg = "bad inline flags: flags 'a', 'u' and 'L' are incompatible"
  805. raise source.error(msg)
  806. char = sourceget()
  807. if char is None:
  808. raise source.error("missing -, : or )")
  809. if char in ")-:":
  810. break
  811. if char not in FLAGS:
  812. msg = "unknown flag" if char.isalpha() else "missing -, : or )"
  813. raise source.error(msg, len(char))
  814. if char == ")":
  815. state.flags |= add_flags
  816. return None
  817. if add_flags & GLOBAL_FLAGS:
  818. raise source.error("bad inline flags: cannot turn on global flag", 1)
  819. if char == "-":
  820. char = sourceget()
  821. if char is None:
  822. raise source.error("missing flag")
  823. if char not in FLAGS:
  824. msg = "unknown flag" if char.isalpha() else "missing flag"
  825. raise source.error(msg, len(char))
  826. while True:
  827. flag = FLAGS[char]
  828. if flag & TYPE_FLAGS:
  829. msg = "bad inline flags: cannot turn off flags 'a', 'u' and 'L'"
  830. raise source.error(msg)
  831. del_flags |= flag
  832. char = sourceget()
  833. if char is None:
  834. raise source.error("missing :")
  835. if char == ":":
  836. break
  837. if char not in FLAGS:
  838. msg = "unknown flag" if char.isalpha() else "missing :"
  839. raise source.error(msg, len(char))
  840. assert char == ":"
  841. if del_flags & GLOBAL_FLAGS:
  842. raise source.error("bad inline flags: cannot turn off global flag", 1)
  843. if add_flags & del_flags:
  844. raise source.error("bad inline flags: flag turned on and off", 1)
  845. return add_flags, del_flags
  846. def fix_flags(src, flags):
  847. # Check and fix flags according to the type of pattern (str or bytes)
  848. if isinstance(src, str):
  849. if flags & SRE_FLAG_LOCALE:
  850. raise ValueError("cannot use LOCALE flag with a str pattern")
  851. if not flags & SRE_FLAG_ASCII:
  852. flags |= SRE_FLAG_UNICODE
  853. elif flags & SRE_FLAG_UNICODE:
  854. raise ValueError("ASCII and UNICODE flags are incompatible")
  855. else:
  856. if flags & SRE_FLAG_UNICODE:
  857. raise ValueError("cannot use UNICODE flag with a bytes pattern")
  858. if flags & SRE_FLAG_LOCALE and flags & SRE_FLAG_ASCII:
  859. raise ValueError("ASCII and LOCALE flags are incompatible")
  860. return flags
  861. def parse(str, flags=0, pattern=None):
  862. # parse 're' pattern into list of (opcode, argument) tuples
  863. source = Tokenizer(str)
  864. if pattern is None:
  865. pattern = Pattern()
  866. pattern.flags = flags
  867. pattern.str = str
  868. try:
  869. p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
  870. except Verbose:
  871. # the VERBOSE flag was switched on inside the pattern. to be
  872. # on the safe side, we'll parse the whole thing again...
  873. pattern = Pattern()
  874. pattern.flags = flags | SRE_FLAG_VERBOSE
  875. pattern.str = str
  876. source.seek(0)
  877. p = _parse_sub(source, pattern, True, 0)
  878. p.pattern.flags = fix_flags(str, p.pattern.flags)
  879. if source.next is not None:
  880. assert source.next == ")"
  881. raise source.error("unbalanced parenthesis")
  882. if flags & SRE_FLAG_DEBUG:
  883. p.dump()
  884. return p
  885. def parse_template(source, pattern):
  886. # parse 're' replacement string into list of literals and
  887. # group references
  888. s = Tokenizer(source)
  889. sget = s.get
  890. groups = []
  891. literals = []
  892. literal = []
  893. lappend = literal.append
  894. def addgroup(index, pos):
  895. if index > pattern.groups:
  896. raise s.error("invalid group reference %d" % index, pos)
  897. if literal:
  898. literals.append(''.join(literal))
  899. del literal[:]
  900. groups.append((len(literals), index))
  901. literals.append(None)
  902. groupindex = pattern.groupindex
  903. while True:
  904. this = sget()
  905. if this is None:
  906. break # end of replacement string
  907. if this[0] == "\\":
  908. # group
  909. c = this[1]
  910. if c == "g":
  911. name = ""
  912. if not s.match("<"):
  913. raise s.error("missing <")
  914. name = s.getuntil(">")
  915. if name.isidentifier():
  916. try:
  917. index = groupindex[name]
  918. except KeyError:
  919. raise IndexError("unknown group name %r" % name)
  920. else:
  921. try:
  922. index = int(name)
  923. if index < 0:
  924. raise ValueError
  925. except ValueError:
  926. raise s.error("bad character in group name %r" % name,
  927. len(name) + 1) from None
  928. if index >= MAXGROUPS:
  929. raise s.error("invalid group reference %d" % index,
  930. len(name) + 1)
  931. addgroup(index, len(name) + 1)
  932. elif c == "0":
  933. if s.next in OCTDIGITS:
  934. this += sget()
  935. if s.next in OCTDIGITS:
  936. this += sget()
  937. lappend(chr(int(this[1:], 8) & 0xff))
  938. elif c in DIGITS:
  939. isoctal = False
  940. if s.next in DIGITS:
  941. this += sget()
  942. if (c in OCTDIGITS and this[2] in OCTDIGITS and
  943. s.next in OCTDIGITS):
  944. this += sget()
  945. isoctal = True
  946. c = int(this[1:], 8)
  947. if c > 0o377:
  948. raise s.error('octal escape value %s outside of '
  949. 'range 0-0o377' % this, len(this))
  950. lappend(chr(c))
  951. if not isoctal:
  952. addgroup(int(this[1:]), len(this) - 1)
  953. else:
  954. try:
  955. this = chr(ESCAPES[this][1])
  956. except KeyError:
  957. if c in ASCIILETTERS:
  958. raise s.error('bad escape %s' % this, len(this))
  959. lappend(this)
  960. else:
  961. lappend(this)
  962. if literal:
  963. literals.append(''.join(literal))
  964. if not isinstance(source, str):
  965. # The tokenizer implicitly decodes bytes objects as latin-1, we must
  966. # therefore re-encode the final representation.
  967. literals = [None if s is None else s.encode('latin-1') for s in literals]
  968. return groups, literals
  969. def expand_template(template, match):
  970. g = match.group
  971. empty = match.string[:0]
  972. groups, literals = template
  973. literals = literals[:]
  974. try:
  975. for index, group in groups:
  976. literals[index] = g(group) or empty
  977. except IndexError:
  978. raise error("invalid group reference %d" % index)
  979. return empty.join(literals)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...