Debian Codegraph @

lib-python/3/re/_parser.py

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