blob: 768ed792ee135e4ea6810a5b21ea2b0b3fc1ba95 [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
27_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:
Collin Winterce36ad82007-08-30 01:19:48 +000084 raise error("redefinition of group name %s as group %d; "
85 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000086 self.groupdict[name] = gid
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 Storchaka44dae8b2014-09-21 22:47:55 +0300106 if op == 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 Storchaka44dae8b2014-09-21 22:47:55 +0300111 elif op == BRANCH:
112 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)
117 elif op == GROUPREF_EXISTS:
118 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 Storchakae2ccf562014-10-10 11:14:49 +0300209 if not self.istext:
210 string = str(string, 'latin1')
Fredrik Lundh90a07912000-06-30 07:50:59 +0000211 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000212 self.index = 0
213 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000214 def __next(self):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300215 index = self.index
216 try:
217 char = self.string[index]
218 except IndexError:
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000219 self.next = None
220 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000221 if char == "\\":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300222 index += 1
Fredrik Lundh90a07912000-06-30 07:50:59 +0000223 try:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300224 char += self.string[index]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000225 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000226 raise error("bogus escape (end of line)")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300227 self.index = index + 1
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000228 self.next = char
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300229 def match(self, char):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000230 if char == self.next:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300231 self.__next()
232 return True
233 return False
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000234 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000235 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000236 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000237 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200238 def getwhile(self, n, charset):
239 result = ''
240 for _ in range(n):
241 c = self.next
242 if c not in charset:
243 break
244 result += c
245 self.__next()
246 return result
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300247 def getuntil(self, terminator):
248 result = ''
249 while True:
250 c = self.next
251 self.__next()
252 if c is None:
253 raise error("unterminated name")
254 if c == terminator:
255 break
256 result += c
257 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000258 def tell(self):
259 return self.index, self.next
260 def seek(self, index):
261 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000262
Georg Brandl1d472b72013-04-14 11:40:00 +0200263# The following three functions are not used in this module anymore, but we keep
264# them here (with DeprecationWarnings) for backwards compatibility.
265
Fredrik Lundh4781b072000-06-29 12:38:45 +0000266def isident(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200267 import warnings
268 warnings.warn('sre_parse.isident() will be removed in 3.5',
269 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000270 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
271
272def isdigit(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200273 import warnings
274 warnings.warn('sre_parse.isdigit() will be removed in 3.5',
275 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000276 return "0" <= char <= "9"
277
278def isname(name):
Georg Brandl1d472b72013-04-14 11:40:00 +0200279 import warnings
280 warnings.warn('sre_parse.isname() will be removed in 3.5',
281 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000282 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000283 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000284 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000285 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000286 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000287 return False
288 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000289
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000290def _class_escape(source, escape):
291 # handle escape code inside character class
292 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000293 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000294 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000295 code = CATEGORIES.get(escape)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300296 if code and code[0] is IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000297 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000298 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000299 c = escape[1:2]
300 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000301 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200302 escape += source.getwhile(2, HEXDIGITS)
303 if len(escape) != 4:
304 raise ValueError
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300305 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200306 elif c == "u" and source.istext:
307 # unicode escape (exactly four digits)
308 escape += source.getwhile(4, HEXDIGITS)
309 if len(escape) != 6:
310 raise ValueError
311 return LITERAL, int(escape[2:], 16)
312 elif c == "U" and source.istext:
313 # unicode escape (exactly eight digits)
314 escape += source.getwhile(8, HEXDIGITS)
315 if len(escape) != 10:
316 raise ValueError
317 c = int(escape[2:], 16)
318 chr(c) # raise ValueError for invalid code
319 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000320 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000321 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200322 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300323 c = int(escape[1:], 8)
324 if c > 0o377:
325 raise error('octal escape value %r outside of '
326 'range 0-0o377' % escape)
327 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000328 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200329 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000330 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000331 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000332 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000333 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000334 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000335
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000336def _escape(source, escape, state):
337 # handle escape code in expression
338 code = CATEGORIES.get(escape)
339 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000340 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000341 code = ESCAPES.get(escape)
342 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000343 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000344 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000345 c = escape[1:2]
346 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000347 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200348 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000349 if len(escape) != 4:
350 raise ValueError
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300351 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200352 elif c == "u" and source.istext:
353 # unicode escape (exactly four digits)
354 escape += source.getwhile(4, HEXDIGITS)
355 if len(escape) != 6:
356 raise ValueError
357 return LITERAL, int(escape[2:], 16)
358 elif c == "U" and source.istext:
359 # unicode escape (exactly eight digits)
360 escape += source.getwhile(8, HEXDIGITS)
361 if len(escape) != 10:
362 raise ValueError
363 c = int(escape[2:], 16)
364 chr(c) # raise ValueError for invalid code
365 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000366 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000367 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200368 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300369 return LITERAL, int(escape[1:], 8)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000370 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000371 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000372 if source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300373 escape += source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000374 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
375 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000376 # got three octal digits; this is an octal escape
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300377 escape += source.get()
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300378 c = int(escape[1:], 8)
379 if c > 0o377:
380 raise error('octal escape value %r outside of '
381 'range 0-0o377' % escape)
382 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000383 # not an octal escape, so this is a group reference
384 group = int(escape[1:])
385 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000386 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000387 raise error("cannot refer to open group")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000388 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000389 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000390 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000391 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000392 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000393 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000394 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000395
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300396def _parse_sub(source, state, nested=True):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000397 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000398
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000399 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000400 itemsappend = items.append
401 sourcematch = source.match
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300402 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000403 itemsappend(_parse(source, state))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300404 if not sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000405 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300406 if nested and source.next is not None and source.next != ")":
407 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000408
409 if len(items) == 1:
410 return items[0]
411
412 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000413 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000414
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000415 # check if all items share a common prefix
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300416 while True:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000417 prefix = None
418 for item in items:
419 if not item:
420 break
421 if prefix is None:
422 prefix = item[0]
423 elif item[0] != prefix:
424 break
425 else:
426 # all subitems start with a common "prefix".
427 # move it out of the branch
428 for item in items:
429 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000430 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000431 continue # check next one
432 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000433
434 # check if the branch can be replaced by a character set
435 for item in items:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300436 if len(item) != 1 or item[0][0] is not LITERAL:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000437 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000438 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000439 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000440 # branch (the compiler may optimize this even more)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300441 subpatternappend((IN, [item[0] for item in items]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000442 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000443
444 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000445 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000446
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000447def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000448 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000449 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000450 item_no = _parse(source, state)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300451 if source.next == "|":
Collin Winterce36ad82007-08-30 01:19:48 +0000452 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000453 else:
454 item_no = None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300455 if source.next is not None and source.next != ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000456 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000457 subpattern = SubPattern(state)
458 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
459 return subpattern
460
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000461def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000462 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000463 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000464
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000465 # precompute constants into local variables
466 subpatternappend = subpattern.append
467 sourceget = source.get
468 sourcematch = source.match
469 _len = len
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300470 _ord = ord
471 verbose = state.flags & SRE_FLAG_VERBOSE
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000472
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300473 while True:
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000474
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300475 this = source.next
Fredrik Lundh90a07912000-06-30 07:50:59 +0000476 if this is None:
477 break # end of pattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300478 if this in "|)":
479 break # end of subpattern
480 sourceget()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000481
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300482 if verbose:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000483 # skip whitespace and comments
484 if this in WHITESPACE:
485 continue
486 if this == "#":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300487 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000488 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300489 if this is None or this == "\n":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000490 break
491 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000492
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300493 if this[0] == "\\":
494 code = _escape(source, this, state)
495 subpatternappend(code)
496
497 elif this not in SPECIAL_CHARS:
498 subpatternappend((LITERAL, _ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000499
Fredrik Lundh90a07912000-06-30 07:50:59 +0000500 elif this == "[":
501 # character set
502 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000503 setappend = set.append
504## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000505## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000506 if sourcematch("^"):
507 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000508 # check remaining characters
509 start = set[:]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300510 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000511 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300512 if this is None:
513 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000514 if this == "]" and set != start:
515 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300516 elif this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000517 code1 = _class_escape(source, this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000518 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300519 code1 = LITERAL, _ord(this)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000520 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000521 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000522 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300523 if this is None:
524 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000525 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000526 if code1[0] is IN:
527 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000528 setappend(code1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300529 setappend((LITERAL, _ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000530 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300531 if this[0] == "\\":
532 code2 = _class_escape(source, this)
Guido van Rossum41c99e72003-04-14 17:59:34 +0000533 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300534 code2 = LITERAL, _ord(this)
535 if code1[0] != LITERAL or code2[0] != LITERAL:
536 raise error("bad character range")
537 lo = code1[1]
538 hi = code2[1]
539 if hi < lo:
540 raise error("bad character range")
541 setappend((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000542 else:
543 if code1[0] is IN:
544 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000545 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000546
Fredrik Lundh770617b2001-01-14 15:06:11 +0000547 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000548 if _len(set)==1 and set[0][0] is LITERAL:
549 subpatternappend(set[0]) # optimization
550 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
551 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000552 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000553 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000554 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000555
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300556 elif this in REPEAT_CHARS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000557 # repeat previous item
558 if this == "?":
559 min, max = 0, 1
560 elif this == "*":
561 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000562
Fredrik Lundh90a07912000-06-30 07:50:59 +0000563 elif this == "+":
564 min, max = 1, MAXREPEAT
565 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000566 if source.next == "}":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300567 subpatternappend((LITERAL, _ord(this)))
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000568 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000569 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000570 min, max = 0, MAXREPEAT
571 lo = hi = ""
572 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300573 lo += sourceget()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000574 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000575 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300576 hi += sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000577 else:
578 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000579 if not sourcematch("}"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300580 subpatternappend((LITERAL, _ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000581 source.seek(here)
582 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000583 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000584 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200585 if min >= MAXREPEAT:
586 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000587 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000588 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200589 if max >= MAXREPEAT:
590 raise OverflowError("the repetition number is too large")
591 if max < min:
592 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000593 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000594 raise error("not supported")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000595 # figure out which item to repeat
596 if subpattern:
597 item = subpattern[-1:]
598 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000599 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000600 if not item or (_len(item) == 1 and item[0][0] == AT):
Collin Winterce36ad82007-08-30 01:19:48 +0000601 raise error("nothing to repeat")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300602 if item[0][0] in _REPEATCODES:
Collin Winterce36ad82007-08-30 01:19:48 +0000603 raise error("multiple repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000604 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000605 subpattern[-1] = (MIN_REPEAT, (min, max, item))
606 else:
607 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000608
Fredrik Lundh90a07912000-06-30 07:50:59 +0000609 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000610 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000611
Fredrik Lundh90a07912000-06-30 07:50:59 +0000612 elif this == "(":
613 group = 1
614 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000615 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000616 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000617 group = 0
618 # options
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300619 char = sourceget()
620 if char is None:
621 raise error("unexpected end of pattern")
622 if char == "P":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000623 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000624 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000625 # named group: skip forward to end of name
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300626 name = source.getuntil(">")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000627 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200628 if not name:
629 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200630 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400631 raise error("bad character in group name %r" % name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000632 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000633 # named backreference
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300634 name = source.getuntil(")")
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200635 if not name:
636 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200637 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400638 raise error("bad character in backref group name "
639 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000640 gid = state.groupdict.get(name)
641 if gid is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700642 msg = "unknown group name: {0!r}".format(name)
643 raise error(msg)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000644 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000645 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000646 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000647 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000648 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000649 raise error("unexpected end of pattern")
650 raise error("unknown specifier: ?P%s" % char)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300651 elif char == ":":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000652 # non-capturing group
653 group = 2
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300654 elif char == "#":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000655 # comment
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300656 while True:
657 if source.next is None:
658 raise error("unbalanced parenthesis")
659 if sourceget() == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000660 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000661 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300662 elif char in "=!<":
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000663 # lookahead assertions
Fredrik Lundh6f013982000-07-03 18:44:21 +0000664 dir = 1
665 if char == "<":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300666 char = sourceget()
667 if char is None or char not in "=!":
Collin Winterce36ad82007-08-30 01:19:48 +0000668 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000669 dir = -1 # lookbehind
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000670 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000671 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000672 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000673 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000674 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000675 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000676 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000677 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300678 elif char == "(":
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000679 # conditional backreference group
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300680 condname = source.getuntil(")")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000681 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200682 if not condname:
683 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200684 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000685 condgroup = state.groupdict.get(condname)
686 if condgroup is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700687 msg = "unknown group name: {0!r}".format(condname)
688 raise error(msg)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000689 else:
690 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000691 condgroup = int(condname)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300692 if condgroup < 0:
693 raise ValueError
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000694 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000695 raise error("bad character in group name")
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300696 if not condgroup:
697 raise error("bad group number")
698 if condgroup >= MAXGROUPS:
699 raise error("the group number is too large")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300700 elif char in FLAGS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000701 # flags
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300702 state.flags |= FLAGS[char]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000703 while source.next in FLAGS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300704 state.flags |= FLAGS[sourceget()]
705 verbose = state.flags & SRE_FLAG_VERBOSE
706 else:
707 raise error("unexpected end of pattern " + char)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000708 if group:
709 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000710 if group == 2:
711 # anonymous group
712 group = None
713 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000714 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000715 if condgroup:
716 p = _parse_sub_cond(source, state, condgroup)
717 else:
718 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000719 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000720 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000721 if group is not None:
Serhiy Storchaka84df7fe2014-11-07 21:43:57 +0200722 state.closegroup(group, p)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000723 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000724 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300725 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000726 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000727 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000728 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000729 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000730 break
Collin Winterce36ad82007-08-30 01:19:48 +0000731 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000732
Fredrik Lundh90a07912000-06-30 07:50:59 +0000733 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000734 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000735
Fredrik Lundh90a07912000-06-30 07:50:59 +0000736 elif this == "$":
737 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000738
Fredrik Lundh90a07912000-06-30 07:50:59 +0000739 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000740 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000741
742 return subpattern
743
Antoine Pitroufd036452008-08-19 17:56:33 +0000744def fix_flags(src, flags):
745 # Check and fix flags according to the type of pattern (str or bytes)
746 if isinstance(src, str):
747 if not flags & SRE_FLAG_ASCII:
748 flags |= SRE_FLAG_UNICODE
749 elif flags & SRE_FLAG_UNICODE:
750 raise ValueError("ASCII and UNICODE flags are incompatible")
751 else:
752 if flags & SRE_FLAG_UNICODE:
753 raise ValueError("can't use UNICODE flag with a bytes pattern")
754 return flags
755
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000756def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000757 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000758
759 source = Tokenizer(str)
760
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000761 if pattern is None:
762 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000763 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000764 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000765
766 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000767 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000768
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300769 if source.next is not None:
770 if source.next == ")":
771 raise error("unbalanced parenthesis")
772 else:
773 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000774
Fredrik Lundh770617b2001-01-14 15:06:11 +0000775 if flags & SRE_FLAG_DEBUG:
776 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000777
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000778 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
779 # the VERBOSE flag was switched on inside the pattern. to be
780 # on the safe side, we'll parse the whole thing again...
781 return parse(str, p.pattern.flags)
782
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000783 return p
784
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000785def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000786 # parse 're' replacement string into list of literals and
787 # group references
788 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000789 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300790 groups = []
791 literals = []
792 literal = []
793 lappend = literal.append
794 def addgroup(index):
795 if literal:
796 literals.append(''.join(literal))
797 del literal[:]
798 groups.append((len(literals), index))
799 literals.append(None)
800 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000801 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000802 if this is None:
803 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300804 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000805 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300806 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000807 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000808 name = ""
809 if s.match("<"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300810 name = s.getuntil(">")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000811 if not name:
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200812 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000813 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000814 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000815 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000816 raise error("negative group number")
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300817 if index >= MAXGROUPS:
818 raise error("the group number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000819 except ValueError:
Georg Brandl1d472b72013-04-14 11:40:00 +0200820 if not name.isidentifier():
Collin Winterce36ad82007-08-30 01:19:48 +0000821 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000822 try:
823 index = pattern.groupindex[name]
824 except KeyError:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700825 msg = "unknown group name: {0!r}".format(name)
826 raise IndexError(msg)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300827 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000828 elif c == "0":
829 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300830 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000831 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300832 this += sget()
833 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000834 elif c in DIGITS:
835 isoctal = False
836 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300837 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000838 if (c in OCTDIGITS and this[2] in OCTDIGITS and
839 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300840 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000841 isoctal = True
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300842 c = int(this[1:], 8)
843 if c > 0o377:
844 raise error('octal escape value %r outside of '
845 'range 0-0o377' % this)
846 lappend(chr(c))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000847 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300848 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000849 else:
850 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300851 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000852 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000853 pass
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300854 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000855 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300856 lappend(this)
857 if literal:
858 literals.append(''.join(literal))
859 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000860 # The tokenizer implicitly decodes bytes objects as latin-1, we must
861 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300862 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000863 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000864
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000865def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000866 g = match.group
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300867 empty = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000868 groups, literals = template
869 literals = literals[:]
870 try:
871 for index, group in groups:
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300872 literals[index] = g(group) or empty
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000873 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000874 raise error("invalid group reference")
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300875 return empty.join(literals)