Debian Codegraph @

rpython/rlib/rsre/rpy/sre_parse.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 sre.py file for information on usage and redistribution.
9 #
10
11 """Internal support module for sre (copied from CPython)"""
12
13 # XXX: show string offset and offending character for all errors
14 from __future__ import print_function
15
16 import sys
17
18 from .sre_constants import *
19
20 SPECIAL_CHARS = ".\\[{()*+?^$|"
21 REPEAT_CHARS = "*+?{"
22
23 DIGITS = set("0123456789")
24
25 OCTDIGITS = set("01234567")
26 HEXDIGITS = set("0123456789abcdefABCDEF")
27 ASCIILETTERS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
28
29 WHITESPACE = set(" \t\n\r\v\f")
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 "t": SRE_FLAG_TEMPLATE,
64 "u": SRE_FLAG_UNICODE,
65 }
66
67 class Pattern:
68 # master pattern object. keeps track of global attributes
69 def __init__(self):
70 self.flags = 0
71 self.open = []
72 self.groups = 1
73 self.groupdict = {}
74 self.lookbehind = 0
75
76 def opengroup(self, name=None):
77 gid = self.groups
78 self.groups = gid + 1
79 if name is not None:
80 ogid = self.groupdict.get(name, None)
81 if ogid is not None:
82 raise error("redefinition of group name %s as group %d; "
83 "was group %d" % (repr(name), gid, ogid))
84 self.groupdict[name] = gid
85 self.open.append(gid)
86 return gid
87 def closegroup(self, gid):
88 self.open.remove(gid)
89 def checkgroup(self, gid):
90 return gid < self.groups and gid not in self.open
91
92 class SubPattern:
93 # a subpattern, in intermediate form
94 def __init__(self, pattern, data=None):
95 self.pattern = pattern
96 if data is None:
97 data = []
98 self.data = data
99 self.width = None
100 def dump(self, level=0):
101 seqtypes = (tuple, list)
102 for op, av in self.data:
103 print(level*" " + op, end=" ")
104 if op == IN:
105 # member sublanguage
106 print()
107 for op, a in av:
108 print((level+1)*" " + op, a)
109 elif op == BRANCH:
110 print()
111 for i, a in enumerate(av[1]):
112 if i:
113 print(level*" " + "or")
114 a.dump(level+1)
115 elif op == GROUPREF_EXISTS:
116 condgroup, item_yes, item_no = av
117 print(condgroup)
118 item_yes.dump(level+1)
119 if item_no:
120 print(level*" " + "else")
121 item_no.dump(level+1)
122 elif isinstance(av, seqtypes):
123 nl = 0
124 for a in av:
125 if isinstance(a, SubPattern):
126 if not nl:
127 print()
128 a.dump(level+1)
129 nl = 1
130 else:
131 print(a, end=" ")
132 nl = 0
133 if not nl:
134 print()
135 else:
136 print(av)
137 def __repr__(self):
138 return repr(self.data)
139 def __len__(self):
140 return len(self.data)
141 def __delitem__(self, index):
142 del self.data[index]
143 def __getitem__(self, index):
144 if isinstance(index, slice):
145 return SubPattern(self.pattern, self.data[index])
146 return self.data[index]
147 def __setitem__(self, index, code):
148 self.data[index] = code
149 def insert(self, index, code):
150 self.data.insert(index, code)
151 def append(self, code):
152 self.data.append(code)
153 def getwidth(self):
154 # determine the width (min, max) for this subpattern
155 if self.width:
156 return self.width
157 lo = hi = 0
158 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
159 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
160 for op, av in self.data:
161 if op is BRANCH:
162 i = MAXREPEAT - 1
163 j = 0
164 for av in av[1]:
165 l, h = av.getwidth()
166 i = min(i, l)
167 j = max(j, h)
168 lo = lo + i
169 hi = hi + j
170 elif op is CALL:
171 i, j = av.getwidth()
172 lo = lo + i
173 hi = hi + j
174 elif op is SUBPATTERN:
175 i, j = av[1].getwidth()
176 lo = lo + i
177 hi = hi + j
178 elif op in REPEATCODES:
179 i, j = av[2].getwidth()
180 lo = lo + i * av[0]
181 hi = hi + j * av[1]
182 elif op in UNITCODES:
183 lo = lo + 1
184 hi = hi + 1
185 elif op == SUCCESS:
186 break
187 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
188 return self.width
189
190 class Tokenizer:
191 def __init__(self, string):
192 self.string = string
193 self.index = 0
194 self.__next()
195 def __next(self):
196 if self.index >= len(self.string):
197 self.next = None
198 return
199 char = self.string[self.index]
200 if char[0] == "\\":
201 try:
202 c = self.string[self.index + 1]
203 except IndexError:
204 raise error("bogus escape (end of line)")
205 char = char + c
206 self.index = self.index + len(char)
207 self.next = char
208 def match(self, char, skip=1):
209 if char == self.next:
210 if skip:
211 self.__next()
212 return 1
213 return 0
214 def get(self):
215 this = self.next
216 self.__next()
217 return this
218 def tell(self):
219 return self.index, self.next
220 def seek(self, index):
221 self.index, self.next = index
222
223 def isident(char):
224 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
225
226 def isdigit(char):
227 return "0" <= char <= "9"
228
229 def isname(name):
230 # check that group name is a valid string
231 if not isident(name[0]):
232 return False
233 for char in name[1:]:
234 if not isident(char) and not isdigit(char):
235 return False
236 return True
237
238 def _class_escape(source, escape, nested):
239 # handle escape code inside character class
240 code = ESCAPES.get(escape)
241 if code:
242 return code
243 code = CATEGORIES.get(escape)
244 if code and code[0] == IN:
245 return code
246 try:
247 c = escape[1:2]
248 if c == "x":
249 # hexadecimal escape (exactly two digits)
250 while source.next in HEXDIGITS and len(escape) < 4:
251 escape = escape + source.get()
252 escape = escape[2:]
253 if len(escape) != 2:
254 raise error("bogus escape: %s" % repr("\\" + escape))
255 return LITERAL, int(escape, 16) & 0xff
256 elif c in OCTDIGITS:
257 # octal escape (up to three digits)
258 while source.next in OCTDIGITS and len(escape) < 4:
259 escape = escape + source.get()
260 escape = escape[1:]
261 return LITERAL, int(escape, 8) & 0xff
262 elif c in DIGITS:
263 raise error("bogus escape: %s" % repr(escape))
264 if len(escape) == 2:
265 if sys.py3kwarning and c in ASCIILETTERS:
266 import warnings
267 if c in 'Uu':
268 warnings.warn('bad escape %s; Unicode escapes are '
269 'supported only since Python 3.3' % escape,
270 FutureWarning, stacklevel=nested + 6)
271 else:
272 warnings.warnpy3k('bad escape %s' % escape,
273 DeprecationWarning, stacklevel=nested + 6)
274 return LITERAL, ord(escape[1])
275 except ValueError:
276 pass
277 raise error("bogus escape: %s" % repr(escape))
278
279 def _escape(source, escape, state, nested):
280 # handle escape code in expression
281 code = CATEGORIES.get(escape)
282 if code:
283 return code
284 code = ESCAPES.get(escape)
285 if code:
286 return code
287 try:
288 c = escape[1:2]
289 if c == "x":
290 # hexadecimal escape
291 while source.next in HEXDIGITS and len(escape) < 4:
292 escape = escape + source.get()
293 if len(escape) != 4:
294 raise ValueError
295 return LITERAL, int(escape[2:], 16) & 0xff
296 elif c == "0":
297 # octal escape
298 while source.next in OCTDIGITS and len(escape) < 4:
299 escape = escape + source.get()
300 return LITERAL, int(escape[1:], 8) & 0xff
301 elif c in DIGITS:
302 # octal escape *or* decimal group reference (sigh)
303 if source.next in DIGITS:
304 escape = escape + source.get()
305 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
306 source.next in OCTDIGITS):
307 # got three octal digits; this is an octal escape
308 escape = escape + source.get()
309 return LITERAL, int(escape[1:], 8) & 0xff
310 # not an octal escape, so this is a group reference
311 group = int(escape[1:])
312 if group < state.groups:
313 if not state.checkgroup(group):
314 raise error("cannot refer to open group")
315 if state.lookbehind:
316 import warnings
317 warnings.warn('group references in lookbehind '
318 'assertions are not supported',
319 RuntimeWarning, stacklevel=nested + 6)
320 return GROUPREF, group
321 raise ValueError
322 if len(escape) == 2:
323 if sys.py3kwarning and c in ASCIILETTERS:
324 import warnings
325 if c in 'Uu':
326 warnings.warn('bad escape %s; Unicode escapes are '
327 'supported only since Python 3.3' % escape,
328 FutureWarning, stacklevel=nested + 6)
329 else:
330 warnings.warnpy3k('bad escape %s' % escape,
331 DeprecationWarning, stacklevel=nested + 6)
332 return LITERAL, ord(escape[1])
333 except ValueError:
334 pass
335 raise error("bogus escape: %s" % repr(escape))
336
337 def _parse_sub(source, state, nested):
338 # parse an alternation: a|b|c
339
340 items = []
341 itemsappend = items.append
342 sourcematch = source.match
343 while 1:
344 itemsappend(_parse(source, state, nested + 1))
345 if sourcematch("|"):
346 continue
347 if not nested:
348 break
349 if not source.next or sourcematch(")", 0):
350 break
351 else:
352 raise error("pattern not properly closed")
353
354 if len(items) == 1:
355 return items[0]
356
357 subpattern = SubPattern(state)
358 subpatternappend = subpattern.append
359
360 # check if all items share a common prefix
361 while 1:
362 prefix = None
363 for item in items:
364 if not item:
365 break
366 if prefix is None:
367 prefix = item[0]
368 elif item[0] != prefix:
369 break
370 else:
371 # all subitems start with a common "prefix".
372 # move it out of the branch
373 for item in items:
374 del item[0]
375 subpatternappend(prefix)
376 continue # check next one
377 break
378
379 # check if the branch can be replaced by a character set
380 for item in items:
381 if len(item) != 1 or item[0][0] != LITERAL:
382 break
383 else:
384 # we can store this as a character set instead of a
385 # branch (the compiler may optimize this even more)
386 set = []
387 setappend = set.append
388 for item in items:
389 setappend(item[0])
390 subpatternappend((IN, set))
391 return subpattern
392
393 subpattern.append((BRANCH, (None, items)))
394 return subpattern
395
396 def _parse_sub_cond(source, state, condgroup, nested):
397 item_yes = _parse(source, state, nested + 1)
398 if source.match("|"):
399 item_no = _parse(source, state, nested + 1)
400 if source.match("|"):
401 raise error("conditional backref with more than two branches")
402 else:
403 item_no = None
404 if source.next and not source.match(")", 0):
405 raise error("pattern not properly closed")
406 subpattern = SubPattern(state)
407 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
408 return subpattern
409
410 _PATTERNENDERS = set("|)")
411 _ASSERTCHARS = set("=!<")
412 _LOOKBEHINDASSERTCHARS = set("=!")
413 _REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
414
415 def _parse(source, state, nested):
416 # parse a simple pattern
417 subpattern = SubPattern(state)
418
419 # precompute constants into local variables
420 subpatternappend = subpattern.append
421 sourceget = source.get
422 sourcematch = source.match
423 _len = len
424 PATTERNENDERS = _PATTERNENDERS
425 ASSERTCHARS = _ASSERTCHARS
426 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
427 REPEATCODES = _REPEATCODES
428
429 while 1:
430
431 if source.next in PATTERNENDERS:
432 break # end of subpattern
433 this = sourceget()
434 if this is None:
435 break # end of pattern
436
437 if state.flags & SRE_FLAG_VERBOSE:
438 # skip whitespace and comments
439 if this in WHITESPACE:
440 continue
441 if this == "#":
442 while 1:
443 this = sourceget()
444 if this in (None, "\n"):
445 break
446 continue
447
448 if this and this[0] not in SPECIAL_CHARS:
449 subpatternappend((LITERAL, ord(this)))
450
451 elif this == "[":
452 # character set
453 set = []
454 setappend = set.append
455 ## if sourcematch(":"):
456 ## pass # handle character classes
457 if sourcematch("^"):
458 setappend((NEGATE, None))
459 # check remaining characters
460 start = set[:]
461 while 1:
462 this = sourceget()
463 if this == "]" and set != start:
464 break
465 elif this and this[0] == "\\":
466 code1 = _class_escape(source, this, nested + 1)
467 elif this:
468 code1 = LITERAL, ord(this)
469 else:
470 raise error("unexpected end of regular expression")
471 if sourcematch("-"):
472 # potential range
473 this = sourceget()
474 if this == "]":
475 if code1[0] is IN:
476 code1 = code1[1][0]
477 setappend(code1)
478 setappend((LITERAL, ord("-")))
479 break
480 elif this:
481 if this[0] == "\\":
482 code2 = _class_escape(source, this, nested + 1)
483 else:
484 code2 = LITERAL, ord(this)
485 if code1[0] != LITERAL or code2[0] != LITERAL:
486 raise error("bad character range")
487 lo = code1[1]
488 hi = code2[1]
489 if hi < lo:
490 raise error("bad character range")
491 setappend((RANGE, (lo, hi)))
492 else:
493 raise error("unexpected end of regular expression")
494 else:
495 if code1[0] is IN:
496 code1 = code1[1][0]
497 setappend(code1)
498
499 # XXX: <fl> should move set optimization to compiler!
500 if _len(set)==1 and set[0][0] is LITERAL:
501 subpatternappend(set[0]) # optimization
502 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
503 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
504 else:
505 # XXX: <fl> should add charmap optimization here
506 subpatternappend((IN, set))
507
508 elif this and this[0] in REPEAT_CHARS:
509 # repeat previous item
510 if this == "?":
511 min, max = 0, 1
512 elif this == "*":
513 min, max = 0, MAXREPEAT
514
515 elif this == "+":
516 min, max = 1, MAXREPEAT
517 elif this == "{":
518 if source.next == "}":
519 subpatternappend((LITERAL, ord(this)))
520 continue
521 here = source.tell()
522 min, max = 0, MAXREPEAT
523 lo = hi = ""
524 while source.next in DIGITS:
525 lo = lo + source.get()
526 if sourcematch(","):
527 while source.next in DIGITS:
528 hi = hi + sourceget()
529 else:
530 hi = lo
531 if not sourcematch("}"):
532 subpatternappend((LITERAL, ord(this)))
533 source.seek(here)
534 continue
535 if lo:
536 min = int(lo)
537 if min >= MAXREPEAT:
538 raise OverflowError("the repetition number is too large")
539 if hi:
540 max = int(hi)
541 if max >= MAXREPEAT:
542 raise OverflowError("the repetition number is too large")
543 if max < min:
544 raise error("bad repeat interval")
545 else:
546 raise error("not supported")
547 # figure out which item to repeat
548 if subpattern:
549 item = subpattern[-1:]
550 else:
551 item = None
552 if not item or (_len(item) == 1 and item[0][0] == AT):
553 raise error("nothing to repeat")
554 if item[0][0] in REPEATCODES:
555 raise error("multiple repeat")
556 if sourcematch("?"):
557 subpattern[-1] = (MIN_REPEAT, (min, max, item))
558 else:
559 subpattern[-1] = (MAX_REPEAT, (min, max, item))
560
561 elif this == ".":
562 subpatternappend((ANY, None))
563
564 elif this == "(":
565 group = 1
566 name = None
567 condgroup = None
568 if sourcematch("?"):
569 group = 0
570 # options
571 if sourcematch("P"):
572 # python extensions
573 if sourcematch("<"):
574 # named group: skip forward to end of name
575 name = ""
576 while 1:
577 char = sourceget()
578 if char is None:
579 raise error("unterminated name")
580 if char == ">":
581 break
582 name = name + char
583 group = 1
584 if not name:
585 raise error("missing group name")
586 if not isname(name):
587 raise error("bad character in group name %r" %
588 name)
589 elif sourcematch("="):
590 # named backreference
591 name = ""
592 while 1:
593 char = sourceget()
594 if char is None:
595 raise error("unterminated name")
596 if char == ")":
597 break
598 name = name + char
599 if not name:
600 raise error("missing group name")
601 if not isname(name):
602 raise error("bad character in backref group name "
603 "%r" % name)
604 gid = state.groupdict.get(name)
605 if gid is None:
606 msg = "unknown group name: {0!r}".format(name)
607 raise error(msg)
608 if state.lookbehind:
609 import warnings
610 warnings.warn('group references in lookbehind '
611 'assertions are not supported',
612 RuntimeWarning, stacklevel=nested + 6)
613 subpatternappend((GROUPREF, gid))
614 continue
615 else:
616 char = sourceget()
617 if char is None:
618 raise error("unexpected end of pattern")
619 raise error("unknown specifier: ?P%s" % char)
620 elif sourcematch(":"):
621 # non-capturing group
622 group = 2
623 elif sourcematch("#"):
624 # comment
625 while 1:
626 if source.next is None or source.next == ")":
627 break
628 sourceget()
629 if not sourcematch(")"):
630 raise error("unbalanced parenthesis")
631 continue
632 elif source.next in ASSERTCHARS:
633 # lookahead assertions
634 char = sourceget()
635 dir = 1
636 if char == "<":
637 if source.next not in LOOKBEHINDASSERTCHARS:
638 raise error("syntax error")
639 dir = -1 # lookbehind
640 char = sourceget()
641 state.lookbehind += 1
642 p = _parse_sub(source, state, nested + 1)
643 if dir < 0:
644 state.lookbehind -= 1
645 if not sourcematch(")"):
646 raise error("unbalanced parenthesis")
647 if char == "=":
648 subpatternappend((ASSERT, (dir, p)))
649 else:
650 subpatternappend((ASSERT_NOT, (dir, p)))
651 continue
652 elif sourcematch("("):
653 # conditional backreference group
654 condname = ""
655 while 1:
656 char = sourceget()
657 if char is None:
658 raise error("unterminated name")
659 if char == ")":
660 break
661 condname = condname + char
662 group = 2
663 if not condname:
664 raise error("missing group name")
665 if isname(condname):
666 condgroup = state.groupdict.get(condname)
667 if condgroup is None:
668 msg = "unknown group name: {0!r}".format(condname)
669 raise error(msg)
670 else:
671 try:
672 condgroup = int(condname)
673 except ValueError:
674 raise error("bad character in group name")
675 if state.lookbehind:
676 import warnings
677 warnings.warn('group references in lookbehind '
678 'assertions are not supported',
679 RuntimeWarning, stacklevel=nested + 6)
680 else:
681 # flags
682 if not source.next in FLAGS:
683 raise error("unexpected end of pattern")
684 while source.next in FLAGS:
685 state.flags = state.flags | FLAGS[sourceget()]
686 if group:
687 # parse group contents
688 if group == 2:
689 # anonymous group
690 group = None
691 else:
692 group = state.opengroup(name)
693 if condgroup:
694 p = _parse_sub_cond(source, state, condgroup, nested + 1)
695 else:
696 p = _parse_sub(source, state, nested + 1)
697 if not sourcematch(")"):
698 raise error("unbalanced parenthesis")
699 if group is not None:
700 state.closegroup(group)
701 subpatternappend((SUBPATTERN, (group, p)))
702 else:
703 while 1:
704 char = sourceget()
705 if char is None:
706 raise error("unexpected end of pattern")
707 if char == ")":
708 break
709 raise error("unknown extension")
710
711 elif this == "^":
712 subpatternappend((AT, AT_BEGINNING))
713
714 elif this == "$":
715 subpattern.append((AT, AT_END))
716
717 elif this and this[0] == "\\":
718 code = _escape(source, this, state, nested + 1)
719 subpatternappend(code)
720
721 else:
722 raise error("parser error")
723
724 return subpattern
725
726 def parse(str, flags=0, pattern=None):
727 # parse 're' pattern into list of (opcode, argument) tuples
728
729 source = Tokenizer(str)
730
731 if pattern is None:
732 pattern = Pattern()
733 pattern.flags = flags
734 pattern.str = str
735
736 p = _parse_sub(source, pattern, 0)
737 if (sys.py3kwarning and
738 (p.pattern.flags & SRE_FLAG_LOCALE) and
739 (p.pattern.flags & SRE_FLAG_UNICODE)):
740 import warnings
741 warnings.warnpy3k("LOCALE and UNICODE flags are incompatible",
742 DeprecationWarning, stacklevel=5)
743
744 tail = source.get()
745 if tail == ")":
746 raise error("unbalanced parenthesis")
747 elif tail:
748 raise error("bogus characters at end of regular expression")
749
750 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
751 # the VERBOSE flag was switched on inside the pattern. to be
752 # on the safe side, we'll parse the whole thing again...
753 return parse(str, p.pattern.flags)
754
755 if flags & SRE_FLAG_DEBUG:
756 p.dump()
757
758 return p
759
760 def parse_template(source, pattern):
761 # parse 're' replacement string into list of literals and
762 # group references
763 s = Tokenizer(source)
764 sget = s.get
765 p = []
766 a = p.append
767 def literal(literal, p=p, pappend=a):
768 if p and p[-1][0] is LITERAL:
769 p[-1] = LITERAL, p[-1][1] + literal
770 else:
771 pappend((LITERAL, literal))
772 sep = source[:0]
773 if type(sep) is type(""):
774 makechar = chr
775 else:
776 makechar = unichr
777 while 1:
778 this = sget()
779 if this is None:
780 break # end of replacement string
781 if this and this[0] == "\\":
782 # group
783 c = this[1:2]
784 if c == "g":
785 name = ""
786 if s.match("<"):
787 while 1:
788 char = sget()
789 if char is None:
790 raise error("unterminated group name")
791 if char == ">":
792 break
793 name = name + char
794 if not name:
795 raise error("missing group name")
796 try:
797 index = int(name)
798 if index < 0:
799 raise error("negative group number")
800 except ValueError:
801 if not isname(name):
802 raise error("bad character in group name")
803 try:
804 index = pattern.groupindex[name]
805 except KeyError:
806 msg = "unknown group name: {0!r}".format(name)
807 raise IndexError(msg)
808 a((MARK, index))
809 elif c == "0":
810 if s.next in OCTDIGITS:
811 this = this + sget()
812 if s.next in OCTDIGITS:
813 this = this + sget()
814 literal(makechar(int(this[1:], 8) & 0xff))
815 elif c in DIGITS:
816 isoctal = False
817 if s.next in DIGITS:
818 this = this + sget()
819 if (c in OCTDIGITS and this[2] in OCTDIGITS and
820 s.next in OCTDIGITS):
821 this = this + sget()
822 isoctal = True
823 literal(makechar(int(this[1:], 8) & 0xff))
824 if not isoctal:
825 a((MARK, int(this[1:])))
826 else:
827 try:
828 this = makechar(ESCAPES[this][1])
829 except KeyError:
830 if sys.py3kwarning and c in ASCIILETTERS:
831 import warnings
832 warnings.warnpy3k('bad escape %s' % this,
833 DeprecationWarning, stacklevel=4)
834 literal(this)
835 else:
836 literal(this)
837 # convert template to groups and literals lists
838 i = 0
839 groups = []
840 groupsappend = groups.append
841 literals = [None] * len(p)
842 for c, s in p:
843 if c is MARK:
844 groupsappend((i, s))
845 # literal[i] is already None
846 else:
847 literals[i] = s
848 i = i + 1
849 return groups, literals
850
851 def expand_template(template, match):
852 g = match.group
853 sep = match.string[:0]
854 groups, literals = template
855 literals = literals[:]
856 try:
857 for index, group in groups:
858 literals[index] = s = g(group)
859 if s is None:
860 raise error("unmatched group")
861 except IndexError:
862 raise error("invalid group reference")
863 return sep.join(literals)