blob: 39341c610e740a660b79230e9c4f8d16984510b6 [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 Lundh90a07912000-06-30 07:50:59 +000069 self.groupdict = {}
Serhiy Storchaka15ea8702014-11-07 21:43:45 +020070 self.subpatterns = [None] # group 0
71 @property
72 def groups(self):
73 return len(self.subpatterns)
Fredrik Lundhebc37b22000-10-28 19:30:41 +000074 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000075 gid = self.groups
Serhiy Storchaka15ea8702014-11-07 21:43:45 +020076 self.subpatterns.append(None)
Raymond Hettingerf13eb552002-06-02 00:40:05 +000077 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000078 ogid = self.groupdict.get(name, None)
79 if ogid is not None:
Fredrik Lundh82b23072001-12-09 16:13:15 +000080 raise error, ("redefinition of group name %s as group %d; "
81 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000082 self.groupdict[name] = gid
83 return gid
Serhiy Storchaka15ea8702014-11-07 21:43:45 +020084 def closegroup(self, gid, p):
85 self.subpatterns[gid] = p
Fredrik Lundhebc37b22000-10-28 19:30:41 +000086 def checkgroup(self, gid):
Serhiy Storchaka15ea8702014-11-07 21:43:45 +020087 return gid < self.groups and self.subpatterns[gid] is not None
Guido van Rossum7627c0d2000-03-31 14:58:54 +000088
89class SubPattern:
90 # a subpattern, in intermediate form
91 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000092 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000093 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000094 data = []
95 self.data = data
96 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000097 def dump(self, level=0):
Serhiy Storchakac0799e32014-09-21 22:47:30 +030098 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000099 for op, av in self.data:
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300100 print level*" " + op,
101 if op == IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000102 # member sublanguage
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300103 print
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000104 for op, a in av:
105 print (level+1)*" " + op, a
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300106 elif op == BRANCH:
107 print
108 for i, a in enumerate(av[1]):
109 if i:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000110 print level*" " + "or"
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300111 a.dump(level+1)
112 elif op == GROUPREF_EXISTS:
113 condgroup, item_yes, item_no = av
114 print condgroup
115 item_yes.dump(level+1)
116 if item_no:
117 print level*" " + "else"
118 item_no.dump(level+1)
119 elif isinstance(av, seqtypes):
120 nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000121 for a in av:
122 if isinstance(a, SubPattern):
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300123 if not nl:
124 print
125 a.dump(level+1)
126 nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000127 else:
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300128 print a,
129 nl = 0
130 if not nl:
131 print
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000132 else:
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300133 print av
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000134 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000135 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000136 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000137 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000138 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000139 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000140 def __getitem__(self, index):
Thomas Wouterse3a985f2006-12-19 08:17:50 +0000141 if isinstance(index, slice):
142 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000143 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000144 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000145 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000146 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000147 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000148 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000149 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000150 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000151 # determine the width (min, max) for this subpattern
152 if self.width:
153 return self.width
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300154 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000155 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
156 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000157 for op, av in self.data:
158 if op is BRANCH:
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300159 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000160 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000161 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000162 l, h = av.getwidth()
163 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000164 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000165 lo = lo + i
166 hi = hi + j
167 elif op is CALL:
168 i, j = av.getwidth()
169 lo = lo + i
170 hi = hi + j
171 elif op is SUBPATTERN:
172 i, j = av[1].getwidth()
173 lo = lo + i
174 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000175 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000176 i, j = av[2].getwidth()
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300177 lo = lo + i * av[0]
178 hi = hi + j * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000179 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000180 lo = lo + 1
181 hi = hi + 1
Serhiy Storchaka15ea8702014-11-07 21:43:45 +0200182 elif op is GROUPREF:
183 i, j = self.pattern.subpatterns[av].getwidth()
184 lo = lo + i
185 hi = hi + j
186 elif op is GROUPREF_EXISTS:
187 i, j = av[1].getwidth()
188 if av[2] is not None:
189 l, h = av[2].getwidth()
190 i = min(i, l)
191 j = max(j, h)
192 else:
193 i = 0
194 lo = lo + i
195 hi = hi + j
196 elif op is SUCCESS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000197 break
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300198 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000199 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000200
201class Tokenizer:
202 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000203 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000204 self.index = 0
205 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000206 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000207 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000208 self.next = None
209 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000210 char = self.string[self.index]
211 if char[0] == "\\":
212 try:
213 c = self.string[self.index + 1]
214 except IndexError:
Fredrik Lundh8a0232d2001-11-02 13:59:51 +0000215 raise error, "bogus escape (end of line)"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000216 char = char + c
217 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000218 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000219 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000220 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000221 if skip:
222 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000223 return 1
224 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000225 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000226 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000227 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000228 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000229 def tell(self):
230 return self.index, self.next
231 def seek(self, index):
232 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000233
Fredrik Lundh4781b072000-06-29 12:38:45 +0000234def isident(char):
235 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
236
237def isdigit(char):
238 return "0" <= char <= "9"
239
240def isname(name):
241 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000242 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000243 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000244 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000245 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000246 return False
247 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000248
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000249def _class_escape(source, escape):
250 # handle escape code inside character class
251 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000252 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000253 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000254 code = CATEGORIES.get(escape)
Ezio Melotti5c4e32b2013-01-11 08:32:01 +0200255 if code and code[0] == IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000256 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000257 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000258 c = escape[1:2]
259 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000260 # hexadecimal escape (exactly two digits)
261 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000262 escape = escape + source.get()
263 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000264 if len(escape) != 2:
265 raise error, "bogus escape: %s" % repr("\\" + escape)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000266 return LITERAL, int(escape, 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000267 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000268 # octal escape (up to three digits)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000269 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000270 escape = escape + source.get()
271 escape = escape[1:]
Barry Warsaw8bee7612004-08-25 02:22:30 +0000272 return LITERAL, int(escape, 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000273 elif c in DIGITS:
274 raise error, "bogus escape: %s" % repr(escape)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000275 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000276 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000277 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000278 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000279 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000280
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000281def _escape(source, escape, state):
282 # handle escape code in expression
283 code = CATEGORIES.get(escape)
284 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000285 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000286 code = ESCAPES.get(escape)
287 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000288 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000289 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000290 c = escape[1:2]
291 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000292 # hexadecimal escape
293 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000294 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000295 if len(escape) != 4:
296 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000297 return LITERAL, int(escape[2:], 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000298 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000299 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000300 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000301 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000302 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000303 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000304 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000305 if source.next in DIGITS:
306 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000307 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
308 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000309 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000310 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000311 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000312 # not an octal escape, so this is a group reference
313 group = int(escape[1:])
314 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000315 if not state.checkgroup(group):
316 raise error, "cannot refer to open group"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000317 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000318 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000319 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000320 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000321 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000322 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000323 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000324
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000325def _parse_sub(source, state, nested=1):
326 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000327
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000328 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000329 itemsappend = items.append
330 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000331 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000332 itemsappend(_parse(source, state))
333 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000334 continue
335 if not nested:
336 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000337 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000338 break
339 else:
340 raise error, "pattern not properly closed"
341
342 if len(items) == 1:
343 return items[0]
344
345 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000346 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000347
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000348 # check if all items share a common prefix
349 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000350 prefix = None
351 for item in items:
352 if not item:
353 break
354 if prefix is None:
355 prefix = item[0]
356 elif item[0] != prefix:
357 break
358 else:
359 # all subitems start with a common "prefix".
360 # move it out of the branch
361 for item in items:
362 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000363 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000364 continue # check next one
365 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000366
367 # check if the branch can be replaced by a character set
368 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000369 if len(item) != 1 or item[0][0] != LITERAL:
370 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000371 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000372 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000373 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000374 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000375 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000376 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000377 setappend(item[0])
378 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000379 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000380
381 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000382 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000383
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000384def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000385 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000386 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000387 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000388 if source.match("|"):
389 raise error, "conditional backref with more than two branches"
390 else:
391 item_no = None
392 if source.next and not source.match(")", 0):
393 raise error, "pattern not properly closed"
394 subpattern = SubPattern(state)
395 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
396 return subpattern
397
Raymond Hettinger049ade22005-02-28 19:27:52 +0000398_PATTERNENDERS = set("|)")
399_ASSERTCHARS = set("=!<")
400_LOOKBEHINDASSERTCHARS = set("=!")
401_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
402
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000403def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000404 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000405 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000406
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000407 # precompute constants into local variables
408 subpatternappend = subpattern.append
409 sourceget = source.get
410 sourcematch = source.match
411 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000412 PATTERNENDERS = _PATTERNENDERS
413 ASSERTCHARS = _ASSERTCHARS
414 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
415 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000416
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000417 while 1:
418
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000419 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000420 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000421 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000422 if this is None:
423 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000424
Fredrik Lundh90a07912000-06-30 07:50:59 +0000425 if state.flags & SRE_FLAG_VERBOSE:
426 # skip whitespace and comments
427 if this in WHITESPACE:
428 continue
429 if this == "#":
430 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000431 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000432 if this in (None, "\n"):
433 break
434 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000435
Fredrik Lundh90a07912000-06-30 07:50:59 +0000436 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000437 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000438
Fredrik Lundh90a07912000-06-30 07:50:59 +0000439 elif this == "[":
440 # character set
441 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000442 setappend = set.append
443## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000444## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000445 if sourcematch("^"):
446 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000447 # check remaining characters
448 start = set[:]
449 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000450 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000451 if this == "]" and set != start:
452 break
453 elif this and this[0] == "\\":
454 code1 = _class_escape(source, this)
455 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000456 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000457 else:
458 raise error, "unexpected end of regular expression"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000459 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000460 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000461 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000462 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000463 if code1[0] is IN:
464 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000465 setappend(code1)
466 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000467 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000468 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000469 if this[0] == "\\":
470 code2 = _class_escape(source, this)
471 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000472 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000473 if code1[0] != LITERAL or code2[0] != LITERAL:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000474 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000475 lo = code1[1]
476 hi = code2[1]
477 if hi < lo:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000478 raise error, "bad character range"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000479 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000480 else:
481 raise error, "unexpected end of regular expression"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000482 else:
483 if code1[0] is IN:
484 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000485 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000486
Fredrik Lundh770617b2001-01-14 15:06:11 +0000487 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000488 if _len(set)==1 and set[0][0] is LITERAL:
489 subpatternappend(set[0]) # optimization
490 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
491 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000492 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000493 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000494 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000495
Fredrik Lundh90a07912000-06-30 07:50:59 +0000496 elif this and this[0] in REPEAT_CHARS:
497 # repeat previous item
498 if this == "?":
499 min, max = 0, 1
500 elif this == "*":
501 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000502
Fredrik Lundh90a07912000-06-30 07:50:59 +0000503 elif this == "+":
504 min, max = 1, MAXREPEAT
505 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000506 if source.next == "}":
507 subpatternappend((LITERAL, ord(this)))
508 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000509 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000510 min, max = 0, MAXREPEAT
511 lo = hi = ""
512 while source.next in DIGITS:
513 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000514 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000515 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000516 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000517 else:
518 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000519 if not sourcematch("}"):
520 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000521 source.seek(here)
522 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000523 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000524 min = int(lo)
Serhiy Storchakae18e05c2013-02-16 16:47:15 +0200525 if min >= MAXREPEAT:
526 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000527 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000528 max = int(hi)
Serhiy Storchakae18e05c2013-02-16 16:47:15 +0200529 if max >= MAXREPEAT:
530 raise OverflowError("the repetition number is too large")
531 if max < min:
532 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000533 else:
534 raise error, "not supported"
535 # figure out which item to repeat
536 if subpattern:
537 item = subpattern[-1:]
538 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000539 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000540 if not item or (_len(item) == 1 and item[0][0] == AT):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000541 raise error, "nothing to repeat"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000542 if item[0][0] in REPEATCODES:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000543 raise error, "multiple repeat"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000544 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000545 subpattern[-1] = (MIN_REPEAT, (min, max, item))
546 else:
547 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000548
Fredrik Lundh90a07912000-06-30 07:50:59 +0000549 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000550 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000551
Fredrik Lundh90a07912000-06-30 07:50:59 +0000552 elif this == "(":
553 group = 1
554 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000555 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000556 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000557 group = 0
558 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000559 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000560 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000561 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000562 # named group: skip forward to end of name
563 name = ""
564 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000565 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000566 if char is None:
567 raise error, "unterminated name"
568 if char == ">":
569 break
570 name = name + char
571 group = 1
Ezio Melottief317382012-11-03 20:31:12 +0200572 if not name:
573 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000574 if not isname(name):
R David Murray60773392013-04-14 13:08:50 -0400575 raise error("bad character in group name %r" %
576 name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000577 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000578 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000579 name = ""
580 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000581 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000582 if char is None:
583 raise error, "unterminated name"
584 if char == ")":
585 break
586 name = name + char
Ezio Melottief317382012-11-03 20:31:12 +0200587 if not name:
588 raise error("missing group name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000589 if not isname(name):
R David Murray60773392013-04-14 13:08:50 -0400590 raise error("bad character in backref group name "
591 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000592 gid = state.groupdict.get(name)
593 if gid is None:
Raymond Hettingerf595a122014-06-22 19:33:19 -0700594 msg = "unknown group name: {0!r}".format(name)
595 raise error(msg)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000596 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000597 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000598 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000599 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000600 if char is None:
601 raise error, "unexpected end of pattern"
602 raise error, "unknown specifier: ?P%s" % char
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000603 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000604 # non-capturing group
605 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000606 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000607 # comment
608 while 1:
609 if source.next is None or source.next == ")":
610 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000611 sourceget()
612 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000613 raise error, "unbalanced parenthesis"
614 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000615 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000616 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000617 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000618 dir = 1
619 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000620 if source.next not in LOOKBEHINDASSERTCHARS:
Fredrik Lundh6f013982000-07-03 18:44:21 +0000621 raise error, "syntax error"
622 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000623 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000624 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000625 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000626 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000627 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000628 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000629 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000630 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000631 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000632 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000633 # conditional backreference group
634 condname = ""
635 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000636 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000637 if char is None:
638 raise error, "unterminated name"
639 if char == ")":
640 break
641 condname = condname + char
642 group = 2
Ezio Melottief317382012-11-03 20:31:12 +0200643 if not condname:
644 raise error("missing group name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000645 if isname(condname):
646 condgroup = state.groupdict.get(condname)
647 if condgroup is None:
Raymond Hettinger008651c2014-06-22 19:45:07 -0700648 msg = "unknown group name: {0!r}".format(condname)
Raymond Hettingerf595a122014-06-22 19:33:19 -0700649 raise error(msg)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000650 else:
651 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000652 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000653 except ValueError:
654 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000655 else:
656 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000657 if not source.next in FLAGS:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000658 raise error, "unexpected end of pattern"
Raymond Hettinger54f02222002-06-01 14:18:47 +0000659 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000660 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000661 if group:
662 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000663 if group == 2:
664 # anonymous group
665 group = None
666 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000667 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000668 if condgroup:
669 p = _parse_sub_cond(source, state, condgroup)
670 else:
671 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000672 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000673 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000674 if group is not None:
Serhiy Storchaka15ea8702014-11-07 21:43:45 +0200675 state.closegroup(group, p)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000676 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000677 else:
678 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000679 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000680 if char is None:
681 raise error, "unexpected end of pattern"
682 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000683 break
684 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000685
Fredrik Lundh90a07912000-06-30 07:50:59 +0000686 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000687 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000688
Fredrik Lundh90a07912000-06-30 07:50:59 +0000689 elif this == "$":
690 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000691
Fredrik Lundh90a07912000-06-30 07:50:59 +0000692 elif this and this[0] == "\\":
693 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000694 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000695
Fredrik Lundh90a07912000-06-30 07:50:59 +0000696 else:
697 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000698
699 return subpattern
700
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000701def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000702 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000703
704 source = Tokenizer(str)
705
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000706 if pattern is None:
707 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000708 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000709 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000710
711 p = _parse_sub(source, pattern, 0)
712
713 tail = source.get()
714 if tail == ")":
715 raise error, "unbalanced parenthesis"
716 elif tail:
717 raise error, "bogus characters at end of regular expression"
718
Fredrik Lundh770617b2001-01-14 15:06:11 +0000719 if flags & SRE_FLAG_DEBUG:
720 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000721
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000722 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
723 # the VERBOSE flag was switched on inside the pattern. to be
724 # on the safe side, we'll parse the whole thing again...
725 return parse(str, p.pattern.flags)
726
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000727 return p
728
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000729def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000730 # parse 're' replacement string into list of literals and
731 # group references
732 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000733 sget = s.get
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000734 p = []
735 a = p.append
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000736 def literal(literal, p=p, pappend=a):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000737 if p and p[-1][0] is LITERAL:
738 p[-1] = LITERAL, p[-1][1] + literal
739 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000740 pappend((LITERAL, literal))
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000741 sep = source[:0]
742 if type(sep) is type(""):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000743 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000744 else:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000745 makechar = unichr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000746 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000747 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000748 if this is None:
749 break # end of replacement string
750 if this and this[0] == "\\":
751 # group
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000752 c = this[1:2]
753 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000754 name = ""
755 if s.match("<"):
756 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000757 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000758 if char is None:
759 raise error, "unterminated group name"
760 if char == ">":
761 break
762 name = name + char
763 if not name:
Ezio Melottief317382012-11-03 20:31:12 +0200764 raise error, "missing group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000765 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000766 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000767 if index < 0:
768 raise error, "negative group number"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000769 except ValueError:
770 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000771 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000772 try:
773 index = pattern.groupindex[name]
774 except KeyError:
Raymond Hettingerf595a122014-06-22 19:33:19 -0700775 msg = "unknown group name: {0!r}".format(name)
776 raise IndexError(msg)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000777 a((MARK, index))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000778 elif c == "0":
779 if s.next in OCTDIGITS:
780 this = this + sget()
781 if s.next in OCTDIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000782 this = this + sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000783 literal(makechar(int(this[1:], 8) & 0xff))
784 elif c in DIGITS:
785 isoctal = False
786 if s.next in DIGITS:
787 this = this + sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000788 if (c in OCTDIGITS and this[2] in OCTDIGITS and
789 s.next in OCTDIGITS):
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000790 this = this + sget()
791 isoctal = True
792 literal(makechar(int(this[1:], 8) & 0xff))
793 if not isoctal:
794 a((MARK, int(this[1:])))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000795 else:
796 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000797 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000798 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000799 pass
800 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000801 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000802 literal(this)
803 # convert template to groups and literals lists
804 i = 0
805 groups = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000806 groupsappend = groups.append
807 literals = [None] * len(p)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000808 for c, s in p:
809 if c is MARK:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000810 groupsappend((i, s))
811 # literal[i] is already None
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000812 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000813 literals[i] = s
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000814 i = i + 1
815 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000816
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000817def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000818 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000819 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000820 groups, literals = template
821 literals = literals[:]
822 try:
823 for index, group in groups:
824 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000825 if s is None:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000826 raise error, "unmatched group"
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000827 except IndexError:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000828 raise error, "invalid group reference"
Barry Warsaw8bee7612004-08-25 02:22:30 +0000829 return sep.join(literals)