blob: e37e2cfce3f81a6ffaba4b2e5eb3a9a35d13748c [file] [log] [blame]
Guido van Rossum7627c0d2000-03-31 14:58:54 +00001#
2# Secret Labs' Regular Expression Engine
Guido van Rossum7627c0d2000-03-31 14:58:54 +00003#
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +00004# convert re-style regular expression to sre pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +00005#
Fredrik Lundh770617b2001-01-14 15:06:11 +00006# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
Guido van Rossum7627c0d2000-03-31 14:58:54 +00007#
Fredrik Lundh29c4ba92000-08-01 18:20:07 +00008# See the sre.py file for information on usage and redistribution.
Guido van Rossum7627c0d2000-03-31 14:58:54 +00009#
10
Fred Drakeb8f22742001-09-04 19:10:20 +000011"""Internal support module for sre"""
12
Fredrik Lundh470ea5a2001-01-14 21:00:44 +000013# XXX: show string offset and offending character for all errors
14
Barry Warsaw8bee7612004-08-25 02:22:30 +000015import sys
Guido van Rossum7627c0d2000-03-31 14:58:54 +000016
17from sre_constants import *
18
19SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000020REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000021
Raymond Hettinger049ade22005-02-28 19:27:52 +000022DIGITS = set("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000023
Raymond Hettinger049ade22005-02-28 19:27:52 +000024OCTDIGITS = set("01234567")
25HEXDIGITS = set("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000026
Raymond Hettinger049ade22005-02-28 19:27:52 +000027WHITESPACE = set(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000028
Guido van Rossum7627c0d2000-03-31 14:58:54 +000029ESCAPES = {
Fredrik Lundhf2989b22001-02-18 12:05:16 +000030 r"\a": (LITERAL, ord("\a")),
31 r"\b": (LITERAL, ord("\b")),
32 r"\f": (LITERAL, ord("\f")),
33 r"\n": (LITERAL, ord("\n")),
34 r"\r": (LITERAL, ord("\r")),
35 r"\t": (LITERAL, ord("\t")),
36 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000037 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000038}
39
40CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000041 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000042 r"\b": (AT, AT_BOUNDARY),
43 r"\B": (AT, AT_NON_BOUNDARY),
44 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
45 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
46 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
47 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
48 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
49 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000050 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000051}
52
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000053FLAGS = {
Fredrik Lundh436c3d52000-06-29 08:58:44 +000054 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000055 "i": SRE_FLAG_IGNORECASE,
56 "L": SRE_FLAG_LOCALE,
57 "m": SRE_FLAG_MULTILINE,
58 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000059 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d52000-06-29 08:58:44 +000060 # extensions
61 "t": SRE_FLAG_TEMPLATE,
62 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000063}
64
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000065class Pattern:
66 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000067 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000068 self.flags = 0
Fredrik Lundhebc37b22000-10-28 19:30:41 +000069 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000070 self.groups = 1
71 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000072 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000073 gid = self.groups
74 self.groups = gid + 1
Raymond Hettingerf13eb552002-06-02 00:40:05 +000075 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000076 ogid = self.groupdict.get(name, None)
77 if ogid is not None:
Fredrik Lundh82b23072001-12-09 16:13:15 +000078 raise error, ("redefinition of group name %s as group %d; "
79 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000080 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000081 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000082 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000083 def closegroup(self, gid):
84 self.open.remove(gid)
85 def checkgroup(self, gid):
86 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000087
88class SubPattern:
89 # a subpattern, in intermediate form
90 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000091 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000092 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000093 data = []
94 self.data = data
95 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000096 def dump(self, level=0):
97 nl = 1
Raymond Hettinger968c56a2004-03-26 23:24:00 +000098 seqtypes = type(()), type([])
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000099 for op, av in self.data:
100 print level*" " + op,; nl = 0
101 if op == "in":
102 # member sublanguage
103 print; nl = 1
104 for op, a in av:
105 print (level+1)*" " + op, a
106 elif op == "branch":
107 print; nl = 1
108 i = 0
109 for a in av[1]:
110 if i > 0:
111 print level*" " + "or"
112 a.dump(level+1); nl = 1
113 i = i + 1
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000114 elif type(av) in seqtypes:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000115 for a in av:
116 if isinstance(a, SubPattern):
117 if not nl: print
118 a.dump(level+1); nl = 1
119 else:
120 print a, ; nl = 0
121 else:
122 print av, ; nl = 0
123 if not nl: print
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000124 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000125 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000126 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000127 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000128 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000129 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000130 def __getitem__(self, index):
Thomas Wouterse3a985f2006-12-19 08:17:50 +0000131 if isinstance(index, slice):
132 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000133 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000134 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000135 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000136 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000137 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000138 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000139 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000140 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000141 # determine the width (min, max) for this subpattern
142 if self.width:
143 return self.width
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300144 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000145 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
146 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000147 for op, av in self.data:
148 if op is BRANCH:
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300149 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000150 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000151 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000152 l, h = av.getwidth()
153 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000154 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000155 lo = lo + i
156 hi = hi + j
157 elif op is CALL:
158 i, j = av.getwidth()
159 lo = lo + i
160 hi = hi + j
161 elif op is SUBPATTERN:
162 i, j = av[1].getwidth()
163 lo = lo + i
164 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000165 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000166 i, j = av[2].getwidth()
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300167 lo = lo + i * av[0]
168 hi = hi + j * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000169 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000170 lo = lo + 1
171 hi = hi + 1
172 elif op == SUCCESS:
173 break
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300174 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000175 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000176
177class Tokenizer:
178 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000179 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000180 self.index = 0
181 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000182 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000183 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000184 self.next = None
185 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000186 char = self.string[self.index]
187 if char[0] == "\\":
188 try:
189 c = self.string[self.index + 1]
190 except IndexError:
Fredrik Lundh8a0232d2001-11-02 13:59:51 +0000191 raise error, "bogus escape (end of line)"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000192 char = char + c
193 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000194 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000195 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000196 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000197 if skip:
198 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000199 return 1
200 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000201 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000202 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000203 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000204 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000205 def tell(self):
206 return self.index, self.next
207 def seek(self, index):
208 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000209
Fredrik Lundh4781b072000-06-29 12:38:45 +0000210def isident(char):
211 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
212
213def isdigit(char):
214 return "0" <= char <= "9"
215
216def isname(name):
217 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000218 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000219 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000220 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000221 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000222 return False
223 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000224
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000225def _class_escape(source, escape):
226 # handle escape code inside character class
227 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000228 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000229 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000230 code = CATEGORIES.get(escape)
Ezio Melotti5c4e32b2013-01-11 08:32:01 +0200231 if code and code[0] == IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000232 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000233 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000234 c = escape[1:2]
235 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000236 # hexadecimal escape (exactly two digits)
237 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000238 escape = escape + source.get()
239 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000240 if len(escape) != 2:
241 raise error, "bogus escape: %s" % repr("\\" + escape)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000242 return LITERAL, int(escape, 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000243 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000244 # octal escape (up to three digits)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000245 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000246 escape = escape + source.get()
247 escape = escape[1:]
Barry Warsaw8bee7612004-08-25 02:22:30 +0000248 return LITERAL, int(escape, 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000249 elif c in DIGITS:
250 raise error, "bogus escape: %s" % repr(escape)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000251 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000252 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000253 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000254 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000255 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000256
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000257def _escape(source, escape, state):
258 # handle escape code in expression
259 code = CATEGORIES.get(escape)
260 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000261 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000262 code = ESCAPES.get(escape)
263 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000264 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000265 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000266 c = escape[1:2]
267 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000268 # hexadecimal escape
269 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000270 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000271 if len(escape) != 4:
272 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000273 return LITERAL, int(escape[2:], 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000274 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000275 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000276 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000277 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000278 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000279 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000280 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000281 if source.next in DIGITS:
282 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000283 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
284 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000285 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000286 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000287 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000288 # not an octal escape, so this is a group reference
289 group = int(escape[1:])
290 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000291 if not state.checkgroup(group):
292 raise error, "cannot refer to open group"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000293 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000294 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000295 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000296 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000297 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000298 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000299 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000300
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000301def _parse_sub(source, state, nested=1):
302 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000303
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000304 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000305 itemsappend = items.append
306 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000307 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000308 itemsappend(_parse(source, state))
309 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000310 continue
311 if not nested:
312 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000313 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000314 break
315 else:
316 raise error, "pattern not properly closed"
317
318 if len(items) == 1:
319 return items[0]
320
321 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000322 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000323
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000324 # check if all items share a common prefix
325 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000326 prefix = None
327 for item in items:
328 if not item:
329 break
330 if prefix is None:
331 prefix = item[0]
332 elif item[0] != prefix:
333 break
334 else:
335 # all subitems start with a common "prefix".
336 # move it out of the branch
337 for item in items:
338 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000339 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000340 continue # check next one
341 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000342
343 # check if the branch can be replaced by a character set
344 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000345 if len(item) != 1 or item[0][0] != LITERAL:
346 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000347 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000348 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000349 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000350 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000351 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000352 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000353 setappend(item[0])
354 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000355 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000356
357 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000358 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000359
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000360def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000361 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000362 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000363 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000364 if source.match("|"):
365 raise error, "conditional backref with more than two branches"
366 else:
367 item_no = None
368 if source.next and not source.match(")", 0):
369 raise error, "pattern not properly closed"
370 subpattern = SubPattern(state)
371 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
372 return subpattern
373
Raymond Hettinger049ade22005-02-28 19:27:52 +0000374_PATTERNENDERS = set("|)")
375_ASSERTCHARS = set("=!<")
376_LOOKBEHINDASSERTCHARS = set("=!")
377_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
378
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000379def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000380 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000381 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000382
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000383 # precompute constants into local variables
384 subpatternappend = subpattern.append
385 sourceget = source.get
386 sourcematch = source.match
387 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000388 PATTERNENDERS = _PATTERNENDERS
389 ASSERTCHARS = _ASSERTCHARS
390 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
391 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000392
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000393 while 1:
394
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000395 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000396 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000397 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000398 if this is None:
399 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000400
Fredrik Lundh90a07912000-06-30 07:50:59 +0000401 if state.flags & SRE_FLAG_VERBOSE:
402 # skip whitespace and comments
403 if this in WHITESPACE:
404 continue
405 if this == "#":
406 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000407 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000408 if this in (None, "\n"):
409 break
410 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000411
Fredrik Lundh90a07912000-06-30 07:50:59 +0000412 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000413 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000414
Fredrik Lundh90a07912000-06-30 07:50:59 +0000415 elif this == "[":
416 # character set
417 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000418 setappend = set.append
419## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000420## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000421 if sourcematch("^"):
422 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000423 # check remaining characters
424 start = set[:]
425 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000426 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000427 if this == "]" and set != start:
428 break
429 elif this and this[0] == "\\":
430 code1 = _class_escape(source, this)
431 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000432 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000433 else:
434 raise error, "unexpected end of regular expression"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000435 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000436 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000437 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000438 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000439 if code1[0] is IN:
440 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000441 setappend(code1)
442 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000443 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000444 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000445 if this[0] == "\\":
446 code2 = _class_escape(source, this)
447 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000448 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000449 if code1[0] != LITERAL or code2[0] != LITERAL:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000450 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000451 lo = code1[1]
452 hi = code2[1]
453 if hi < lo:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000454 raise error, "bad character range"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000455 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000456 else:
457 raise error, "unexpected end of regular expression"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000458 else:
459 if code1[0] is IN:
460 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000461 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000462
Fredrik Lundh770617b2001-01-14 15:06:11 +0000463 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000464 if _len(set)==1 and set[0][0] is LITERAL:
465 subpatternappend(set[0]) # optimization
466 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
467 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000468 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000469 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000470 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000471
Fredrik Lundh90a07912000-06-30 07:50:59 +0000472 elif this and this[0] in REPEAT_CHARS:
473 # repeat previous item
474 if this == "?":
475 min, max = 0, 1
476 elif this == "*":
477 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000478
Fredrik Lundh90a07912000-06-30 07:50:59 +0000479 elif this == "+":
480 min, max = 1, MAXREPEAT
481 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000482 if source.next == "}":
483 subpatternappend((LITERAL, ord(this)))
484 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000485 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000486 min, max = 0, MAXREPEAT
487 lo = hi = ""
488 while source.next in DIGITS:
489 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000490 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000491 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000492 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000493 else:
494 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000495 if not sourcematch("}"):
496 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000497 source.seek(here)
498 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000499 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000500 min = int(lo)
Serhiy Storchakae18e05c2013-02-16 16:47:15 +0200501 if min >= MAXREPEAT:
502 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000503 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000504 max = int(hi)
Serhiy Storchakae18e05c2013-02-16 16:47:15 +0200505 if max >= MAXREPEAT:
506 raise OverflowError("the repetition number is too large")
507 if max < min:
508 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000509 else:
510 raise error, "not supported"
511 # figure out which item to repeat
512 if subpattern:
513 item = subpattern[-1:]
514 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000515 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000516 if not item or (_len(item) == 1 and item[0][0] == AT):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000517 raise error, "nothing to repeat"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000518 if item[0][0] in REPEATCODES:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000519 raise error, "multiple repeat"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000520 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000521 subpattern[-1] = (MIN_REPEAT, (min, max, item))
522 else:
523 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000524
Fredrik Lundh90a07912000-06-30 07:50:59 +0000525 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000526 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000527
Fredrik Lundh90a07912000-06-30 07:50:59 +0000528 elif this == "(":
529 group = 1
530 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000531 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000532 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000533 group = 0
534 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000535 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000536 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000537 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000538 # named group: skip forward to end of name
539 name = ""
540 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000541 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000542 if char is None:
543 raise error, "unterminated name"
544 if char == ">":
545 break
546 name = name + char
547 group = 1
Ezio Melottief317382012-11-03 20:31:12 +0200548 if not name:
549 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000550 if not isname(name):
R David Murray60773392013-04-14 13:08:50 -0400551 raise error("bad character in group name %r" %
552 name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000553 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000554 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000555 name = ""
556 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000557 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000558 if char is None:
559 raise error, "unterminated name"
560 if char == ")":
561 break
562 name = name + char
Ezio Melottief317382012-11-03 20:31:12 +0200563 if not name:
564 raise error("missing group name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000565 if not isname(name):
R David Murray60773392013-04-14 13:08:50 -0400566 raise error("bad character in backref group name "
567 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000568 gid = state.groupdict.get(name)
569 if gid is None:
570 raise error, "unknown group name"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000571 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000572 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000573 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000574 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000575 if char is None:
576 raise error, "unexpected end of pattern"
577 raise error, "unknown specifier: ?P%s" % char
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000578 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000579 # non-capturing group
580 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000581 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000582 # comment
583 while 1:
584 if source.next is None or source.next == ")":
585 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000586 sourceget()
587 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000588 raise error, "unbalanced parenthesis"
589 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000590 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000591 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000592 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000593 dir = 1
594 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000595 if source.next not in LOOKBEHINDASSERTCHARS:
Fredrik Lundh6f013982000-07-03 18:44:21 +0000596 raise error, "syntax error"
597 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000598 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000599 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000600 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000601 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000602 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000603 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000604 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000605 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000606 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000607 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000608 # conditional backreference group
609 condname = ""
610 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000611 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000612 if char is None:
613 raise error, "unterminated name"
614 if char == ")":
615 break
616 condname = condname + char
617 group = 2
Ezio Melottief317382012-11-03 20:31:12 +0200618 if not condname:
619 raise error("missing group name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000620 if isname(condname):
621 condgroup = state.groupdict.get(condname)
622 if condgroup is None:
623 raise error, "unknown group name"
624 else:
625 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000626 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000627 except ValueError:
628 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000629 else:
630 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000631 if not source.next in FLAGS:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000632 raise error, "unexpected end of pattern"
Raymond Hettinger54f02222002-06-01 14:18:47 +0000633 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000634 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000635 if group:
636 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000637 if group == 2:
638 # anonymous group
639 group = None
640 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000641 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000642 if condgroup:
643 p = _parse_sub_cond(source, state, condgroup)
644 else:
645 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000646 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000647 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000648 if group is not None:
649 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000650 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000651 else:
652 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000653 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000654 if char is None:
655 raise error, "unexpected end of pattern"
656 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000657 break
658 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000659
Fredrik Lundh90a07912000-06-30 07:50:59 +0000660 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000661 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000662
Fredrik Lundh90a07912000-06-30 07:50:59 +0000663 elif this == "$":
664 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000665
Fredrik Lundh90a07912000-06-30 07:50:59 +0000666 elif this and this[0] == "\\":
667 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000668 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000669
Fredrik Lundh90a07912000-06-30 07:50:59 +0000670 else:
671 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000672
673 return subpattern
674
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000675def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000676 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000677
678 source = Tokenizer(str)
679
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000680 if pattern is None:
681 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000682 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000683 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000684
685 p = _parse_sub(source, pattern, 0)
686
687 tail = source.get()
688 if tail == ")":
689 raise error, "unbalanced parenthesis"
690 elif tail:
691 raise error, "bogus characters at end of regular expression"
692
Fredrik Lundh770617b2001-01-14 15:06:11 +0000693 if flags & SRE_FLAG_DEBUG:
694 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000695
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000696 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
697 # the VERBOSE flag was switched on inside the pattern. to be
698 # on the safe side, we'll parse the whole thing again...
699 return parse(str, p.pattern.flags)
700
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000701 return p
702
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000703def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000704 # parse 're' replacement string into list of literals and
705 # group references
706 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000707 sget = s.get
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000708 p = []
709 a = p.append
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000710 def literal(literal, p=p, pappend=a):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000711 if p and p[-1][0] is LITERAL:
712 p[-1] = LITERAL, p[-1][1] + literal
713 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000714 pappend((LITERAL, literal))
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000715 sep = source[:0]
716 if type(sep) is type(""):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000717 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000718 else:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000719 makechar = unichr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000720 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000721 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000722 if this is None:
723 break # end of replacement string
724 if this and this[0] == "\\":
725 # group
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000726 c = this[1:2]
727 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000728 name = ""
729 if s.match("<"):
730 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000731 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000732 if char is None:
733 raise error, "unterminated group name"
734 if char == ">":
735 break
736 name = name + char
737 if not name:
Ezio Melottief317382012-11-03 20:31:12 +0200738 raise error, "missing group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000739 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000740 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000741 if index < 0:
742 raise error, "negative group number"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000743 except ValueError:
744 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000745 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000746 try:
747 index = pattern.groupindex[name]
748 except KeyError:
749 raise IndexError, "unknown group name"
750 a((MARK, index))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000751 elif c == "0":
752 if s.next in OCTDIGITS:
753 this = this + sget()
754 if s.next in OCTDIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000755 this = this + sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000756 literal(makechar(int(this[1:], 8) & 0xff))
757 elif c in DIGITS:
758 isoctal = False
759 if s.next in DIGITS:
760 this = this + sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000761 if (c in OCTDIGITS and this[2] in OCTDIGITS and
762 s.next in OCTDIGITS):
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000763 this = this + sget()
764 isoctal = True
765 literal(makechar(int(this[1:], 8) & 0xff))
766 if not isoctal:
767 a((MARK, int(this[1:])))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000768 else:
769 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000770 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000771 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000772 pass
773 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000774 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000775 literal(this)
776 # convert template to groups and literals lists
777 i = 0
778 groups = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000779 groupsappend = groups.append
780 literals = [None] * len(p)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000781 for c, s in p:
782 if c is MARK:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000783 groupsappend((i, s))
784 # literal[i] is already None
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000785 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000786 literals[i] = s
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000787 i = i + 1
788 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000789
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000790def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000791 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000792 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000793 groups, literals = template
794 literals = literals[:]
795 try:
796 for index, group in groups:
797 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000798 if s is None:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000799 raise error, "unmatched group"
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000800 except IndexError:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000801 raise error, "invalid group reference"
Barry Warsaw8bee7612004-08-25 02:22:30 +0000802 return sep.join(literals)