blob: 98afd7cb4a681ec0b82b3d93e9a23ab8fb317240 [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
Guido van Rossum7627c0d2000-03-31 14:58:54 +000015from sre_constants import *
16
17SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000018REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000019
Serhiy Storchakae2ccf562014-10-10 11:14:49 +030020DIGITS = frozenset("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000021
Serhiy Storchakae2ccf562014-10-10 11:14:49 +030022OCTDIGITS = frozenset("01234567")
23HEXDIGITS = frozenset("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000024
Serhiy Storchakae2ccf562014-10-10 11:14:49 +030025WHITESPACE = frozenset(" \t\n\r\v\f")
26
Raymond Hettingerdf1b6992014-11-09 15:56:33 -080027_REPEATCODES = frozenset({MIN_REPEAT, MAX_REPEAT})
28_UNITCODES = frozenset({ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY})
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000029
Guido van Rossum7627c0d2000-03-31 14:58:54 +000030ESCAPES = {
Fredrik Lundhf2989b22001-02-18 12:05:16 +000031 r"\a": (LITERAL, ord("\a")),
32 r"\b": (LITERAL, ord("\b")),
33 r"\f": (LITERAL, ord("\f")),
34 r"\n": (LITERAL, ord("\n")),
35 r"\r": (LITERAL, ord("\r")),
36 r"\t": (LITERAL, ord("\t")),
37 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000038 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000039}
40
41CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000042 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000043 r"\b": (AT, AT_BOUNDARY),
44 r"\B": (AT, AT_NON_BOUNDARY),
45 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
46 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
47 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
48 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
49 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
50 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000051 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000052}
53
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000054FLAGS = {
Fredrik Lundh436c3d582000-06-29 08:58:44 +000055 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000056 "i": SRE_FLAG_IGNORECASE,
57 "L": SRE_FLAG_LOCALE,
58 "m": SRE_FLAG_MULTILINE,
59 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000060 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000061 # extensions
Antoine Pitroufd036452008-08-19 17:56:33 +000062 "a": SRE_FLAG_ASCII,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000063 "t": SRE_FLAG_TEMPLATE,
64 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000065}
66
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000067class Pattern:
68 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000069 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000070 self.flags = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +000071 self.groupdict = {}
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +020072 self.subpatterns = [None] # group 0
73 self.lookbehindgroups = None
74 @property
75 def groups(self):
76 return len(self.subpatterns)
Fredrik Lundhebc37b22000-10-28 19:30:41 +000077 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000078 gid = self.groups
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +020079 self.subpatterns.append(None)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +030080 if self.groups > MAXGROUPS:
81 raise error("groups number is too large")
Raymond Hettingerf13eb552002-06-02 00:40:05 +000082 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000083 ogid = self.groupdict.get(name, None)
84 if ogid is not None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +020085 raise error("redefinition of group name %r as group %d; "
86 "was group %d" % (name, gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000087 self.groupdict[name] = gid
88 return gid
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +020089 def closegroup(self, gid, p):
90 self.subpatterns[gid] = p
Fredrik Lundhebc37b22000-10-28 19:30:41 +000091 def checkgroup(self, gid):
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +020092 return gid < self.groups and self.subpatterns[gid] is not None
93
94 def checklookbehindgroup(self, gid, source):
95 if self.lookbehindgroups is not None:
96 if not self.checkgroup(gid):
97 raise source.error('cannot refer to an open group')
98 if gid >= self.lookbehindgroups:
99 raise source.error('cannot refer to group defined in the same '
100 'lookbehind subpattern')
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000101
102class SubPattern:
103 # a subpattern, in intermediate form
104 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000105 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +0000106 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000107 data = []
108 self.data = data
109 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000110 def dump(self, level=0):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300111 nl = True
Guido van Rossum13257902007-06-07 23:15:56 +0000112 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000113 for op, av in self.data:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200114 print(level*" " + str(op), end='')
Serhiy Storchakaab140882014-11-11 21:13:28 +0200115 if op is IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000116 # member sublanguage
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300117 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000118 for op, a in av:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200119 print((level+1)*" " + str(op), a)
Serhiy Storchakaab140882014-11-11 21:13:28 +0200120 elif op is BRANCH:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300121 print()
122 for i, a in enumerate(av[1]):
123 if i:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200124 print(level*" " + "OR")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300125 a.dump(level+1)
Serhiy Storchakaab140882014-11-11 21:13:28 +0200126 elif op is GROUPREF_EXISTS:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300127 condgroup, item_yes, item_no = av
128 print('', condgroup)
129 item_yes.dump(level+1)
130 if item_no:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200131 print(level*" " + "ELSE")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300132 item_no.dump(level+1)
Guido van Rossum13257902007-06-07 23:15:56 +0000133 elif isinstance(av, seqtypes):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300134 nl = False
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000135 for a in av:
136 if isinstance(a, SubPattern):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300137 if not nl:
138 print()
139 a.dump(level+1)
140 nl = True
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000141 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300142 if not nl:
143 print(' ', end='')
144 print(a, end='')
145 nl = False
146 if not nl:
147 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000148 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300149 print('', av)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000150 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000151 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000152 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000153 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000154 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000155 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000156 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000157 if isinstance(index, slice):
158 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000159 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000160 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000161 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000162 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000163 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000164 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000165 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000166 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000167 # determine the width (min, max) for this subpattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300168 if self.width is not None:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000169 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000170 lo = hi = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000171 for op, av in self.data:
172 if op is BRANCH:
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300173 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000174 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000175 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000176 l, h = av.getwidth()
177 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000178 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000179 lo = lo + i
180 hi = hi + j
181 elif op is CALL:
182 i, j = av.getwidth()
183 lo = lo + i
184 hi = hi + j
185 elif op is SUBPATTERN:
186 i, j = av[1].getwidth()
187 lo = lo + i
188 hi = hi + j
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300189 elif op in _REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000190 i, j = av[2].getwidth()
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300191 lo = lo + i * av[0]
192 hi = hi + j * av[1]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300193 elif op in _UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000194 lo = lo + 1
195 hi = hi + 1
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200196 elif op is GROUPREF:
197 i, j = self.pattern.subpatterns[av].getwidth()
198 lo = lo + i
199 hi = hi + j
200 elif op is GROUPREF_EXISTS:
201 i, j = av[1].getwidth()
202 if av[2] is not None:
203 l, h = av[2].getwidth()
204 i = min(i, l)
205 j = max(j, h)
206 else:
207 i = 0
208 lo = lo + i
209 hi = hi + j
210 elif op is SUCCESS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000211 break
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300212 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000213 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000214
215class Tokenizer:
216 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200217 self.istext = isinstance(string, str)
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200218 self.string = string
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300219 if not self.istext:
220 string = str(string, 'latin1')
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200221 self.decoded_string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000222 self.index = 0
Serhiy Storchakab99c1322014-11-10 14:38:16 +0200223 self.next = None
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000224 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000225 def __next(self):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300226 index = self.index
227 try:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200228 char = self.decoded_string[index]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300229 except IndexError:
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000230 self.next = None
231 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000232 if char == "\\":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300233 index += 1
Fredrik Lundh90a07912000-06-30 07:50:59 +0000234 try:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200235 char += self.decoded_string[index]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000236 except IndexError:
Serhiy Storchaka1b2004f2014-11-10 18:28:53 +0200237 raise error("bogus escape (end of line)",
238 self.string, len(self.string) - 1) from None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300239 self.index = index + 1
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000240 self.next = char
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300241 def match(self, char):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000242 if char == self.next:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300243 self.__next()
244 return True
245 return False
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000246 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000247 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000248 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000249 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200250 def getwhile(self, n, charset):
251 result = ''
252 for _ in range(n):
253 c = self.next
254 if c not in charset:
255 break
256 result += c
257 self.__next()
258 return result
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300259 def getuntil(self, terminator):
260 result = ''
261 while True:
262 c = self.next
263 self.__next()
264 if c is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200265 raise self.error("unterminated name")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300266 if c == terminator:
267 break
268 result += c
269 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000270 def tell(self):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200271 return self.index - len(self.next or '')
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000272 def seek(self, index):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200273 self.index = index
274 self.__next()
275
276 def error(self, msg, offset=0):
277 return error(msg, self.string, self.tell() - offset)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000278
Georg Brandl1d472b72013-04-14 11:40:00 +0200279# The following three functions are not used in this module anymore, but we keep
280# them here (with DeprecationWarnings) for backwards compatibility.
281
Fredrik Lundh4781b072000-06-29 12:38:45 +0000282def isident(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200283 import warnings
284 warnings.warn('sre_parse.isident() will be removed in 3.5',
285 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000286 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
287
288def isdigit(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200289 import warnings
290 warnings.warn('sre_parse.isdigit() will be removed in 3.5',
291 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000292 return "0" <= char <= "9"
293
294def isname(name):
Georg Brandl1d472b72013-04-14 11:40:00 +0200295 import warnings
296 warnings.warn('sre_parse.isname() will be removed in 3.5',
297 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000298 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000299 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000300 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000301 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000302 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000303 return False
304 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000305
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000306def _class_escape(source, escape):
307 # handle escape code inside character class
308 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000309 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000310 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000311 code = CATEGORIES.get(escape)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300312 if code and code[0] is IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000313 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000314 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000315 c = escape[1:2]
316 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000317 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200318 escape += source.getwhile(2, HEXDIGITS)
319 if len(escape) != 4:
320 raise ValueError
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300321 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200322 elif c == "u" and source.istext:
323 # unicode escape (exactly four digits)
324 escape += source.getwhile(4, HEXDIGITS)
325 if len(escape) != 6:
326 raise ValueError
327 return LITERAL, int(escape[2:], 16)
328 elif c == "U" and source.istext:
329 # unicode escape (exactly eight digits)
330 escape += source.getwhile(8, HEXDIGITS)
331 if len(escape) != 10:
332 raise ValueError
333 c = int(escape[2:], 16)
334 chr(c) # raise ValueError for invalid code
335 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000336 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000337 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200338 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300339 c = int(escape[1:], 8)
340 if c > 0o377:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200341 raise source.error('octal escape value %r outside of '
342 'range 0-0o377' % escape, len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300343 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000344 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200345 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000346 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000347 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000348 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000349 pass
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200350 raise source.error("bogus escape: %r" % escape, len(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000351
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000352def _escape(source, escape, state):
353 # handle escape code in expression
354 code = CATEGORIES.get(escape)
355 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000356 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000357 code = ESCAPES.get(escape)
358 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000359 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000360 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000361 c = escape[1:2]
362 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000363 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200364 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000365 if len(escape) != 4:
366 raise ValueError
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300367 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200368 elif c == "u" and source.istext:
369 # unicode escape (exactly four digits)
370 escape += source.getwhile(4, HEXDIGITS)
371 if len(escape) != 6:
372 raise ValueError
373 return LITERAL, int(escape[2:], 16)
374 elif c == "U" and source.istext:
375 # unicode escape (exactly eight digits)
376 escape += source.getwhile(8, HEXDIGITS)
377 if len(escape) != 10:
378 raise ValueError
379 c = int(escape[2:], 16)
380 chr(c) # raise ValueError for invalid code
381 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000382 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000383 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200384 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300385 return LITERAL, int(escape[1:], 8)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000386 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000387 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000388 if source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300389 escape += source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000390 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
391 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000392 # got three octal digits; this is an octal escape
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300393 escape += source.get()
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300394 c = int(escape[1:], 8)
395 if c > 0o377:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200396 raise source.error('octal escape value %r outside of '
397 'range 0-0o377' % escape,
398 len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300399 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000400 # not an octal escape, so this is a group reference
401 group = int(escape[1:])
402 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000403 if not state.checkgroup(group):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200404 raise source.error("cannot refer to open group",
405 len(escape))
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200406 state.checklookbehindgroup(group, source)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000407 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000408 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000409 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000410 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000411 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000412 pass
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200413 raise source.error("bogus escape: %r" % escape, len(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000414
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300415def _parse_sub(source, state, nested=True):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000416 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000417
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000418 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000419 itemsappend = items.append
420 sourcematch = source.match
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300421 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000422 itemsappend(_parse(source, state))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300423 if not sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000424 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300425 if nested and source.next is not None and source.next != ")":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200426 raise source.error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000427
428 if len(items) == 1:
429 return items[0]
430
431 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000432 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000433
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000434 # check if all items share a common prefix
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300435 while True:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000436 prefix = None
437 for item in items:
438 if not item:
439 break
440 if prefix is None:
441 prefix = item[0]
442 elif item[0] != prefix:
443 break
444 else:
445 # all subitems start with a common "prefix".
446 # move it out of the branch
447 for item in items:
448 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000449 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000450 continue # check next one
451 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000452
453 # check if the branch can be replaced by a character set
454 for item in items:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300455 if len(item) != 1 or item[0][0] is not LITERAL:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000456 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000457 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000458 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000459 # branch (the compiler may optimize this even more)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300460 subpatternappend((IN, [item[0] for item in items]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000461 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000462
463 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000464 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000465
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000466def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000467 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000468 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000469 item_no = _parse(source, state)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300470 if source.next == "|":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200471 raise source.error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000472 else:
473 item_no = None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300474 if source.next is not None and source.next != ")":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200475 raise source.error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000476 subpattern = SubPattern(state)
477 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
478 return subpattern
479
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000480def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000481 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000482 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000483
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000484 # precompute constants into local variables
485 subpatternappend = subpattern.append
486 sourceget = source.get
487 sourcematch = source.match
488 _len = len
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300489 _ord = ord
490 verbose = state.flags & SRE_FLAG_VERBOSE
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000491
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300492 while True:
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000493
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300494 this = source.next
Fredrik Lundh90a07912000-06-30 07:50:59 +0000495 if this is None:
496 break # end of pattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300497 if this in "|)":
498 break # end of subpattern
499 sourceget()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000500
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300501 if verbose:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000502 # skip whitespace and comments
503 if this in WHITESPACE:
504 continue
505 if this == "#":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300506 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000507 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300508 if this is None or this == "\n":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000509 break
510 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000511
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300512 if this[0] == "\\":
513 code = _escape(source, this, state)
514 subpatternappend(code)
515
516 elif this not in SPECIAL_CHARS:
517 subpatternappend((LITERAL, _ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000518
Fredrik Lundh90a07912000-06-30 07:50:59 +0000519 elif this == "[":
520 # character set
521 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000522 setappend = set.append
523## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000524## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000525 if sourcematch("^"):
526 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000527 # check remaining characters
528 start = set[:]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300529 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000530 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300531 if this is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200532 raise source.error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000533 if this == "]" and set != start:
534 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300535 elif this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000536 code1 = _class_escape(source, this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000537 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300538 code1 = LITERAL, _ord(this)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000539 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000540 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000541 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300542 if this is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200543 raise source.error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000544 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000545 if code1[0] is IN:
546 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000547 setappend(code1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300548 setappend((LITERAL, _ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000549 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300550 if this[0] == "\\":
551 code2 = _class_escape(source, this)
Guido van Rossum41c99e72003-04-14 17:59:34 +0000552 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300553 code2 = LITERAL, _ord(this)
554 if code1[0] != LITERAL or code2[0] != LITERAL:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200555 raise source.error("bad character range", len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300556 lo = code1[1]
557 hi = code2[1]
558 if hi < lo:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200559 raise source.error("bad character range", len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300560 setappend((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000561 else:
562 if code1[0] is IN:
563 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000564 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000565
Fredrik Lundh770617b2001-01-14 15:06:11 +0000566 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000567 if _len(set)==1 and set[0][0] is LITERAL:
568 subpatternappend(set[0]) # optimization
569 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
570 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000571 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000572 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000573 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000574
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300575 elif this in REPEAT_CHARS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000576 # repeat previous item
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200577 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000578 if this == "?":
579 min, max = 0, 1
580 elif this == "*":
581 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000582
Fredrik Lundh90a07912000-06-30 07:50:59 +0000583 elif this == "+":
584 min, max = 1, MAXREPEAT
585 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000586 if source.next == "}":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300587 subpatternappend((LITERAL, _ord(this)))
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000588 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000589 min, max = 0, MAXREPEAT
590 lo = hi = ""
591 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300592 lo += sourceget()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000593 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000594 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300595 hi += sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000596 else:
597 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000598 if not sourcematch("}"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300599 subpatternappend((LITERAL, _ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000600 source.seek(here)
601 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000602 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000603 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200604 if min >= MAXREPEAT:
605 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000606 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000607 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200608 if max >= MAXREPEAT:
609 raise OverflowError("the repetition number is too large")
610 if max < min:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200611 raise source.error("bad repeat interval",
612 source.tell() - here)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000613 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200614 raise source.error("not supported", len(this))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000615 # figure out which item to repeat
616 if subpattern:
617 item = subpattern[-1:]
618 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000619 item = None
Serhiy Storchakaab140882014-11-11 21:13:28 +0200620 if not item or (_len(item) == 1 and item[0][0] is AT):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200621 raise source.error("nothing to repeat",
622 source.tell() - here + len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300623 if item[0][0] in _REPEATCODES:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200624 raise source.error("multiple repeat",
625 source.tell() - here + len(this))
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000626 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000627 subpattern[-1] = (MIN_REPEAT, (min, max, item))
628 else:
629 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000630
Fredrik Lundh90a07912000-06-30 07:50:59 +0000631 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000632 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000633
Fredrik Lundh90a07912000-06-30 07:50:59 +0000634 elif this == "(":
635 group = 1
636 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000637 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000638 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000639 group = 0
640 # options
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300641 char = sourceget()
642 if char is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200643 raise self.error("unexpected end of pattern")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300644 if char == "P":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000645 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000646 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000647 # named group: skip forward to end of name
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300648 name = source.getuntil(">")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000649 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200650 if not name:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200651 raise source.error("missing group name", 1)
Georg Brandl1d472b72013-04-14 11:40:00 +0200652 if not name.isidentifier():
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200653 raise source.error("bad character in group name "
654 "%r" % name,
655 len(name) + 1)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000656 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000657 # named backreference
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300658 name = source.getuntil(")")
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200659 if not name:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200660 raise source.error("missing group name", 1)
Georg Brandl1d472b72013-04-14 11:40:00 +0200661 if not name.isidentifier():
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200662 raise source.error("bad character in backref "
663 "group name %r" % name,
664 len(name) + 1)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000665 gid = state.groupdict.get(name)
666 if gid is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700667 msg = "unknown group name: {0!r}".format(name)
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200668 raise source.error(msg, len(name) + 1)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200669 state.checklookbehindgroup(gid, source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000670 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000671 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000672 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000673 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000674 if char is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200675 raise source.error("unexpected end of pattern")
676 raise source.error("unknown specifier: ?P%s" % char,
677 len(char))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300678 elif char == ":":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000679 # non-capturing group
680 group = 2
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300681 elif char == "#":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000682 # comment
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300683 while True:
684 if source.next is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200685 raise source.error("unbalanced parenthesis")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300686 if sourceget() == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000687 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000688 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300689 elif char in "=!<":
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000690 # lookahead assertions
Fredrik Lundh6f013982000-07-03 18:44:21 +0000691 dir = 1
692 if char == "<":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300693 char = sourceget()
694 if char is None or char not in "=!":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200695 raise source.error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000696 dir = -1 # lookbehind
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200697 lookbehindgroups = state.lookbehindgroups
698 if lookbehindgroups is None:
699 state.lookbehindgroups = state.groups
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000700 p = _parse_sub(source, state)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200701 if dir < 0:
702 if lookbehindgroups is None:
703 state.lookbehindgroups = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000704 if not sourcematch(")"):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200705 raise source.error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000706 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000707 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000708 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000709 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000710 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300711 elif char == "(":
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000712 # conditional backreference group
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300713 condname = source.getuntil(")")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000714 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200715 if not condname:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200716 raise source.error("missing group name", 1)
Georg Brandl1d472b72013-04-14 11:40:00 +0200717 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000718 condgroup = state.groupdict.get(condname)
719 if condgroup is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700720 msg = "unknown group name: {0!r}".format(condname)
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200721 raise source.error(msg, len(condname) + 1)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000722 else:
723 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000724 condgroup = int(condname)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300725 if condgroup < 0:
726 raise ValueError
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000727 except ValueError:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200728 raise source.error("bad character in group name",
729 len(condname) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300730 if not condgroup:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200731 raise source.error("bad group number",
732 len(condname) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300733 if condgroup >= MAXGROUPS:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200734 raise source.error("the group number is too large",
735 len(condname) + 1)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200736 state.checklookbehindgroup(condgroup, source)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300737 elif char in FLAGS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000738 # flags
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300739 state.flags |= FLAGS[char]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000740 while source.next in FLAGS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300741 state.flags |= FLAGS[sourceget()]
742 verbose = state.flags & SRE_FLAG_VERBOSE
743 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200744 raise source.error("unexpected end of pattern")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000745 if group:
746 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000747 if group == 2:
748 # anonymous group
749 group = None
750 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200751 try:
752 group = state.opengroup(name)
753 except error as err:
754 raise source.error(err.msg, len(name) + 1)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000755 if condgroup:
756 p = _parse_sub_cond(source, state, condgroup)
757 else:
758 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000759 if not sourcematch(")"):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200760 raise source.error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000761 if group is not None:
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200762 state.closegroup(group, p)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000763 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000764 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300765 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000766 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000767 if char is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200768 raise source.error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000769 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000770 break
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200771 raise source.error("unknown extension", len(char))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000772
Fredrik Lundh90a07912000-06-30 07:50:59 +0000773 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000774 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000775
Fredrik Lundh90a07912000-06-30 07:50:59 +0000776 elif this == "$":
777 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000778
Fredrik Lundh90a07912000-06-30 07:50:59 +0000779 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200780 raise source.error("parser error", len(this))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000781
782 return subpattern
783
Antoine Pitroufd036452008-08-19 17:56:33 +0000784def fix_flags(src, flags):
785 # Check and fix flags according to the type of pattern (str or bytes)
786 if isinstance(src, str):
Serhiy Storchaka22a309a2014-12-01 11:50:07 +0200787 if flags & SRE_FLAG_LOCALE:
788 import warnings
789 warnings.warn("LOCALE flag with a str pattern is deprecated. "
790 "Will be an error in 3.6",
791 DeprecationWarning, stacklevel=6)
Antoine Pitroufd036452008-08-19 17:56:33 +0000792 if not flags & SRE_FLAG_ASCII:
793 flags |= SRE_FLAG_UNICODE
794 elif flags & SRE_FLAG_UNICODE:
795 raise ValueError("ASCII and UNICODE flags are incompatible")
796 else:
797 if flags & SRE_FLAG_UNICODE:
798 raise ValueError("can't use UNICODE flag with a bytes pattern")
Serhiy Storchaka22a309a2014-12-01 11:50:07 +0200799 if flags & SRE_FLAG_LOCALE and flags & SRE_FLAG_ASCII:
800 import warnings
801 warnings.warn("ASCII and LOCALE flags are incompatible. "
802 "Will be an error in 3.6",
803 DeprecationWarning, stacklevel=6)
Antoine Pitroufd036452008-08-19 17:56:33 +0000804 return flags
805
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000806def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000807 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000808
809 source = Tokenizer(str)
810
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000811 if pattern is None:
812 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000813 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000814 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000815
816 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000817 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000818
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300819 if source.next is not None:
820 if source.next == ")":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200821 raise source.error("unbalanced parenthesis")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300822 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200823 raise source.error("bogus characters at end of regular expression",
824 len(tail))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000825
Fredrik Lundh770617b2001-01-14 15:06:11 +0000826 if flags & SRE_FLAG_DEBUG:
827 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000828
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000829 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
830 # the VERBOSE flag was switched on inside the pattern. to be
831 # on the safe side, we'll parse the whole thing again...
832 return parse(str, p.pattern.flags)
833
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000834 return p
835
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000836def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000837 # parse 're' replacement string into list of literals and
838 # group references
839 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000840 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300841 groups = []
842 literals = []
843 literal = []
844 lappend = literal.append
845 def addgroup(index):
846 if literal:
847 literals.append(''.join(literal))
848 del literal[:]
849 groups.append((len(literals), index))
850 literals.append(None)
851 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000852 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000853 if this is None:
854 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300855 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000856 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300857 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000858 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000859 name = ""
860 if s.match("<"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300861 name = s.getuntil(">")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000862 if not name:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200863 raise s.error("missing group name", 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000864 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000865 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000866 if index < 0:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200867 raise s.error("negative group number", len(name) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300868 if index >= MAXGROUPS:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200869 raise s.error("the group number is too large",
870 len(name) + 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000871 except ValueError:
Georg Brandl1d472b72013-04-14 11:40:00 +0200872 if not name.isidentifier():
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200873 raise s.error("bad character in group name",
874 len(name) + 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000875 try:
876 index = pattern.groupindex[name]
877 except KeyError:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700878 msg = "unknown group name: {0!r}".format(name)
879 raise IndexError(msg)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300880 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000881 elif c == "0":
882 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300883 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000884 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300885 this += sget()
886 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000887 elif c in DIGITS:
888 isoctal = False
889 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300890 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000891 if (c in OCTDIGITS and this[2] in OCTDIGITS and
892 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300893 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000894 isoctal = True
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300895 c = int(this[1:], 8)
896 if c > 0o377:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200897 raise s.error('octal escape value %r outside of '
898 'range 0-0o377' % this, len(this))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300899 lappend(chr(c))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000900 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300901 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000902 else:
903 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300904 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000905 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000906 pass
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300907 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000908 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300909 lappend(this)
910 if literal:
911 literals.append(''.join(literal))
912 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000913 # The tokenizer implicitly decodes bytes objects as latin-1, we must
914 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300915 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000916 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000917
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000918def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000919 g = match.group
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300920 empty = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000921 groups, literals = template
922 literals = literals[:]
923 try:
924 for index, group in groups:
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300925 literals[index] = g(group) or empty
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000926 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000927 raise error("invalid group reference")
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300928 return empty.join(literals)