blob: b9a1852823dac597bede84ff07b729f958ffb67a [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 *
Serhiy Storchaka70ca0212013-02-16 16:47:47 +020016from _sre import MAXREPEAT
Guido van Rossum7627c0d2000-03-31 14:58:54 +000017
18SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000019REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000020
Raymond Hettinger049ade22005-02-28 19:27:52 +000021DIGITS = set("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000022
Raymond Hettinger049ade22005-02-28 19:27:52 +000023OCTDIGITS = set("01234567")
24HEXDIGITS = set("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000025
Raymond Hettinger049ade22005-02-28 19:27:52 +000026WHITESPACE = set(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000027
Guido van Rossum7627c0d2000-03-31 14:58:54 +000028ESCAPES = {
Fredrik Lundhf2989b22001-02-18 12:05:16 +000029 r"\a": (LITERAL, ord("\a")),
30 r"\b": (LITERAL, ord("\b")),
31 r"\f": (LITERAL, ord("\f")),
32 r"\n": (LITERAL, ord("\n")),
33 r"\r": (LITERAL, ord("\r")),
34 r"\t": (LITERAL, ord("\t")),
35 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000036 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000037}
38
39CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000040 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000041 r"\b": (AT, AT_BOUNDARY),
42 r"\B": (AT, AT_NON_BOUNDARY),
43 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
44 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
45 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
46 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
47 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
48 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000049 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000050}
51
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000052FLAGS = {
Fredrik Lundh436c3d582000-06-29 08:58:44 +000053 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000054 "i": SRE_FLAG_IGNORECASE,
55 "L": SRE_FLAG_LOCALE,
56 "m": SRE_FLAG_MULTILINE,
57 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000058 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000059 # extensions
Antoine Pitroufd036452008-08-19 17:56:33 +000060 "a": SRE_FLAG_ASCII,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000061 "t": SRE_FLAG_TEMPLATE,
62 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000063}
64
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000065class Pattern:
66 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000067 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000068 self.flags = 0
Fredrik Lundhebc37b22000-10-28 19:30:41 +000069 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000070 self.groups = 1
71 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000072 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000073 gid = self.groups
74 self.groups = gid + 1
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +030075 if self.groups > MAXGROUPS:
76 raise error("groups number is too large")
Raymond Hettingerf13eb552002-06-02 00:40:05 +000077 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000078 ogid = self.groupdict.get(name, None)
79 if ogid is not None:
Collin Winterce36ad82007-08-30 01:19:48 +000080 raise error("redefinition of group name %s as group %d; "
81 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000082 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000083 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000084 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000085 def closegroup(self, gid):
86 self.open.remove(gid)
87 def checkgroup(self, gid):
88 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000089
90class SubPattern:
91 # a subpattern, in intermediate form
92 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000093 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000094 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000095 data = []
96 self.data = data
97 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000098 def dump(self, level=0):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +030099 nl = True
Guido van Rossum13257902007-06-07 23:15:56 +0000100 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000101 for op, av in self.data:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300102 print(level*" " + op, end='')
103 if op == IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000104 # member sublanguage
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300105 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000106 for op, a in av:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000107 print((level+1)*" " + op, a)
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300108 elif op == BRANCH:
109 print()
110 for i, a in enumerate(av[1]):
111 if i:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000112 print(level*" " + "or")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300113 a.dump(level+1)
114 elif op == GROUPREF_EXISTS:
115 condgroup, item_yes, item_no = av
116 print('', condgroup)
117 item_yes.dump(level+1)
118 if item_no:
119 print(level*" " + "else")
120 item_no.dump(level+1)
Guido van Rossum13257902007-06-07 23:15:56 +0000121 elif isinstance(av, seqtypes):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300122 nl = False
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000123 for a in av:
124 if isinstance(a, SubPattern):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300125 if not nl:
126 print()
127 a.dump(level+1)
128 nl = True
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000129 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300130 if not nl:
131 print(' ', end='')
132 print(a, end='')
133 nl = False
134 if not nl:
135 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000136 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300137 print('', av)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000138 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000139 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000140 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000141 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000142 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000143 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000144 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000145 if isinstance(index, slice):
146 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000147 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000148 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000149 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000150 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000151 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000152 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000153 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000154 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000155 # determine the width (min, max) for this subpattern
156 if self.width:
157 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000158 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000159 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
160 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000161 for op, av in self.data:
162 if op is BRANCH:
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300163 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000164 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000165 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000166 l, h = av.getwidth()
167 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000168 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000169 lo = lo + i
170 hi = hi + j
171 elif op is CALL:
172 i, j = av.getwidth()
173 lo = lo + i
174 hi = hi + j
175 elif op is SUBPATTERN:
176 i, j = av[1].getwidth()
177 lo = lo + i
178 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000179 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000180 i, j = av[2].getwidth()
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300181 lo = lo + i * av[0]
182 hi = hi + j * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000183 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000184 lo = lo + 1
185 hi = hi + 1
186 elif op == SUCCESS:
187 break
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300188 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000189 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000190
191class Tokenizer:
192 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200193 self.istext = isinstance(string, str)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000194 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000195 self.index = 0
196 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000197 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000198 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000199 self.next = None
200 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000201 char = self.string[self.index:self.index+1]
202 # Special case for the str8, since indexing returns a integer
203 # XXX This is only needed for test_bug_926075 in test_re.py
Antoine Pitrou463badf2012-06-23 13:29:19 +0200204 if char and not self.istext:
Thomas Wouters40a088d2008-03-18 20:19:54 +0000205 char = chr(char[0])
Guido van Rossum75a902d2007-10-19 22:06:24 +0000206 if char == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000207 try:
208 c = self.string[self.index + 1]
209 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000210 raise error("bogus escape (end of line)")
Antoine Pitrou463badf2012-06-23 13:29:19 +0200211 if not self.istext:
Antoine Pitrou22628c42008-07-22 17:53:22 +0000212 c = chr(c)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000213 char = char + c
214 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000215 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000216 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000217 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000218 if skip:
219 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000220 return 1
221 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000222 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000223 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000224 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000225 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200226 def getwhile(self, n, charset):
227 result = ''
228 for _ in range(n):
229 c = self.next
230 if c not in charset:
231 break
232 result += c
233 self.__next()
234 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000235 def tell(self):
236 return self.index, self.next
237 def seek(self, index):
238 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000239
Georg Brandl1d472b72013-04-14 11:40:00 +0200240# The following three functions are not used in this module anymore, but we keep
241# them here (with DeprecationWarnings) for backwards compatibility.
242
Fredrik Lundh4781b072000-06-29 12:38:45 +0000243def isident(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200244 import warnings
245 warnings.warn('sre_parse.isident() will be removed in 3.5',
246 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000247 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
248
249def isdigit(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200250 import warnings
251 warnings.warn('sre_parse.isdigit() will be removed in 3.5',
252 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000253 return "0" <= char <= "9"
254
255def isname(name):
Georg Brandl1d472b72013-04-14 11:40:00 +0200256 import warnings
257 warnings.warn('sre_parse.isname() will be removed in 3.5',
258 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000259 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000260 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000261 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000262 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000263 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000264 return False
265 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000266
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000267def _class_escape(source, escape):
268 # handle escape code inside character class
269 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000270 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000271 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000272 code = CATEGORIES.get(escape)
Ezio Melottife8e6e72013-01-11 08:32:01 +0200273 if code and code[0] == IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000274 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000275 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000276 c = escape[1:2]
277 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000278 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200279 escape += source.getwhile(2, HEXDIGITS)
280 if len(escape) != 4:
281 raise ValueError
282 return LITERAL, int(escape[2:], 16) & 0xff
283 elif c == "u" and source.istext:
284 # unicode escape (exactly four digits)
285 escape += source.getwhile(4, HEXDIGITS)
286 if len(escape) != 6:
287 raise ValueError
288 return LITERAL, int(escape[2:], 16)
289 elif c == "U" and source.istext:
290 # unicode escape (exactly eight digits)
291 escape += source.getwhile(8, HEXDIGITS)
292 if len(escape) != 10:
293 raise ValueError
294 c = int(escape[2:], 16)
295 chr(c) # raise ValueError for invalid code
296 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000297 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000298 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200299 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300300 c = int(escape[1:], 8)
301 if c > 0o377:
302 raise error('octal escape value %r outside of '
303 'range 0-0o377' % escape)
304 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000305 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200306 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000307 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000308 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000309 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000310 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000311 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000312
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000313def _escape(source, escape, state):
314 # handle escape code in expression
315 code = CATEGORIES.get(escape)
316 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000317 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000318 code = ESCAPES.get(escape)
319 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000320 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000321 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000322 c = escape[1:2]
323 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000324 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200325 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000326 if len(escape) != 4:
327 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000328 return LITERAL, int(escape[2:], 16) & 0xff
Antoine Pitrou463badf2012-06-23 13:29:19 +0200329 elif c == "u" and source.istext:
330 # unicode escape (exactly four digits)
331 escape += source.getwhile(4, HEXDIGITS)
332 if len(escape) != 6:
333 raise ValueError
334 return LITERAL, int(escape[2:], 16)
335 elif c == "U" and source.istext:
336 # unicode escape (exactly eight digits)
337 escape += source.getwhile(8, HEXDIGITS)
338 if len(escape) != 10:
339 raise ValueError
340 c = int(escape[2:], 16)
341 chr(c) # raise ValueError for invalid code
342 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000343 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000344 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200345 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300346 return LITERAL, int(escape[1:], 8)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000347 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000348 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000349 if source.next in DIGITS:
350 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000351 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
352 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000353 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000354 escape = escape + source.get()
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300355 c = int(escape[1:], 8)
356 if c > 0o377:
357 raise error('octal escape value %r outside of '
358 'range 0-0o377' % escape)
359 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000360 # not an octal escape, so this is a group reference
361 group = int(escape[1:])
362 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000363 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000364 raise error("cannot refer to open group")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000365 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000366 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000367 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000368 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000369 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000370 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000371 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000372
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000373def _parse_sub(source, state, nested=1):
374 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000375
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000376 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000377 itemsappend = items.append
378 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000379 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000380 itemsappend(_parse(source, state))
381 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000382 continue
383 if not nested:
384 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000385 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000386 break
387 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000388 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000389
390 if len(items) == 1:
391 return items[0]
392
393 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000394 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000395
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000396 # check if all items share a common prefix
397 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000398 prefix = None
399 for item in items:
400 if not item:
401 break
402 if prefix is None:
403 prefix = item[0]
404 elif item[0] != prefix:
405 break
406 else:
407 # all subitems start with a common "prefix".
408 # move it out of the branch
409 for item in items:
410 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000411 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000412 continue # check next one
413 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000414
415 # check if the branch can be replaced by a character set
416 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000417 if len(item) != 1 or item[0][0] != LITERAL:
418 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000419 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000420 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000421 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000422 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000423 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000424 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000425 setappend(item[0])
426 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000427 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000428
429 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000430 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000431
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000432def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000433 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000434 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000435 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000436 if source.match("|"):
Collin Winterce36ad82007-08-30 01:19:48 +0000437 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000438 else:
439 item_no = None
440 if source.next and not source.match(")", 0):
Collin Winterce36ad82007-08-30 01:19:48 +0000441 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000442 subpattern = SubPattern(state)
443 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
444 return subpattern
445
Raymond Hettinger049ade22005-02-28 19:27:52 +0000446_PATTERNENDERS = set("|)")
447_ASSERTCHARS = set("=!<")
448_LOOKBEHINDASSERTCHARS = set("=!")
449_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
450
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000451def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000452 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000453 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000454
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000455 # precompute constants into local variables
456 subpatternappend = subpattern.append
457 sourceget = source.get
458 sourcematch = source.match
459 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000460 PATTERNENDERS = _PATTERNENDERS
461 ASSERTCHARS = _ASSERTCHARS
462 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
463 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000464
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000465 while 1:
466
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000467 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000468 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000469 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000470 if this is None:
471 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000472
Fredrik Lundh90a07912000-06-30 07:50:59 +0000473 if state.flags & SRE_FLAG_VERBOSE:
474 # skip whitespace and comments
475 if this in WHITESPACE:
476 continue
477 if this == "#":
478 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000479 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000480 if this in (None, "\n"):
481 break
482 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000483
Fredrik Lundh90a07912000-06-30 07:50:59 +0000484 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000485 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000486
Fredrik Lundh90a07912000-06-30 07:50:59 +0000487 elif this == "[":
488 # character set
489 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000490 setappend = set.append
491## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000492## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000493 if sourcematch("^"):
494 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000495 # check remaining characters
496 start = set[:]
497 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000498 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000499 if this == "]" and set != start:
500 break
501 elif this and this[0] == "\\":
502 code1 = _class_escape(source, this)
503 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000504 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000505 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000506 raise error("unexpected end of regular expression")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000507 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000508 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000509 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000510 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000511 if code1[0] is IN:
512 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000513 setappend(code1)
514 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000515 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000516 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000517 if this[0] == "\\":
518 code2 = _class_escape(source, this)
519 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000520 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000521 if code1[0] != LITERAL or code2[0] != LITERAL:
Collin Winterce36ad82007-08-30 01:19:48 +0000522 raise error("bad character range")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000523 lo = code1[1]
524 hi = code2[1]
525 if hi < lo:
Collin Winterce36ad82007-08-30 01:19:48 +0000526 raise error("bad character range")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000527 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000528 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000529 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000530 else:
531 if code1[0] is IN:
532 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000533 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000534
Fredrik Lundh770617b2001-01-14 15:06:11 +0000535 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000536 if _len(set)==1 and set[0][0] is LITERAL:
537 subpatternappend(set[0]) # optimization
538 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
539 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000540 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000541 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000542 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000543
Fredrik Lundh90a07912000-06-30 07:50:59 +0000544 elif this and this[0] in REPEAT_CHARS:
545 # repeat previous item
546 if this == "?":
547 min, max = 0, 1
548 elif this == "*":
549 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000550
Fredrik Lundh90a07912000-06-30 07:50:59 +0000551 elif this == "+":
552 min, max = 1, MAXREPEAT
553 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000554 if source.next == "}":
555 subpatternappend((LITERAL, ord(this)))
556 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000557 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000558 min, max = 0, MAXREPEAT
559 lo = hi = ""
560 while source.next in DIGITS:
561 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000562 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000563 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000564 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000565 else:
566 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000567 if not sourcematch("}"):
568 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000569 source.seek(here)
570 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000571 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000572 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200573 if min >= MAXREPEAT:
574 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000575 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000576 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200577 if max >= MAXREPEAT:
578 raise OverflowError("the repetition number is too large")
579 if max < min:
580 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000581 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000582 raise error("not supported")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000583 # figure out which item to repeat
584 if subpattern:
585 item = subpattern[-1:]
586 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000587 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000588 if not item or (_len(item) == 1 and item[0][0] == AT):
Collin Winterce36ad82007-08-30 01:19:48 +0000589 raise error("nothing to repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000590 if item[0][0] in REPEATCODES:
Collin Winterce36ad82007-08-30 01:19:48 +0000591 raise error("multiple repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000592 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000593 subpattern[-1] = (MIN_REPEAT, (min, max, item))
594 else:
595 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000596
Fredrik Lundh90a07912000-06-30 07:50:59 +0000597 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000598 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000599
Fredrik Lundh90a07912000-06-30 07:50:59 +0000600 elif this == "(":
601 group = 1
602 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000603 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000604 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000605 group = 0
606 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000607 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000608 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000609 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000610 # named group: skip forward to end of name
611 name = ""
612 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000613 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000614 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000615 raise error("unterminated name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000616 if char == ">":
617 break
618 name = name + char
619 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200620 if not name:
621 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200622 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400623 raise error("bad character in group name %r" % name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000624 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000625 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000626 name = ""
627 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000628 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000629 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000630 raise error("unterminated name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000631 if char == ")":
632 break
633 name = name + char
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200634 if not name:
635 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200636 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400637 raise error("bad character in backref group name "
638 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000639 gid = state.groupdict.get(name)
640 if gid is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700641 msg = "unknown group name: {0!r}".format(name)
642 raise error(msg)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000643 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000644 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000645 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000646 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000647 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000648 raise error("unexpected end of pattern")
649 raise error("unknown specifier: ?P%s" % char)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000650 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000651 # non-capturing group
652 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000653 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000654 # comment
655 while 1:
656 if source.next is None or source.next == ")":
657 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000658 sourceget()
659 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000660 raise error("unbalanced parenthesis")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000661 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000662 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000663 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000664 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000665 dir = 1
666 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000667 if source.next not in LOOKBEHINDASSERTCHARS:
Collin Winterce36ad82007-08-30 01:19:48 +0000668 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000669 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000670 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000671 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000672 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000673 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000674 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000675 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000676 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000677 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000678 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000679 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000680 # conditional backreference group
681 condname = ""
682 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000683 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000684 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000685 raise error("unterminated name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000686 if char == ")":
687 break
688 condname = condname + char
689 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200690 if not condname:
691 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200692 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000693 condgroup = state.groupdict.get(condname)
694 if condgroup is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700695 msg = "unknown group name: {0!r}".format(condname)
696 raise error(msg)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000697 else:
698 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000699 condgroup = int(condname)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300700 if condgroup < 0:
701 raise ValueError
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000702 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000703 raise error("bad character in group name")
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300704 if not condgroup:
705 raise error("bad group number")
706 if condgroup >= MAXGROUPS:
707 raise error("the group number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000708 else:
709 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000710 if not source.next in FLAGS:
Collin Winterce36ad82007-08-30 01:19:48 +0000711 raise error("unexpected end of pattern")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000712 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000713 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000714 if group:
715 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000716 if group == 2:
717 # anonymous group
718 group = None
719 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000720 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000721 if condgroup:
722 p = _parse_sub_cond(source, state, condgroup)
723 else:
724 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000725 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000726 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000727 if group is not None:
728 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000729 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000730 else:
731 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000732 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000733 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000734 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000735 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000736 break
Collin Winterce36ad82007-08-30 01:19:48 +0000737 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000738
Fredrik Lundh90a07912000-06-30 07:50:59 +0000739 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000740 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000741
Fredrik Lundh90a07912000-06-30 07:50:59 +0000742 elif this == "$":
743 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000744
Fredrik Lundh90a07912000-06-30 07:50:59 +0000745 elif this and this[0] == "\\":
746 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000747 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000748
Fredrik Lundh90a07912000-06-30 07:50:59 +0000749 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000750 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000751
752 return subpattern
753
Antoine Pitroufd036452008-08-19 17:56:33 +0000754def fix_flags(src, flags):
755 # Check and fix flags according to the type of pattern (str or bytes)
756 if isinstance(src, str):
757 if not flags & SRE_FLAG_ASCII:
758 flags |= SRE_FLAG_UNICODE
759 elif flags & SRE_FLAG_UNICODE:
760 raise ValueError("ASCII and UNICODE flags are incompatible")
761 else:
762 if flags & SRE_FLAG_UNICODE:
763 raise ValueError("can't use UNICODE flag with a bytes pattern")
764 return flags
765
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000766def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000767 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000768
769 source = Tokenizer(str)
770
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000771 if pattern is None:
772 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000773 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000774 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000775
776 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000777 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000778
779 tail = source.get()
780 if tail == ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000781 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000782 elif tail:
Collin Winterce36ad82007-08-30 01:19:48 +0000783 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000784
Fredrik Lundh770617b2001-01-14 15:06:11 +0000785 if flags & SRE_FLAG_DEBUG:
786 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000787
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000788 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
789 # the VERBOSE flag was switched on inside the pattern. to be
790 # on the safe side, we'll parse the whole thing again...
791 return parse(str, p.pattern.flags)
792
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000793 return p
794
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000795def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000796 # parse 're' replacement string into list of literals and
797 # group references
798 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000799 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300800 groups = []
801 literals = []
802 literal = []
803 lappend = literal.append
804 def addgroup(index):
805 if literal:
806 literals.append(''.join(literal))
807 del literal[:]
808 groups.append((len(literals), index))
809 literals.append(None)
810 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000811 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000812 if this is None:
813 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300814 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000815 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300816 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000817 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000818 name = ""
819 if s.match("<"):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300820 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000821 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000822 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000823 raise error("unterminated group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000824 if char == ">":
825 break
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300826 name += char
Fredrik Lundh90a07912000-06-30 07:50:59 +0000827 if not name:
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200828 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000829 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000830 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000831 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000832 raise error("negative group number")
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300833 if index >= MAXGROUPS:
834 raise error("the group number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000835 except ValueError:
Georg Brandl1d472b72013-04-14 11:40:00 +0200836 if not name.isidentifier():
Collin Winterce36ad82007-08-30 01:19:48 +0000837 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000838 try:
839 index = pattern.groupindex[name]
840 except KeyError:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700841 msg = "unknown group name: {0!r}".format(name)
842 raise IndexError(msg)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300843 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000844 elif c == "0":
845 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300846 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000847 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300848 this += sget()
849 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000850 elif c in DIGITS:
851 isoctal = False
852 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300853 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000854 if (c in OCTDIGITS and this[2] in OCTDIGITS and
855 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300856 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000857 isoctal = True
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300858 c = int(this[1:], 8)
859 if c > 0o377:
860 raise error('octal escape value %r outside of '
861 'range 0-0o377' % this)
862 lappend(chr(c))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000863 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300864 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000865 else:
866 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300867 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000868 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000869 pass
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300870 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000871 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300872 lappend(this)
873 if literal:
874 literals.append(''.join(literal))
875 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000876 # The tokenizer implicitly decodes bytes objects as latin-1, we must
877 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300878 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000879 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000880
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000881def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000882 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000883 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000884 groups, literals = template
885 literals = literals[:]
886 try:
887 for index, group in groups:
888 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000889 if s is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000890 raise error("unmatched group")
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000891 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000892 raise error("invalid group reference")
Barry Warsaw8bee7612004-08-25 02:22:30 +0000893 return sep.join(literals)