blob: 319bf43b33f048d8f4528e876592f7ca7b71a591 [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
Raymond Hettinger049ade22005-02-28 19:27:52 +000019def set(seq):
20 s = {}
21 for elem in seq:
22 s[elem] = 1
23 return s
24
Guido van Rossum7627c0d2000-03-31 14:58:54 +000025SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000026REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000027
Raymond Hettinger049ade22005-02-28 19:27:52 +000028DIGITS = set("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000029
Raymond Hettinger049ade22005-02-28 19:27:52 +000030OCTDIGITS = set("01234567")
31HEXDIGITS = set("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000032
Raymond Hettinger049ade22005-02-28 19:27:52 +000033WHITESPACE = set(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000034
Guido van Rossum7627c0d2000-03-31 14:58:54 +000035ESCAPES = {
Fredrik Lundhf2989b22001-02-18 12:05:16 +000036 r"\a": (LITERAL, ord("\a")),
37 r"\b": (LITERAL, ord("\b")),
38 r"\f": (LITERAL, ord("\f")),
39 r"\n": (LITERAL, ord("\n")),
40 r"\r": (LITERAL, ord("\r")),
41 r"\t": (LITERAL, ord("\t")),
42 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000043 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000044}
45
46CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000047 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000048 r"\b": (AT, AT_BOUNDARY),
49 r"\B": (AT, AT_NON_BOUNDARY),
50 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
51 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
52 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
53 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
54 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
55 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000056 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000057}
58
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000059FLAGS = {
Fredrik Lundh436c3d582000-06-29 08:58:44 +000060 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000061 "i": SRE_FLAG_IGNORECASE,
62 "L": SRE_FLAG_LOCALE,
63 "m": SRE_FLAG_MULTILINE,
64 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000065 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000066 # extensions
67 "t": SRE_FLAG_TEMPLATE,
68 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000069}
70
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000071class Pattern:
72 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000073 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000074 self.flags = 0
Fredrik Lundhebc37b22000-10-28 19:30:41 +000075 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000076 self.groups = 1
77 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000078 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000079 gid = self.groups
80 self.groups = gid + 1
Raymond Hettingerf13eb552002-06-02 00:40:05 +000081 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000082 ogid = self.groupdict.get(name, None)
83 if ogid is not None:
Fredrik Lundh82b23072001-12-09 16:13:15 +000084 raise error, ("redefinition of group name %s as group %d; "
85 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000086 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000087 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000088 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000089 def closegroup(self, gid):
90 self.open.remove(gid)
91 def checkgroup(self, gid):
92 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000093
94class SubPattern:
95 # a subpattern, in intermediate form
96 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000097 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000098 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000099 data = []
100 self.data = data
101 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000102 def dump(self, level=0):
103 nl = 1
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000104 seqtypes = type(()), type([])
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000105 for op, av in self.data:
106 print level*" " + op,; nl = 0
107 if op == "in":
108 # member sublanguage
109 print; nl = 1
110 for op, a in av:
111 print (level+1)*" " + op, a
112 elif op == "branch":
113 print; nl = 1
114 i = 0
115 for a in av[1]:
116 if i > 0:
117 print level*" " + "or"
118 a.dump(level+1); nl = 1
119 i = i + 1
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000120 elif type(av) in seqtypes:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000121 for a in av:
122 if isinstance(a, SubPattern):
123 if not nl: print
124 a.dump(level+1); nl = 1
125 else:
126 print a, ; nl = 0
127 else:
128 print av, ; nl = 0
129 if not nl: print
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000130 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000131 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000132 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000133 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000134 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000135 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000136 def __getitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000137 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000138 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000139 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000140 def __getslice__(self, start, stop):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000141 return SubPattern(self.pattern, self.data[start:stop])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000142 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000143 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000144 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000145 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000146 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000147 # determine the width (min, max) for this subpattern
148 if self.width:
149 return self.width
150 lo = hi = 0L
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000151 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
152 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000153 for op, av in self.data:
154 if op is BRANCH:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000155 i = sys.maxint
156 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000157 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000158 l, h = av.getwidth()
159 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000160 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000161 lo = lo + i
162 hi = hi + j
163 elif op is CALL:
164 i, j = av.getwidth()
165 lo = lo + i
166 hi = hi + j
167 elif op is SUBPATTERN:
168 i, j = av[1].getwidth()
169 lo = lo + i
170 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000171 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000172 i, j = av[2].getwidth()
173 lo = lo + long(i) * av[0]
174 hi = hi + long(j) * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000175 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000176 lo = lo + 1
177 hi = hi + 1
178 elif op == SUCCESS:
179 break
180 self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint))
181 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000182
183class Tokenizer:
184 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000185 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000186 self.index = 0
187 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000188 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000189 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000190 self.next = None
191 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000192 char = self.string[self.index]
193 if char[0] == "\\":
194 try:
195 c = self.string[self.index + 1]
196 except IndexError:
Fredrik Lundh8a0232d2001-11-02 13:59:51 +0000197 raise error, "bogus escape (end of line)"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000198 char = char + c
199 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000200 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000201 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000202 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000203 if skip:
204 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000205 return 1
206 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000207 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000208 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000209 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000210 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000211 def tell(self):
212 return self.index, self.next
213 def seek(self, index):
214 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000215
Fredrik Lundh4781b072000-06-29 12:38:45 +0000216def isident(char):
217 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
218
219def isdigit(char):
220 return "0" <= char <= "9"
221
222def isname(name):
223 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000224 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000225 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000226 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000227 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000228 return False
229 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000230
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000231def _class_escape(source, escape):
232 # handle escape code inside character class
233 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000234 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000235 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000236 code = CATEGORIES.get(escape)
237 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000238 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000239 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000240 c = escape[1:2]
241 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000242 # hexadecimal escape (exactly two digits)
243 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000244 escape = escape + source.get()
245 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000246 if len(escape) != 2:
247 raise error, "bogus escape: %s" % repr("\\" + escape)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000248 return LITERAL, int(escape, 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000249 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000250 # octal escape (up to three digits)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000251 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000252 escape = escape + source.get()
253 escape = escape[1:]
Barry Warsaw8bee7612004-08-25 02:22:30 +0000254 return LITERAL, int(escape, 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000255 elif c in DIGITS:
256 raise error, "bogus escape: %s" % repr(escape)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000257 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000258 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000259 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000260 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000261 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000262
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000263def _escape(source, escape, state):
264 # handle escape code in expression
265 code = CATEGORIES.get(escape)
266 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000267 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000268 code = ESCAPES.get(escape)
269 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000270 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000271 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000272 c = escape[1:2]
273 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000274 # hexadecimal escape
275 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000276 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000277 if len(escape) != 4:
278 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000279 return LITERAL, int(escape[2:], 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000280 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000281 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000282 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000283 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000284 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000285 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000286 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000287 if source.next in DIGITS:
288 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000289 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
290 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000291 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000292 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000293 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000294 # not an octal escape, so this is a group reference
295 group = int(escape[1:])
296 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000297 if not state.checkgroup(group):
298 raise error, "cannot refer to open group"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000299 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000300 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000301 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000302 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000303 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000304 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000305 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000306
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000307def _parse_sub(source, state, nested=1):
308 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000309
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000310 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000311 itemsappend = items.append
312 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000313 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000314 itemsappend(_parse(source, state))
315 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000316 continue
317 if not nested:
318 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000319 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000320 break
321 else:
322 raise error, "pattern not properly closed"
323
324 if len(items) == 1:
325 return items[0]
326
327 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000328 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000329
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000330 # check if all items share a common prefix
331 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000332 prefix = None
333 for item in items:
334 if not item:
335 break
336 if prefix is None:
337 prefix = item[0]
338 elif item[0] != prefix:
339 break
340 else:
341 # all subitems start with a common "prefix".
342 # move it out of the branch
343 for item in items:
344 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000345 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000346 continue # check next one
347 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000348
349 # check if the branch can be replaced by a character set
350 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000351 if len(item) != 1 or item[0][0] != LITERAL:
352 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000353 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000354 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000355 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000356 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000357 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000358 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000359 setappend(item[0])
360 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000361 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000362
363 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000364 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000365
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000366def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000367 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000368 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000369 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000370 if source.match("|"):
371 raise error, "conditional backref with more than two branches"
372 else:
373 item_no = None
374 if source.next and not source.match(")", 0):
375 raise error, "pattern not properly closed"
376 subpattern = SubPattern(state)
377 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
378 return subpattern
379
Raymond Hettinger049ade22005-02-28 19:27:52 +0000380_PATTERNENDERS = set("|)")
381_ASSERTCHARS = set("=!<")
382_LOOKBEHINDASSERTCHARS = set("=!")
383_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
384
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000385def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000386 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000387 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000388
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000389 # precompute constants into local variables
390 subpatternappend = subpattern.append
391 sourceget = source.get
392 sourcematch = source.match
393 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000394 PATTERNENDERS = _PATTERNENDERS
395 ASSERTCHARS = _ASSERTCHARS
396 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
397 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000398
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000399 while 1:
400
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000401 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000402 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000403 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000404 if this is None:
405 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000406
Fredrik Lundh90a07912000-06-30 07:50:59 +0000407 if state.flags & SRE_FLAG_VERBOSE:
408 # skip whitespace and comments
409 if this in WHITESPACE:
410 continue
411 if this == "#":
412 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000413 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000414 if this in (None, "\n"):
415 break
416 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000417
Fredrik Lundh90a07912000-06-30 07:50:59 +0000418 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000419 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000420
Fredrik Lundh90a07912000-06-30 07:50:59 +0000421 elif this == "[":
422 # character set
423 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000424 setappend = set.append
425## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000426## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000427 if sourcematch("^"):
428 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000429 # check remaining characters
430 start = set[:]
431 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000432 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000433 if this == "]" and set != start:
434 break
435 elif this and this[0] == "\\":
436 code1 = _class_escape(source, this)
437 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000438 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000439 else:
440 raise error, "unexpected end of regular expression"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000441 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000442 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000443 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000444 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000445 if code1[0] is IN:
446 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000447 setappend(code1)
448 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000449 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000450 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000451 if this[0] == "\\":
452 code2 = _class_escape(source, this)
453 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000454 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000455 if code1[0] != LITERAL or code2[0] != LITERAL:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000456 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000457 lo = code1[1]
458 hi = code2[1]
459 if hi < lo:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000460 raise error, "bad character range"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000461 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000462 else:
463 raise error, "unexpected end of regular expression"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000464 else:
465 if code1[0] is IN:
466 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000467 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000468
Fredrik Lundh770617b2001-01-14 15:06:11 +0000469 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000470 if _len(set)==1 and set[0][0] is LITERAL:
471 subpatternappend(set[0]) # optimization
472 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
473 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000474 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000475 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000476 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000477
Fredrik Lundh90a07912000-06-30 07:50:59 +0000478 elif this and this[0] in REPEAT_CHARS:
479 # repeat previous item
480 if this == "?":
481 min, max = 0, 1
482 elif this == "*":
483 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000484
Fredrik Lundh90a07912000-06-30 07:50:59 +0000485 elif this == "+":
486 min, max = 1, MAXREPEAT
487 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000488 if source.next == "}":
489 subpatternappend((LITERAL, ord(this)))
490 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000491 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000492 min, max = 0, MAXREPEAT
493 lo = hi = ""
494 while source.next in DIGITS:
495 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000496 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000497 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000498 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000499 else:
500 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000501 if not sourcematch("}"):
502 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000503 source.seek(here)
504 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000505 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000506 min = int(lo)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000507 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000508 max = int(hi)
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000509 if max < min:
510 raise error, "bad repeat interval"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000511 else:
512 raise error, "not supported"
513 # figure out which item to repeat
514 if subpattern:
515 item = subpattern[-1:]
516 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000517 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000518 if not item or (_len(item) == 1 and item[0][0] == AT):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000519 raise error, "nothing to repeat"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000520 if item[0][0] in REPEATCODES:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000521 raise error, "multiple repeat"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000522 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000523 subpattern[-1] = (MIN_REPEAT, (min, max, item))
524 else:
525 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000526
Fredrik Lundh90a07912000-06-30 07:50:59 +0000527 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000528 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000529
Fredrik Lundh90a07912000-06-30 07:50:59 +0000530 elif this == "(":
531 group = 1
532 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000533 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000534 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000535 group = 0
536 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000537 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000538 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000539 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000540 # named group: skip forward to end of name
541 name = ""
542 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000543 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000544 if char is None:
545 raise error, "unterminated name"
546 if char == ">":
547 break
548 name = name + char
549 group = 1
550 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000551 raise error, "bad character in group name"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000552 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000553 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000554 name = ""
555 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000556 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000557 if char is None:
558 raise error, "unterminated name"
559 if char == ")":
560 break
561 name = name + char
562 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000563 raise error, "bad character in group name"
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000564 gid = state.groupdict.get(name)
565 if gid is None:
566 raise error, "unknown group name"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000567 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000568 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000569 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000570 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000571 if char is None:
572 raise error, "unexpected end of pattern"
573 raise error, "unknown specifier: ?P%s" % char
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000574 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000575 # non-capturing group
576 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000577 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000578 # comment
579 while 1:
580 if source.next is None or source.next == ")":
581 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000582 sourceget()
583 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000584 raise error, "unbalanced parenthesis"
585 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000586 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000587 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000588 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000589 dir = 1
590 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000591 if source.next not in LOOKBEHINDASSERTCHARS:
Fredrik Lundh6f013982000-07-03 18:44:21 +0000592 raise error, "syntax error"
593 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000594 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000595 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000596 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000597 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000598 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000599 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000600 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000601 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000602 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000603 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000604 # conditional backreference group
605 condname = ""
606 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000607 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000608 if char is None:
609 raise error, "unterminated name"
610 if char == ")":
611 break
612 condname = condname + char
613 group = 2
614 if isname(condname):
615 condgroup = state.groupdict.get(condname)
616 if condgroup is None:
617 raise error, "unknown group name"
618 else:
619 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000620 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000621 except ValueError:
622 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000623 else:
624 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000625 if not source.next in FLAGS:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000626 raise error, "unexpected end of pattern"
Raymond Hettinger54f02222002-06-01 14:18:47 +0000627 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000628 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000629 if group:
630 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000631 if group == 2:
632 # anonymous group
633 group = None
634 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000635 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000636 if condgroup:
637 p = _parse_sub_cond(source, state, condgroup)
638 else:
639 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000640 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000641 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000642 if group is not None:
643 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000644 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000645 else:
646 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000647 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000648 if char is None:
649 raise error, "unexpected end of pattern"
650 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000651 break
652 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000653
Fredrik Lundh90a07912000-06-30 07:50:59 +0000654 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000655 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000656
Fredrik Lundh90a07912000-06-30 07:50:59 +0000657 elif this == "$":
658 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000659
Fredrik Lundh90a07912000-06-30 07:50:59 +0000660 elif this and this[0] == "\\":
661 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000662 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000663
Fredrik Lundh90a07912000-06-30 07:50:59 +0000664 else:
665 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000666
667 return subpattern
668
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000669def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000670 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000671
672 source = Tokenizer(str)
673
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000674 if pattern is None:
675 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000676 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000677 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000678
679 p = _parse_sub(source, pattern, 0)
680
681 tail = source.get()
682 if tail == ")":
683 raise error, "unbalanced parenthesis"
684 elif tail:
685 raise error, "bogus characters at end of regular expression"
686
Fredrik Lundh770617b2001-01-14 15:06:11 +0000687 if flags & SRE_FLAG_DEBUG:
688 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000689
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000690 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
691 # the VERBOSE flag was switched on inside the pattern. to be
692 # on the safe side, we'll parse the whole thing again...
693 return parse(str, p.pattern.flags)
694
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000695 return p
696
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000697def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000698 # parse 're' replacement string into list of literals and
699 # group references
700 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000701 sget = s.get
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000702 p = []
703 a = p.append
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000704 def literal(literal, p=p, pappend=a):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000705 if p and p[-1][0] is LITERAL:
706 p[-1] = LITERAL, p[-1][1] + literal
707 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000708 pappend((LITERAL, literal))
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000709 sep = source[:0]
710 if type(sep) is type(""):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000711 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000712 else:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000713 makechar = unichr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000714 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000715 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000716 if this is None:
717 break # end of replacement string
718 if this and this[0] == "\\":
719 # group
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000720 c = this[1:2]
721 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000722 name = ""
723 if s.match("<"):
724 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000725 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000726 if char is None:
727 raise error, "unterminated group name"
728 if char == ">":
729 break
730 name = name + char
731 if not name:
732 raise error, "bad group name"
733 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000734 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000735 if index < 0:
736 raise error, "negative group number"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000737 except ValueError:
738 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000739 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000740 try:
741 index = pattern.groupindex[name]
742 except KeyError:
743 raise IndexError, "unknown group name"
744 a((MARK, index))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000745 elif c == "0":
746 if s.next in OCTDIGITS:
747 this = this + sget()
748 if s.next in OCTDIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000749 this = this + sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000750 literal(makechar(int(this[1:], 8) & 0xff))
751 elif c in DIGITS:
752 isoctal = False
753 if s.next in DIGITS:
754 this = this + sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000755 if (c in OCTDIGITS and this[2] in OCTDIGITS and
756 s.next in OCTDIGITS):
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000757 this = this + sget()
758 isoctal = True
759 literal(makechar(int(this[1:], 8) & 0xff))
760 if not isoctal:
761 a((MARK, int(this[1:])))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000762 else:
763 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000764 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000765 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000766 pass
767 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000768 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000769 literal(this)
770 # convert template to groups and literals lists
771 i = 0
772 groups = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000773 groupsappend = groups.append
774 literals = [None] * len(p)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000775 for c, s in p:
776 if c is MARK:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000777 groupsappend((i, s))
778 # literal[i] is already None
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000779 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000780 literals[i] = s
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000781 i = i + 1
782 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000783
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000784def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000785 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000786 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000787 groups, literals = template
788 literals = literals[:]
789 try:
790 for index, group in groups:
791 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000792 if s is None:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000793 raise error, "unmatched group"
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000794 except IndexError:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000795 raise error, "invalid group reference"
Barry Warsaw8bee7612004-08-25 02:22:30 +0000796 return sep.join(literals)