blob: 45411f89f16e9ff10a77738be76fbac34a46feec [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 Storchaka84df7fe2014-11-07 21:43:57 +020072 self.subpatterns = [None] # group 0
73 @property
74 def groups(self):
75 return len(self.subpatterns)
Fredrik Lundhebc37b22000-10-28 19:30:41 +000076 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000077 gid = self.groups
Serhiy Storchaka84df7fe2014-11-07 21:43:57 +020078 self.subpatterns.append(None)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +030079 if self.groups > MAXGROUPS:
80 raise error("groups number is too large")
Raymond Hettingerf13eb552002-06-02 00:40:05 +000081 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000082 ogid = self.groupdict.get(name, None)
83 if ogid is not None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +020084 raise error("redefinition of group name %r as group %d; "
85 "was group %d" % (name, gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000086 self.groupdict[name] = gid
87 return gid
Serhiy Storchaka84df7fe2014-11-07 21:43:57 +020088 def closegroup(self, gid, p):
89 self.subpatterns[gid] = p
Fredrik Lundhebc37b22000-10-28 19:30:41 +000090 def checkgroup(self, gid):
Serhiy Storchaka84df7fe2014-11-07 21:43:57 +020091 return gid < self.groups and self.subpatterns[gid] is not None
Guido van Rossum7627c0d2000-03-31 14:58:54 +000092
93class SubPattern:
94 # a subpattern, in intermediate form
95 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000096 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000097 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000098 data = []
99 self.data = data
100 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000101 def dump(self, level=0):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300102 nl = True
Guido van Rossum13257902007-06-07 23:15:56 +0000103 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000104 for op, av in self.data:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200105 print(level*" " + str(op), end='')
Serhiy Storchakaab140882014-11-11 21:13:28 +0200106 if op is IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000107 # member sublanguage
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300108 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000109 for op, a in av:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200110 print((level+1)*" " + str(op), a)
Serhiy Storchakaab140882014-11-11 21:13:28 +0200111 elif op is BRANCH:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300112 print()
113 for i, a in enumerate(av[1]):
114 if i:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200115 print(level*" " + "OR")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300116 a.dump(level+1)
Serhiy Storchakaab140882014-11-11 21:13:28 +0200117 elif op is GROUPREF_EXISTS:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300118 condgroup, item_yes, item_no = av
119 print('', condgroup)
120 item_yes.dump(level+1)
121 if item_no:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200122 print(level*" " + "ELSE")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300123 item_no.dump(level+1)
Guido van Rossum13257902007-06-07 23:15:56 +0000124 elif isinstance(av, seqtypes):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300125 nl = False
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000126 for a in av:
127 if isinstance(a, SubPattern):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300128 if not nl:
129 print()
130 a.dump(level+1)
131 nl = True
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000132 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300133 if not nl:
134 print(' ', end='')
135 print(a, end='')
136 nl = False
137 if not nl:
138 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000139 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300140 print('', av)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000141 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000142 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000143 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000144 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000145 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000146 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000147 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000148 if isinstance(index, slice):
149 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000150 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000151 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000152 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000153 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000154 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000155 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000156 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000157 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000158 # determine the width (min, max) for this subpattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300159 if self.width is not None:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000160 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000161 lo = hi = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000162 for op, av in self.data:
163 if op is BRANCH:
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300164 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000165 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000166 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000167 l, h = av.getwidth()
168 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000169 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000170 lo = lo + i
171 hi = hi + j
172 elif op is CALL:
173 i, j = av.getwidth()
174 lo = lo + i
175 hi = hi + j
176 elif op is SUBPATTERN:
177 i, j = av[1].getwidth()
178 lo = lo + i
179 hi = hi + j
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300180 elif op in _REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000181 i, j = av[2].getwidth()
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300182 lo = lo + i * av[0]
183 hi = hi + j * av[1]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300184 elif op in _UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000185 lo = lo + 1
186 hi = hi + 1
Serhiy Storchaka84df7fe2014-11-07 21:43:57 +0200187 elif op is GROUPREF:
188 i, j = self.pattern.subpatterns[av].getwidth()
189 lo = lo + i
190 hi = hi + j
191 elif op is GROUPREF_EXISTS:
192 i, j = av[1].getwidth()
193 if av[2] is not None:
194 l, h = av[2].getwidth()
195 i = min(i, l)
196 j = max(j, h)
197 else:
198 i = 0
199 lo = lo + i
200 hi = hi + j
201 elif op is SUCCESS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000202 break
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300203 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000204 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000205
206class Tokenizer:
207 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200208 self.istext = isinstance(string, str)
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200209 self.string = string
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300210 if not self.istext:
211 string = str(string, 'latin1')
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200212 self.decoded_string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000213 self.index = 0
Serhiy Storchakab99c1322014-11-10 14:38:16 +0200214 self.next = None
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000215 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000216 def __next(self):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300217 index = self.index
218 try:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200219 char = self.decoded_string[index]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300220 except IndexError:
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000221 self.next = None
222 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000223 if char == "\\":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300224 index += 1
Fredrik Lundh90a07912000-06-30 07:50:59 +0000225 try:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200226 char += self.decoded_string[index]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000227 except IndexError:
Serhiy Storchaka1b2004f2014-11-10 18:28:53 +0200228 raise error("bogus escape (end of line)",
229 self.string, len(self.string) - 1) from None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300230 self.index = index + 1
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000231 self.next = char
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300232 def match(self, char):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000233 if char == self.next:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300234 self.__next()
235 return True
236 return False
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000237 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000238 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000239 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000240 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200241 def getwhile(self, n, charset):
242 result = ''
243 for _ in range(n):
244 c = self.next
245 if c not in charset:
246 break
247 result += c
248 self.__next()
249 return result
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300250 def getuntil(self, terminator):
251 result = ''
252 while True:
253 c = self.next
254 self.__next()
255 if c is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200256 raise self.error("unterminated name")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300257 if c == terminator:
258 break
259 result += c
260 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000261 def tell(self):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200262 return self.index - len(self.next or '')
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000263 def seek(self, index):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200264 self.index = index
265 self.__next()
266
267 def error(self, msg, offset=0):
268 return error(msg, self.string, self.tell() - offset)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000269
Georg Brandl1d472b72013-04-14 11:40:00 +0200270# The following three functions are not used in this module anymore, but we keep
271# them here (with DeprecationWarnings) for backwards compatibility.
272
Fredrik Lundh4781b072000-06-29 12:38:45 +0000273def isident(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200274 import warnings
275 warnings.warn('sre_parse.isident() will be removed in 3.5',
276 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000277 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
278
279def isdigit(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200280 import warnings
281 warnings.warn('sre_parse.isdigit() will be removed in 3.5',
282 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000283 return "0" <= char <= "9"
284
285def isname(name):
Georg Brandl1d472b72013-04-14 11:40:00 +0200286 import warnings
287 warnings.warn('sre_parse.isname() will be removed in 3.5',
288 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000289 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000290 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000291 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000292 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000293 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000294 return False
295 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000296
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000297def _class_escape(source, escape):
298 # handle escape code inside character class
299 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000300 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000301 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000302 code = CATEGORIES.get(escape)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300303 if code and code[0] is IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000304 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000305 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000306 c = escape[1:2]
307 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000308 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200309 escape += source.getwhile(2, HEXDIGITS)
310 if len(escape) != 4:
311 raise ValueError
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300312 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200313 elif c == "u" and source.istext:
314 # unicode escape (exactly four digits)
315 escape += source.getwhile(4, HEXDIGITS)
316 if len(escape) != 6:
317 raise ValueError
318 return LITERAL, int(escape[2:], 16)
319 elif c == "U" and source.istext:
320 # unicode escape (exactly eight digits)
321 escape += source.getwhile(8, HEXDIGITS)
322 if len(escape) != 10:
323 raise ValueError
324 c = int(escape[2:], 16)
325 chr(c) # raise ValueError for invalid code
326 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000327 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000328 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200329 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300330 c = int(escape[1:], 8)
331 if c > 0o377:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200332 raise source.error('octal escape value %r outside of '
333 'range 0-0o377' % escape, len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300334 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000335 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200336 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000337 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000338 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000339 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000340 pass
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200341 raise source.error("bogus escape: %r" % escape, len(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000342
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000343def _escape(source, escape, state):
344 # handle escape code in expression
345 code = CATEGORIES.get(escape)
346 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000347 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000348 code = ESCAPES.get(escape)
349 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000350 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000351 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000352 c = escape[1:2]
353 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000354 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200355 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000356 if len(escape) != 4:
357 raise ValueError
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300358 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200359 elif c == "u" and source.istext:
360 # unicode escape (exactly four digits)
361 escape += source.getwhile(4, HEXDIGITS)
362 if len(escape) != 6:
363 raise ValueError
364 return LITERAL, int(escape[2:], 16)
365 elif c == "U" and source.istext:
366 # unicode escape (exactly eight digits)
367 escape += source.getwhile(8, HEXDIGITS)
368 if len(escape) != 10:
369 raise ValueError
370 c = int(escape[2:], 16)
371 chr(c) # raise ValueError for invalid code
372 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000373 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000374 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200375 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300376 return LITERAL, int(escape[1:], 8)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000377 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000378 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000379 if source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300380 escape += source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000381 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
382 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000383 # got three octal digits; this is an octal escape
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300384 escape += source.get()
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300385 c = int(escape[1:], 8)
386 if c > 0o377:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200387 raise source.error('octal escape value %r outside of '
388 'range 0-0o377' % escape,
389 len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300390 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000391 # not an octal escape, so this is a group reference
392 group = int(escape[1:])
393 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000394 if not state.checkgroup(group):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200395 raise source.error("cannot refer to open group",
396 len(escape))
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000397 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000398 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000399 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000400 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000401 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000402 pass
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200403 raise source.error("bogus escape: %r" % escape, len(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000404
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300405def _parse_sub(source, state, nested=True):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000406 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000407
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000408 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000409 itemsappend = items.append
410 sourcematch = source.match
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300411 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000412 itemsappend(_parse(source, state))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300413 if not sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000414 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300415 if nested and source.next is not None and source.next != ")":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200416 raise source.error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000417
418 if len(items) == 1:
419 return items[0]
420
421 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000422 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000423
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000424 # check if all items share a common prefix
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300425 while True:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000426 prefix = None
427 for item in items:
428 if not item:
429 break
430 if prefix is None:
431 prefix = item[0]
432 elif item[0] != prefix:
433 break
434 else:
435 # all subitems start with a common "prefix".
436 # move it out of the branch
437 for item in items:
438 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000439 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000440 continue # check next one
441 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000442
443 # check if the branch can be replaced by a character set
444 for item in items:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300445 if len(item) != 1 or item[0][0] is not LITERAL:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000446 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000447 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000448 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000449 # branch (the compiler may optimize this even more)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300450 subpatternappend((IN, [item[0] for item in items]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000451 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000452
453 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000454 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000455
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000456def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000457 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000458 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000459 item_no = _parse(source, state)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300460 if source.next == "|":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200461 raise source.error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000462 else:
463 item_no = None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300464 if source.next is not None and source.next != ")":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200465 raise source.error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000466 subpattern = SubPattern(state)
467 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
468 return subpattern
469
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000470def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000471 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000472 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000473
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000474 # precompute constants into local variables
475 subpatternappend = subpattern.append
476 sourceget = source.get
477 sourcematch = source.match
478 _len = len
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300479 _ord = ord
480 verbose = state.flags & SRE_FLAG_VERBOSE
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000481
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300482 while True:
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000483
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300484 this = source.next
Fredrik Lundh90a07912000-06-30 07:50:59 +0000485 if this is None:
486 break # end of pattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300487 if this in "|)":
488 break # end of subpattern
489 sourceget()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000490
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300491 if verbose:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000492 # skip whitespace and comments
493 if this in WHITESPACE:
494 continue
495 if this == "#":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300496 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000497 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300498 if this is None or this == "\n":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000499 break
500 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000501
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300502 if this[0] == "\\":
503 code = _escape(source, this, state)
504 subpatternappend(code)
505
506 elif this not in SPECIAL_CHARS:
507 subpatternappend((LITERAL, _ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000508
Fredrik Lundh90a07912000-06-30 07:50:59 +0000509 elif this == "[":
510 # character set
511 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000512 setappend = set.append
513## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000514## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000515 if sourcematch("^"):
516 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000517 # check remaining characters
518 start = set[:]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300519 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000520 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300521 if this is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200522 raise source.error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000523 if this == "]" and set != start:
524 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300525 elif this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000526 code1 = _class_escape(source, this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000527 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300528 code1 = LITERAL, _ord(this)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000529 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000530 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000531 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300532 if this is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200533 raise source.error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000534 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000535 if code1[0] is IN:
536 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000537 setappend(code1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300538 setappend((LITERAL, _ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000539 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300540 if this[0] == "\\":
541 code2 = _class_escape(source, this)
Guido van Rossum41c99e72003-04-14 17:59:34 +0000542 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300543 code2 = LITERAL, _ord(this)
544 if code1[0] != LITERAL or code2[0] != LITERAL:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200545 raise source.error("bad character range", len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300546 lo = code1[1]
547 hi = code2[1]
548 if hi < lo:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200549 raise source.error("bad character range", len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300550 setappend((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000551 else:
552 if code1[0] is IN:
553 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000554 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000555
Fredrik Lundh770617b2001-01-14 15:06:11 +0000556 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000557 if _len(set)==1 and set[0][0] is LITERAL:
558 subpatternappend(set[0]) # optimization
559 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
560 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000561 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000562 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000563 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000564
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300565 elif this in REPEAT_CHARS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000566 # repeat previous item
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200567 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000568 if this == "?":
569 min, max = 0, 1
570 elif this == "*":
571 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000572
Fredrik Lundh90a07912000-06-30 07:50:59 +0000573 elif this == "+":
574 min, max = 1, MAXREPEAT
575 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000576 if source.next == "}":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300577 subpatternappend((LITERAL, _ord(this)))
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000578 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000579 min, max = 0, MAXREPEAT
580 lo = hi = ""
581 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300582 lo += sourceget()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000583 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000584 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300585 hi += sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000586 else:
587 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000588 if not sourcematch("}"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300589 subpatternappend((LITERAL, _ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000590 source.seek(here)
591 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000592 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000593 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200594 if min >= MAXREPEAT:
595 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000596 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000597 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200598 if max >= MAXREPEAT:
599 raise OverflowError("the repetition number is too large")
600 if max < min:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200601 raise source.error("bad repeat interval",
602 source.tell() - here)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000603 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200604 raise source.error("not supported", len(this))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000605 # figure out which item to repeat
606 if subpattern:
607 item = subpattern[-1:]
608 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000609 item = None
Serhiy Storchakaab140882014-11-11 21:13:28 +0200610 if not item or (_len(item) == 1 and item[0][0] is AT):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200611 raise source.error("nothing to repeat",
612 source.tell() - here + len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300613 if item[0][0] in _REPEATCODES:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200614 raise source.error("multiple repeat",
615 source.tell() - here + len(this))
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000616 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000617 subpattern[-1] = (MIN_REPEAT, (min, max, item))
618 else:
619 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000620
Fredrik Lundh90a07912000-06-30 07:50:59 +0000621 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000622 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000623
Fredrik Lundh90a07912000-06-30 07:50:59 +0000624 elif this == "(":
625 group = 1
626 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000627 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000628 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000629 group = 0
630 # options
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300631 char = sourceget()
632 if char is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200633 raise self.error("unexpected end of pattern")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300634 if char == "P":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000635 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000636 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000637 # named group: skip forward to end of name
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300638 name = source.getuntil(">")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000639 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200640 if not name:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200641 raise source.error("missing group name", 1)
Georg Brandl1d472b72013-04-14 11:40:00 +0200642 if not name.isidentifier():
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200643 raise source.error("bad character in group name "
644 "%r" % name,
645 len(name) + 1)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000646 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000647 # named backreference
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300648 name = source.getuntil(")")
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200649 if not name:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200650 raise source.error("missing group name", 1)
Georg Brandl1d472b72013-04-14 11:40:00 +0200651 if not name.isidentifier():
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200652 raise source.error("bad character in backref "
653 "group name %r" % name,
654 len(name) + 1)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000655 gid = state.groupdict.get(name)
656 if gid is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700657 msg = "unknown group name: {0!r}".format(name)
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200658 raise source.error(msg, len(name) + 1)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000659 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000660 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000661 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000662 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000663 if char is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200664 raise source.error("unexpected end of pattern")
665 raise source.error("unknown specifier: ?P%s" % char,
666 len(char))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300667 elif char == ":":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000668 # non-capturing group
669 group = 2
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300670 elif char == "#":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000671 # comment
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300672 while True:
673 if source.next is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200674 raise source.error("unbalanced parenthesis")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300675 if sourceget() == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000676 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000677 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300678 elif char in "=!<":
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000679 # lookahead assertions
Fredrik Lundh6f013982000-07-03 18:44:21 +0000680 dir = 1
681 if char == "<":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300682 char = sourceget()
683 if char is None or char not in "=!":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200684 raise source.error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000685 dir = -1 # lookbehind
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000686 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000687 if not sourcematch(")"):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200688 raise source.error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000689 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000690 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000691 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000692 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000693 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300694 elif char == "(":
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000695 # conditional backreference group
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300696 condname = source.getuntil(")")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000697 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200698 if not condname:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200699 raise source.error("missing group name", 1)
Georg Brandl1d472b72013-04-14 11:40:00 +0200700 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000701 condgroup = state.groupdict.get(condname)
702 if condgroup is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700703 msg = "unknown group name: {0!r}".format(condname)
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200704 raise source.error(msg, len(condname) + 1)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000705 else:
706 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000707 condgroup = int(condname)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300708 if condgroup < 0:
709 raise ValueError
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000710 except ValueError:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200711 raise source.error("bad character in group name",
712 len(condname) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300713 if not condgroup:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200714 raise source.error("bad group number",
715 len(condname) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300716 if condgroup >= MAXGROUPS:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200717 raise source.error("the group number is too large",
718 len(condname) + 1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300719 elif char in FLAGS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000720 # flags
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300721 state.flags |= FLAGS[char]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000722 while source.next in FLAGS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300723 state.flags |= FLAGS[sourceget()]
724 verbose = state.flags & SRE_FLAG_VERBOSE
725 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200726 raise source.error("unexpected end of pattern")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000727 if group:
728 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000729 if group == 2:
730 # anonymous group
731 group = None
732 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200733 try:
734 group = state.opengroup(name)
735 except error as err:
736 raise source.error(err.msg, len(name) + 1)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000737 if condgroup:
738 p = _parse_sub_cond(source, state, condgroup)
739 else:
740 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000741 if not sourcematch(")"):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200742 raise source.error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000743 if group is not None:
Serhiy Storchaka84df7fe2014-11-07 21:43:57 +0200744 state.closegroup(group, p)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000745 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000746 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300747 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000748 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000749 if char is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200750 raise source.error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000751 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000752 break
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200753 raise source.error("unknown extension", len(char))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000754
Fredrik Lundh90a07912000-06-30 07:50:59 +0000755 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000756 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000757
Fredrik Lundh90a07912000-06-30 07:50:59 +0000758 elif this == "$":
759 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000760
Fredrik Lundh90a07912000-06-30 07:50:59 +0000761 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200762 raise source.error("parser error", len(this))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000763
764 return subpattern
765
Antoine Pitroufd036452008-08-19 17:56:33 +0000766def fix_flags(src, flags):
767 # Check and fix flags according to the type of pattern (str or bytes)
768 if isinstance(src, str):
769 if not flags & SRE_FLAG_ASCII:
770 flags |= SRE_FLAG_UNICODE
771 elif flags & SRE_FLAG_UNICODE:
772 raise ValueError("ASCII and UNICODE flags are incompatible")
773 else:
774 if flags & SRE_FLAG_UNICODE:
775 raise ValueError("can't use UNICODE flag with a bytes pattern")
776 return flags
777
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000778def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000779 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000780
781 source = Tokenizer(str)
782
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000783 if pattern is None:
784 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000785 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000786 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000787
788 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000789 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000790
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300791 if source.next is not None:
792 if source.next == ")":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200793 raise source.error("unbalanced parenthesis")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300794 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200795 raise source.error("bogus characters at end of regular expression",
796 len(tail))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000797
Fredrik Lundh770617b2001-01-14 15:06:11 +0000798 if flags & SRE_FLAG_DEBUG:
799 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000800
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000801 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
802 # the VERBOSE flag was switched on inside the pattern. to be
803 # on the safe side, we'll parse the whole thing again...
804 return parse(str, p.pattern.flags)
805
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000806 return p
807
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000808def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000809 # parse 're' replacement string into list of literals and
810 # group references
811 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000812 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300813 groups = []
814 literals = []
815 literal = []
816 lappend = literal.append
817 def addgroup(index):
818 if literal:
819 literals.append(''.join(literal))
820 del literal[:]
821 groups.append((len(literals), index))
822 literals.append(None)
823 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000824 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000825 if this is None:
826 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300827 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000828 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300829 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000830 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000831 name = ""
832 if s.match("<"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300833 name = s.getuntil(">")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000834 if not name:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200835 raise s.error("missing group name", 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000836 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000837 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000838 if index < 0:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200839 raise s.error("negative group number", len(name) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300840 if index >= MAXGROUPS:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200841 raise s.error("the group number is too large",
842 len(name) + 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000843 except ValueError:
Georg Brandl1d472b72013-04-14 11:40:00 +0200844 if not name.isidentifier():
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200845 raise s.error("bad character in group name",
846 len(name) + 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000847 try:
848 index = pattern.groupindex[name]
849 except KeyError:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700850 msg = "unknown group name: {0!r}".format(name)
851 raise IndexError(msg)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300852 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000853 elif c == "0":
854 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300855 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000856 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300857 this += sget()
858 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000859 elif c in DIGITS:
860 isoctal = False
861 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300862 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000863 if (c in OCTDIGITS and this[2] in OCTDIGITS and
864 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300865 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000866 isoctal = True
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300867 c = int(this[1:], 8)
868 if c > 0o377:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200869 raise s.error('octal escape value %r outside of '
870 'range 0-0o377' % this, len(this))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300871 lappend(chr(c))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000872 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300873 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000874 else:
875 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300876 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000877 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000878 pass
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300879 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000880 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300881 lappend(this)
882 if literal:
883 literals.append(''.join(literal))
884 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000885 # The tokenizer implicitly decodes bytes objects as latin-1, we must
886 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300887 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000888 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000889
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000890def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000891 g = match.group
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300892 empty = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000893 groups, literals = template
894 literals = literals[:]
895 try:
896 for index, group in groups:
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300897 literals[index] = g(group) or empty
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000898 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000899 raise error("invalid group reference")
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300900 return empty.join(literals)