blob: b85ce88c34cd5c53ff03592540a036d3137deecd [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):
Serhiy Storchakac0799e32014-09-21 22:47:30 +030097 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000098 for op, av in self.data:
Serhiy Storchakac0799e32014-09-21 22:47:30 +030099 print level*" " + op,
100 if op == IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000101 # member sublanguage
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300102 print
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000103 for op, a in av:
104 print (level+1)*" " + op, a
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300105 elif op == BRANCH:
106 print
107 for i, a in enumerate(av[1]):
108 if i:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000109 print level*" " + "or"
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300110 a.dump(level+1)
111 elif op == GROUPREF_EXISTS:
112 condgroup, item_yes, item_no = av
113 print condgroup
114 item_yes.dump(level+1)
115 if item_no:
116 print level*" " + "else"
117 item_no.dump(level+1)
118 elif isinstance(av, seqtypes):
119 nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000120 for a in av:
121 if isinstance(a, SubPattern):
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300122 if not nl:
123 print
124 a.dump(level+1)
125 nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000126 else:
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300127 print a,
128 nl = 0
129 if not nl:
130 print
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000131 else:
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300132 print av
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000133 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000134 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000135 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000136 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000137 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000138 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000139 def __getitem__(self, index):
Thomas Wouterse3a985f2006-12-19 08:17:50 +0000140 if isinstance(index, slice):
141 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000142 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000143 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000144 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000145 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000146 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000147 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000148 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000149 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000150 # determine the width (min, max) for this subpattern
151 if self.width:
152 return self.width
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300153 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000154 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
155 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000156 for op, av in self.data:
157 if op is BRANCH:
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300158 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000159 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000160 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000161 l, h = av.getwidth()
162 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000163 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000164 lo = lo + i
165 hi = hi + j
166 elif op is CALL:
167 i, j = av.getwidth()
168 lo = lo + i
169 hi = hi + j
170 elif op is SUBPATTERN:
171 i, j = av[1].getwidth()
172 lo = lo + i
173 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000174 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000175 i, j = av[2].getwidth()
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300176 lo = lo + i * av[0]
177 hi = hi + j * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000178 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000179 lo = lo + 1
180 hi = hi + 1
181 elif op == SUCCESS:
182 break
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300183 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000184 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000185
186class Tokenizer:
187 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000188 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000189 self.index = 0
190 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000191 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000192 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000193 self.next = None
194 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000195 char = self.string[self.index]
196 if char[0] == "\\":
197 try:
198 c = self.string[self.index + 1]
199 except IndexError:
Fredrik Lundh8a0232d2001-11-02 13:59:51 +0000200 raise error, "bogus escape (end of line)"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000201 char = char + c
202 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000203 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000204 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000205 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000206 if skip:
207 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000208 return 1
209 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000210 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000211 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000212 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000213 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000214 def tell(self):
215 return self.index, self.next
216 def seek(self, index):
217 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000218
Fredrik Lundh4781b072000-06-29 12:38:45 +0000219def isident(char):
220 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
221
222def isdigit(char):
223 return "0" <= char <= "9"
224
225def isname(name):
226 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000227 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000228 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000229 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000230 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000231 return False
232 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000233
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000234def _class_escape(source, escape):
235 # handle escape code inside character class
236 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000237 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000238 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000239 code = CATEGORIES.get(escape)
Ezio Melotti5c4e32b2013-01-11 08:32:01 +0200240 if code and code[0] == IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000241 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000242 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000243 c = escape[1:2]
244 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000245 # hexadecimal escape (exactly two digits)
246 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000247 escape = escape + source.get()
248 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000249 if len(escape) != 2:
250 raise error, "bogus escape: %s" % repr("\\" + escape)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000251 return LITERAL, int(escape, 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000252 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000253 # octal escape (up to three digits)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000254 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000255 escape = escape + source.get()
256 escape = escape[1:]
Barry Warsaw8bee7612004-08-25 02:22:30 +0000257 return LITERAL, int(escape, 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000258 elif c in DIGITS:
259 raise error, "bogus escape: %s" % repr(escape)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000260 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000261 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000262 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000263 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000264 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000265
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000266def _escape(source, escape, state):
267 # handle escape code in expression
268 code = CATEGORIES.get(escape)
269 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000270 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000271 code = ESCAPES.get(escape)
272 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000273 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000274 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000275 c = escape[1:2]
276 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000277 # hexadecimal escape
278 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000279 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000280 if len(escape) != 4:
281 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000282 return LITERAL, int(escape[2:], 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000283 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000284 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000285 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +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 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000289 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000290 if source.next in DIGITS:
291 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000292 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
293 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000294 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000295 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000296 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000297 # not an octal escape, so this is a group reference
298 group = int(escape[1:])
299 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000300 if not state.checkgroup(group):
301 raise error, "cannot refer to open group"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000302 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000303 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000304 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000305 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000306 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000307 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000308 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000309
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000310def _parse_sub(source, state, nested=1):
311 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000312
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000313 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000314 itemsappend = items.append
315 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000316 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000317 itemsappend(_parse(source, state))
318 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000319 continue
320 if not nested:
321 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000322 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000323 break
324 else:
325 raise error, "pattern not properly closed"
326
327 if len(items) == 1:
328 return items[0]
329
330 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000331 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000332
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000333 # check if all items share a common prefix
334 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000335 prefix = None
336 for item in items:
337 if not item:
338 break
339 if prefix is None:
340 prefix = item[0]
341 elif item[0] != prefix:
342 break
343 else:
344 # all subitems start with a common "prefix".
345 # move it out of the branch
346 for item in items:
347 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000348 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000349 continue # check next one
350 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000351
352 # check if the branch can be replaced by a character set
353 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000354 if len(item) != 1 or item[0][0] != LITERAL:
355 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000356 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000357 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000358 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000359 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000360 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000361 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000362 setappend(item[0])
363 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000364 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000365
366 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000367 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000368
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000369def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000370 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000371 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000372 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000373 if source.match("|"):
374 raise error, "conditional backref with more than two branches"
375 else:
376 item_no = None
377 if source.next and not source.match(")", 0):
378 raise error, "pattern not properly closed"
379 subpattern = SubPattern(state)
380 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
381 return subpattern
382
Raymond Hettinger049ade22005-02-28 19:27:52 +0000383_PATTERNENDERS = set("|)")
384_ASSERTCHARS = set("=!<")
385_LOOKBEHINDASSERTCHARS = set("=!")
386_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
387
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000388def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000389 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000390 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000391
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000392 # precompute constants into local variables
393 subpatternappend = subpattern.append
394 sourceget = source.get
395 sourcematch = source.match
396 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000397 PATTERNENDERS = _PATTERNENDERS
398 ASSERTCHARS = _ASSERTCHARS
399 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
400 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000401
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000402 while 1:
403
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000404 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000405 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000406 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000407 if this is None:
408 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000409
Fredrik Lundh90a07912000-06-30 07:50:59 +0000410 if state.flags & SRE_FLAG_VERBOSE:
411 # skip whitespace and comments
412 if this in WHITESPACE:
413 continue
414 if this == "#":
415 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000416 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000417 if this in (None, "\n"):
418 break
419 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000420
Fredrik Lundh90a07912000-06-30 07:50:59 +0000421 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000422 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000423
Fredrik Lundh90a07912000-06-30 07:50:59 +0000424 elif this == "[":
425 # character set
426 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000427 setappend = set.append
428## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000429## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000430 if sourcematch("^"):
431 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000432 # check remaining characters
433 start = set[:]
434 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000435 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000436 if this == "]" and set != start:
437 break
438 elif this and this[0] == "\\":
439 code1 = _class_escape(source, this)
440 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000441 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000442 else:
443 raise error, "unexpected end of regular expression"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000444 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000445 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000446 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000447 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000448 if code1[0] is IN:
449 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000450 setappend(code1)
451 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000452 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000453 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000454 if this[0] == "\\":
455 code2 = _class_escape(source, this)
456 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000457 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000458 if code1[0] != LITERAL or code2[0] != LITERAL:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000459 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000460 lo = code1[1]
461 hi = code2[1]
462 if hi < lo:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000463 raise error, "bad character range"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000464 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000465 else:
466 raise error, "unexpected end of regular expression"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000467 else:
468 if code1[0] is IN:
469 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000470 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000471
Fredrik Lundh770617b2001-01-14 15:06:11 +0000472 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000473 if _len(set)==1 and set[0][0] is LITERAL:
474 subpatternappend(set[0]) # optimization
475 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
476 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000477 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000478 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000479 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000480
Fredrik Lundh90a07912000-06-30 07:50:59 +0000481 elif this and this[0] in REPEAT_CHARS:
482 # repeat previous item
483 if this == "?":
484 min, max = 0, 1
485 elif this == "*":
486 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000487
Fredrik Lundh90a07912000-06-30 07:50:59 +0000488 elif this == "+":
489 min, max = 1, MAXREPEAT
490 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000491 if source.next == "}":
492 subpatternappend((LITERAL, ord(this)))
493 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000494 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000495 min, max = 0, MAXREPEAT
496 lo = hi = ""
497 while source.next in DIGITS:
498 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000499 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000500 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000501 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000502 else:
503 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000504 if not sourcematch("}"):
505 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000506 source.seek(here)
507 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000508 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000509 min = int(lo)
Serhiy Storchakae18e05c2013-02-16 16:47:15 +0200510 if min >= MAXREPEAT:
511 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000512 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000513 max = int(hi)
Serhiy Storchakae18e05c2013-02-16 16:47:15 +0200514 if max >= MAXREPEAT:
515 raise OverflowError("the repetition number is too large")
516 if max < min:
517 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000518 else:
519 raise error, "not supported"
520 # figure out which item to repeat
521 if subpattern:
522 item = subpattern[-1:]
523 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000524 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000525 if not item or (_len(item) == 1 and item[0][0] == AT):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000526 raise error, "nothing to repeat"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000527 if item[0][0] in REPEATCODES:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000528 raise error, "multiple repeat"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000529 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000530 subpattern[-1] = (MIN_REPEAT, (min, max, item))
531 else:
532 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000533
Fredrik Lundh90a07912000-06-30 07:50:59 +0000534 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000535 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000536
Fredrik Lundh90a07912000-06-30 07:50:59 +0000537 elif this == "(":
538 group = 1
539 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000540 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000541 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000542 group = 0
543 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000544 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000545 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000546 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000547 # named group: skip forward to end of name
548 name = ""
549 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000550 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000551 if char is None:
552 raise error, "unterminated name"
553 if char == ">":
554 break
555 name = name + char
556 group = 1
Ezio Melottief317382012-11-03 20:31:12 +0200557 if not name:
558 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000559 if not isname(name):
R David Murray60773392013-04-14 13:08:50 -0400560 raise error("bad character in group name %r" %
561 name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000562 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000563 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000564 name = ""
565 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000566 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000567 if char is None:
568 raise error, "unterminated name"
569 if char == ")":
570 break
571 name = name + char
Ezio Melottief317382012-11-03 20:31:12 +0200572 if not name:
573 raise error("missing group name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000574 if not isname(name):
R David Murray60773392013-04-14 13:08:50 -0400575 raise error("bad character in backref group name "
576 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000577 gid = state.groupdict.get(name)
578 if gid is None:
Raymond Hettingerf595a122014-06-22 19:33:19 -0700579 msg = "unknown group name: {0!r}".format(name)
580 raise error(msg)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000581 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000582 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000583 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000584 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000585 if char is None:
586 raise error, "unexpected end of pattern"
587 raise error, "unknown specifier: ?P%s" % char
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000588 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000589 # non-capturing group
590 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000591 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000592 # comment
593 while 1:
594 if source.next is None or source.next == ")":
595 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000596 sourceget()
597 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000598 raise error, "unbalanced parenthesis"
599 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000600 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000601 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000602 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000603 dir = 1
604 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000605 if source.next not in LOOKBEHINDASSERTCHARS:
Fredrik Lundh6f013982000-07-03 18:44:21 +0000606 raise error, "syntax error"
607 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000608 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000609 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000610 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000611 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000612 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000613 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000614 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000615 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000616 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000617 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000618 # conditional backreference group
619 condname = ""
620 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000621 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000622 if char is None:
623 raise error, "unterminated name"
624 if char == ")":
625 break
626 condname = condname + char
627 group = 2
Ezio Melottief317382012-11-03 20:31:12 +0200628 if not condname:
629 raise error("missing group name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000630 if isname(condname):
631 condgroup = state.groupdict.get(condname)
632 if condgroup is None:
Raymond Hettinger008651c2014-06-22 19:45:07 -0700633 msg = "unknown group name: {0!r}".format(condname)
Raymond Hettingerf595a122014-06-22 19:33:19 -0700634 raise error(msg)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000635 else:
636 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000637 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000638 except ValueError:
639 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000640 else:
641 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000642 if not source.next in FLAGS:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000643 raise error, "unexpected end of pattern"
Raymond Hettinger54f02222002-06-01 14:18:47 +0000644 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000645 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000646 if group:
647 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000648 if group == 2:
649 # anonymous group
650 group = None
651 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000652 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000653 if condgroup:
654 p = _parse_sub_cond(source, state, condgroup)
655 else:
656 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000657 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000658 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000659 if group is not None:
660 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000661 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000662 else:
663 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000664 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000665 if char is None:
666 raise error, "unexpected end of pattern"
667 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000668 break
669 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000670
Fredrik Lundh90a07912000-06-30 07:50:59 +0000671 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000672 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000673
Fredrik Lundh90a07912000-06-30 07:50:59 +0000674 elif this == "$":
675 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000676
Fredrik Lundh90a07912000-06-30 07:50:59 +0000677 elif this and this[0] == "\\":
678 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000679 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000680
Fredrik Lundh90a07912000-06-30 07:50:59 +0000681 else:
682 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000683
684 return subpattern
685
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000686def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000687 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000688
689 source = Tokenizer(str)
690
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000691 if pattern is None:
692 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000693 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000694 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000695
696 p = _parse_sub(source, pattern, 0)
697
698 tail = source.get()
699 if tail == ")":
700 raise error, "unbalanced parenthesis"
701 elif tail:
702 raise error, "bogus characters at end of regular expression"
703
Fredrik Lundh770617b2001-01-14 15:06:11 +0000704 if flags & SRE_FLAG_DEBUG:
705 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000706
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000707 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
708 # the VERBOSE flag was switched on inside the pattern. to be
709 # on the safe side, we'll parse the whole thing again...
710 return parse(str, p.pattern.flags)
711
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000712 return p
713
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000714def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000715 # parse 're' replacement string into list of literals and
716 # group references
717 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000718 sget = s.get
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000719 p = []
720 a = p.append
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000721 def literal(literal, p=p, pappend=a):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000722 if p and p[-1][0] is LITERAL:
723 p[-1] = LITERAL, p[-1][1] + literal
724 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000725 pappend((LITERAL, literal))
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000726 sep = source[:0]
727 if type(sep) is type(""):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000728 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000729 else:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000730 makechar = unichr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000731 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000732 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000733 if this is None:
734 break # end of replacement string
735 if this and this[0] == "\\":
736 # group
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000737 c = this[1:2]
738 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000739 name = ""
740 if s.match("<"):
741 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000742 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000743 if char is None:
744 raise error, "unterminated group name"
745 if char == ">":
746 break
747 name = name + char
748 if not name:
Ezio Melottief317382012-11-03 20:31:12 +0200749 raise error, "missing group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000750 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000751 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000752 if index < 0:
753 raise error, "negative group number"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000754 except ValueError:
755 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000756 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000757 try:
758 index = pattern.groupindex[name]
759 except KeyError:
Raymond Hettingerf595a122014-06-22 19:33:19 -0700760 msg = "unknown group name: {0!r}".format(name)
761 raise IndexError(msg)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000762 a((MARK, index))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000763 elif c == "0":
764 if s.next in OCTDIGITS:
765 this = this + sget()
766 if s.next in OCTDIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000767 this = this + sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000768 literal(makechar(int(this[1:], 8) & 0xff))
769 elif c in DIGITS:
770 isoctal = False
771 if s.next in DIGITS:
772 this = this + sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000773 if (c in OCTDIGITS and this[2] in OCTDIGITS and
774 s.next in OCTDIGITS):
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000775 this = this + sget()
776 isoctal = True
777 literal(makechar(int(this[1:], 8) & 0xff))
778 if not isoctal:
779 a((MARK, int(this[1:])))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000780 else:
781 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000782 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000783 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000784 pass
785 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000786 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000787 literal(this)
788 # convert template to groups and literals lists
789 i = 0
790 groups = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000791 groupsappend = groups.append
792 literals = [None] * len(p)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000793 for c, s in p:
794 if c is MARK:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000795 groupsappend((i, s))
796 # literal[i] is already None
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000797 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000798 literals[i] = s
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000799 i = i + 1
800 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000801
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000802def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000803 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000804 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000805 groups, literals = template
806 literals = literals[:]
807 try:
808 for index, group in groups:
809 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000810 if s is None:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000811 raise error, "unmatched group"
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000812 except IndexError:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000813 raise error, "invalid group reference"
Barry Warsaw8bee7612004-08-25 02:22:30 +0000814 return sep.join(literals)