blob: 7fd145b6233265001c1f2ea423d09e8a20edfac8 [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
Raymond Hettingerf13eb552002-06-02 00:40:05 +000075 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000076 ogid = self.groupdict.get(name, None)
77 if ogid is not None:
Collin Winterce36ad82007-08-30 01:19:48 +000078 raise error("redefinition of group name %s as group %d; "
79 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000080 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000081 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000082 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000083 def closegroup(self, gid):
84 self.open.remove(gid)
85 def checkgroup(self, gid):
86 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000087
88class SubPattern:
89 # a subpattern, in intermediate form
90 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000091 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000092 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000093 data = []
94 self.data = data
95 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000096 def dump(self, level=0):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +030097 nl = True
Guido van Rossum13257902007-06-07 23:15:56 +000098 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000099 for op, av in self.data:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300100 print(level*" " + op, end='')
101 if op == IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000102 # member sublanguage
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300103 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000104 for op, a in av:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000105 print((level+1)*" " + op, a)
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300106 elif op == BRANCH:
107 print()
108 for i, a in enumerate(av[1]):
109 if i:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000110 print(level*" " + "or")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300111 a.dump(level+1)
112 elif op == GROUPREF_EXISTS:
113 condgroup, item_yes, item_no = av
114 print('', condgroup)
115 item_yes.dump(level+1)
116 if item_no:
117 print(level*" " + "else")
118 item_no.dump(level+1)
Guido van Rossum13257902007-06-07 23:15:56 +0000119 elif isinstance(av, seqtypes):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300120 nl = False
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000121 for a in av:
122 if isinstance(a, SubPattern):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300123 if not nl:
124 print()
125 a.dump(level+1)
126 nl = True
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000127 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300128 if not nl:
129 print(' ', end='')
130 print(a, end='')
131 nl = False
132 if not nl:
133 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000134 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300135 print('', av)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000136 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000137 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000138 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000139 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000140 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000141 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000142 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000143 if isinstance(index, slice):
144 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000145 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000146 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000147 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000148 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000149 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000150 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000151 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000152 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000153 # determine the width (min, max) for this subpattern
154 if self.width:
155 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000156 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000157 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
158 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000159 for op, av in self.data:
160 if op is BRANCH:
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300161 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000162 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000163 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000164 l, h = av.getwidth()
165 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000166 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000167 lo = lo + i
168 hi = hi + j
169 elif op is CALL:
170 i, j = av.getwidth()
171 lo = lo + i
172 hi = hi + j
173 elif op is SUBPATTERN:
174 i, j = av[1].getwidth()
175 lo = lo + i
176 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000177 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000178 i, j = av[2].getwidth()
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300179 lo = lo + i * av[0]
180 hi = hi + j * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000181 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000182 lo = lo + 1
183 hi = hi + 1
184 elif op == SUCCESS:
185 break
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300186 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000187 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000188
189class Tokenizer:
190 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200191 self.istext = isinstance(string, str)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000192 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000193 self.index = 0
194 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000195 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000196 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000197 self.next = None
198 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000199 char = self.string[self.index:self.index+1]
200 # Special case for the str8, since indexing returns a integer
201 # XXX This is only needed for test_bug_926075 in test_re.py
Antoine Pitrou463badf2012-06-23 13:29:19 +0200202 if char and not self.istext:
Thomas Wouters40a088d2008-03-18 20:19:54 +0000203 char = chr(char[0])
Guido van Rossum75a902d2007-10-19 22:06:24 +0000204 if char == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000205 try:
206 c = self.string[self.index + 1]
207 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000208 raise error("bogus escape (end of line)")
Antoine Pitrou463badf2012-06-23 13:29:19 +0200209 if not self.istext:
Antoine Pitrou22628c42008-07-22 17:53:22 +0000210 c = chr(c)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000211 char = char + c
212 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000213 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000214 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000215 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000216 if skip:
217 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000218 return 1
219 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000220 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000221 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000222 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000223 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200224 def getwhile(self, n, charset):
225 result = ''
226 for _ in range(n):
227 c = self.next
228 if c not in charset:
229 break
230 result += c
231 self.__next()
232 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000233 def tell(self):
234 return self.index, self.next
235 def seek(self, index):
236 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000237
Georg Brandl1d472b72013-04-14 11:40:00 +0200238# The following three functions are not used in this module anymore, but we keep
239# them here (with DeprecationWarnings) for backwards compatibility.
240
Fredrik Lundh4781b072000-06-29 12:38:45 +0000241def isident(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200242 import warnings
243 warnings.warn('sre_parse.isident() will be removed in 3.5',
244 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000245 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
246
247def isdigit(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200248 import warnings
249 warnings.warn('sre_parse.isdigit() will be removed in 3.5',
250 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000251 return "0" <= char <= "9"
252
253def isname(name):
Georg Brandl1d472b72013-04-14 11:40:00 +0200254 import warnings
255 warnings.warn('sre_parse.isname() will be removed in 3.5',
256 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000257 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000258 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000259 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000260 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000261 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000262 return False
263 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000264
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000265def _class_escape(source, escape):
266 # handle escape code inside character class
267 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000268 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000269 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000270 code = CATEGORIES.get(escape)
Ezio Melottife8e6e72013-01-11 08:32:01 +0200271 if code and code[0] == IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000272 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000273 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000274 c = escape[1:2]
275 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000276 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200277 escape += source.getwhile(2, HEXDIGITS)
278 if len(escape) != 4:
279 raise ValueError
280 return LITERAL, int(escape[2:], 16) & 0xff
281 elif c == "u" and source.istext:
282 # unicode escape (exactly four digits)
283 escape += source.getwhile(4, HEXDIGITS)
284 if len(escape) != 6:
285 raise ValueError
286 return LITERAL, int(escape[2:], 16)
287 elif c == "U" and source.istext:
288 # unicode escape (exactly eight digits)
289 escape += source.getwhile(8, HEXDIGITS)
290 if len(escape) != 10:
291 raise ValueError
292 c = int(escape[2:], 16)
293 chr(c) # raise ValueError for invalid code
294 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000295 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000296 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200297 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300298 c = int(escape[1:], 8)
299 if c > 0o377:
300 raise error('octal escape value %r outside of '
301 'range 0-0o377' % escape)
302 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000303 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200304 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000305 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000306 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000307 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000308 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000309 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000310
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000311def _escape(source, escape, state):
312 # handle escape code in expression
313 code = CATEGORIES.get(escape)
314 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000315 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000316 code = ESCAPES.get(escape)
317 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000318 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000319 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000320 c = escape[1:2]
321 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000322 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200323 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000324 if len(escape) != 4:
325 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000326 return LITERAL, int(escape[2:], 16) & 0xff
Antoine Pitrou463badf2012-06-23 13:29:19 +0200327 elif c == "u" and source.istext:
328 # unicode escape (exactly four digits)
329 escape += source.getwhile(4, HEXDIGITS)
330 if len(escape) != 6:
331 raise ValueError
332 return LITERAL, int(escape[2:], 16)
333 elif c == "U" and source.istext:
334 # unicode escape (exactly eight digits)
335 escape += source.getwhile(8, HEXDIGITS)
336 if len(escape) != 10:
337 raise ValueError
338 c = int(escape[2:], 16)
339 chr(c) # raise ValueError for invalid code
340 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000341 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000342 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200343 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300344 return LITERAL, int(escape[1:], 8)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000345 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000346 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000347 if source.next in DIGITS:
348 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000349 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
350 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000351 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000352 escape = escape + source.get()
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300353 c = int(escape[1:], 8)
354 if c > 0o377:
355 raise error('octal escape value %r outside of '
356 'range 0-0o377' % escape)
357 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000358 # not an octal escape, so this is a group reference
359 group = int(escape[1:])
360 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000361 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000362 raise error("cannot refer to open group")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000363 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000364 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000365 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000366 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000367 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000368 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000369 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000370
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000371def _parse_sub(source, state, nested=1):
372 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000373
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000374 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000375 itemsappend = items.append
376 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000377 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000378 itemsappend(_parse(source, state))
379 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000380 continue
381 if not nested:
382 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000383 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000384 break
385 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000386 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000387
388 if len(items) == 1:
389 return items[0]
390
391 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000392 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000393
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000394 # check if all items share a common prefix
395 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000396 prefix = None
397 for item in items:
398 if not item:
399 break
400 if prefix is None:
401 prefix = item[0]
402 elif item[0] != prefix:
403 break
404 else:
405 # all subitems start with a common "prefix".
406 # move it out of the branch
407 for item in items:
408 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000409 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000410 continue # check next one
411 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000412
413 # check if the branch can be replaced by a character set
414 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000415 if len(item) != 1 or item[0][0] != LITERAL:
416 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000417 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000418 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000419 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000420 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000421 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000422 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000423 setappend(item[0])
424 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000425 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000426
427 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000428 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000429
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000430def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000431 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000432 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000433 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000434 if source.match("|"):
Collin Winterce36ad82007-08-30 01:19:48 +0000435 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000436 else:
437 item_no = None
438 if source.next and not source.match(")", 0):
Collin Winterce36ad82007-08-30 01:19:48 +0000439 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000440 subpattern = SubPattern(state)
441 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
442 return subpattern
443
Raymond Hettinger049ade22005-02-28 19:27:52 +0000444_PATTERNENDERS = set("|)")
445_ASSERTCHARS = set("=!<")
446_LOOKBEHINDASSERTCHARS = set("=!")
447_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
448
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000449def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000450 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000451 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000452
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000453 # precompute constants into local variables
454 subpatternappend = subpattern.append
455 sourceget = source.get
456 sourcematch = source.match
457 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000458 PATTERNENDERS = _PATTERNENDERS
459 ASSERTCHARS = _ASSERTCHARS
460 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
461 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000462
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000463 while 1:
464
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000465 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000466 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000467 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000468 if this is None:
469 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000470
Fredrik Lundh90a07912000-06-30 07:50:59 +0000471 if state.flags & SRE_FLAG_VERBOSE:
472 # skip whitespace and comments
473 if this in WHITESPACE:
474 continue
475 if this == "#":
476 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000477 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000478 if this in (None, "\n"):
479 break
480 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000481
Fredrik Lundh90a07912000-06-30 07:50:59 +0000482 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000483 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000484
Fredrik Lundh90a07912000-06-30 07:50:59 +0000485 elif this == "[":
486 # character set
487 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000488 setappend = set.append
489## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000490## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000491 if sourcematch("^"):
492 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000493 # check remaining characters
494 start = set[:]
495 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000496 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000497 if this == "]" and set != start:
498 break
499 elif this and this[0] == "\\":
500 code1 = _class_escape(source, this)
501 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000502 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000503 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000504 raise error("unexpected end of regular expression")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000505 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000506 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000507 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000508 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000509 if code1[0] is IN:
510 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000511 setappend(code1)
512 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000513 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000514 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000515 if this[0] == "\\":
516 code2 = _class_escape(source, this)
517 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000518 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000519 if code1[0] != LITERAL or code2[0] != LITERAL:
Collin Winterce36ad82007-08-30 01:19:48 +0000520 raise error("bad character range")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000521 lo = code1[1]
522 hi = code2[1]
523 if hi < lo:
Collin Winterce36ad82007-08-30 01:19:48 +0000524 raise error("bad character range")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000525 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000526 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000527 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000528 else:
529 if code1[0] is IN:
530 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000531 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000532
Fredrik Lundh770617b2001-01-14 15:06:11 +0000533 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000534 if _len(set)==1 and set[0][0] is LITERAL:
535 subpatternappend(set[0]) # optimization
536 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
537 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000538 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000539 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000540 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000541
Fredrik Lundh90a07912000-06-30 07:50:59 +0000542 elif this and this[0] in REPEAT_CHARS:
543 # repeat previous item
544 if this == "?":
545 min, max = 0, 1
546 elif this == "*":
547 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000548
Fredrik Lundh90a07912000-06-30 07:50:59 +0000549 elif this == "+":
550 min, max = 1, MAXREPEAT
551 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000552 if source.next == "}":
553 subpatternappend((LITERAL, ord(this)))
554 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000555 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000556 min, max = 0, MAXREPEAT
557 lo = hi = ""
558 while source.next in DIGITS:
559 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000560 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000561 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000562 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000563 else:
564 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000565 if not sourcematch("}"):
566 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000567 source.seek(here)
568 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000569 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000570 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200571 if min >= MAXREPEAT:
572 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000573 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000574 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200575 if max >= MAXREPEAT:
576 raise OverflowError("the repetition number is too large")
577 if max < min:
578 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000579 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000580 raise error("not supported")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000581 # figure out which item to repeat
582 if subpattern:
583 item = subpattern[-1:]
584 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000585 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000586 if not item or (_len(item) == 1 and item[0][0] == AT):
Collin Winterce36ad82007-08-30 01:19:48 +0000587 raise error("nothing to repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000588 if item[0][0] in REPEATCODES:
Collin Winterce36ad82007-08-30 01:19:48 +0000589 raise error("multiple repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000590 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000591 subpattern[-1] = (MIN_REPEAT, (min, max, item))
592 else:
593 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000594
Fredrik Lundh90a07912000-06-30 07:50:59 +0000595 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000596 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000597
Fredrik Lundh90a07912000-06-30 07:50:59 +0000598 elif this == "(":
599 group = 1
600 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000601 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000602 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000603 group = 0
604 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000605 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000606 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000607 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000608 # named group: skip forward to end of name
609 name = ""
610 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000611 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000612 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000613 raise error("unterminated name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000614 if char == ">":
615 break
616 name = name + char
617 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200618 if not name:
619 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200620 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400621 raise error("bad character in group name %r" % name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000622 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000623 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000624 name = ""
625 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000626 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000627 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000628 raise error("unterminated name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000629 if char == ")":
630 break
631 name = name + char
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200632 if not name:
633 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200634 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400635 raise error("bad character in backref group name "
636 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000637 gid = state.groupdict.get(name)
638 if gid is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700639 msg = "unknown group name: {0!r}".format(name)
640 raise error(msg)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000641 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000642 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000643 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000644 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000645 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000646 raise error("unexpected end of pattern")
647 raise error("unknown specifier: ?P%s" % char)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000648 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000649 # non-capturing group
650 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000651 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000652 # comment
653 while 1:
654 if source.next is None or source.next == ")":
655 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000656 sourceget()
657 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000658 raise error("unbalanced parenthesis")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000659 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000660 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000661 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000662 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000663 dir = 1
664 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000665 if source.next not in LOOKBEHINDASSERTCHARS:
Collin Winterce36ad82007-08-30 01:19:48 +0000666 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000667 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000668 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000669 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000670 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000671 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000672 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000673 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000674 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000675 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000676 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000677 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000678 # conditional backreference group
679 condname = ""
680 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000681 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000682 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000683 raise error("unterminated name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000684 if char == ")":
685 break
686 condname = condname + char
687 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200688 if not condname:
689 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200690 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000691 condgroup = state.groupdict.get(condname)
692 if condgroup is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700693 msg = "unknown group name: {0!r}".format(condname)
694 raise error(msg)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000695 else:
696 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000697 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000698 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000699 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000700 else:
701 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000702 if not source.next in FLAGS:
Collin Winterce36ad82007-08-30 01:19:48 +0000703 raise error("unexpected end of pattern")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000704 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000705 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000706 if group:
707 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000708 if group == 2:
709 # anonymous group
710 group = None
711 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000712 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000713 if condgroup:
714 p = _parse_sub_cond(source, state, condgroup)
715 else:
716 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000717 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000718 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000719 if group is not None:
720 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000721 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000722 else:
723 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000724 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000725 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000726 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000727 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000728 break
Collin Winterce36ad82007-08-30 01:19:48 +0000729 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000730
Fredrik Lundh90a07912000-06-30 07:50:59 +0000731 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000732 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000733
Fredrik Lundh90a07912000-06-30 07:50:59 +0000734 elif this == "$":
735 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000736
Fredrik Lundh90a07912000-06-30 07:50:59 +0000737 elif this and this[0] == "\\":
738 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000739 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000740
Fredrik Lundh90a07912000-06-30 07:50:59 +0000741 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000742 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000743
744 return subpattern
745
Antoine Pitroufd036452008-08-19 17:56:33 +0000746def fix_flags(src, flags):
747 # Check and fix flags according to the type of pattern (str or bytes)
748 if isinstance(src, str):
749 if not flags & SRE_FLAG_ASCII:
750 flags |= SRE_FLAG_UNICODE
751 elif flags & SRE_FLAG_UNICODE:
752 raise ValueError("ASCII and UNICODE flags are incompatible")
753 else:
754 if flags & SRE_FLAG_UNICODE:
755 raise ValueError("can't use UNICODE flag with a bytes pattern")
756 return flags
757
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000758def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000759 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000760
761 source = Tokenizer(str)
762
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000763 if pattern is None:
764 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000765 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000766 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000767
768 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000769 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000770
771 tail = source.get()
772 if tail == ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000773 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000774 elif tail:
Collin Winterce36ad82007-08-30 01:19:48 +0000775 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000776
Fredrik Lundh770617b2001-01-14 15:06:11 +0000777 if flags & SRE_FLAG_DEBUG:
778 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000779
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000780 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
781 # the VERBOSE flag was switched on inside the pattern. to be
782 # on the safe side, we'll parse the whole thing again...
783 return parse(str, p.pattern.flags)
784
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000785 return p
786
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000787def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000788 # parse 're' replacement string into list of literals and
789 # group references
790 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000791 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300792 groups = []
793 literals = []
794 literal = []
795 lappend = literal.append
796 def addgroup(index):
797 if literal:
798 literals.append(''.join(literal))
799 del literal[:]
800 groups.append((len(literals), index))
801 literals.append(None)
802 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000803 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000804 if this is None:
805 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300806 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000807 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300808 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000809 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000810 name = ""
811 if s.match("<"):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300812 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000813 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000814 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000815 raise error("unterminated group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000816 if char == ">":
817 break
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300818 name += char
Fredrik Lundh90a07912000-06-30 07:50:59 +0000819 if not name:
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200820 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000821 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000822 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000823 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000824 raise error("negative group number")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000825 except ValueError:
Georg Brandl1d472b72013-04-14 11:40:00 +0200826 if not name.isidentifier():
Collin Winterce36ad82007-08-30 01:19:48 +0000827 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000828 try:
829 index = pattern.groupindex[name]
830 except KeyError:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700831 msg = "unknown group name: {0!r}".format(name)
832 raise IndexError(msg)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300833 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000834 elif c == "0":
835 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300836 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000837 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300838 this += sget()
839 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000840 elif c in DIGITS:
841 isoctal = False
842 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300843 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000844 if (c in OCTDIGITS and this[2] in OCTDIGITS and
845 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300846 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000847 isoctal = True
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300848 c = int(this[1:], 8)
849 if c > 0o377:
850 raise error('octal escape value %r outside of '
851 'range 0-0o377' % this)
852 lappend(chr(c))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000853 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300854 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000855 else:
856 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300857 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000858 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000859 pass
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300860 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000861 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300862 lappend(this)
863 if literal:
864 literals.append(''.join(literal))
865 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000866 # The tokenizer implicitly decodes bytes objects as latin-1, we must
867 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300868 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000869 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000870
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000871def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000872 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000873 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000874 groups, literals = template
875 literals = literals[:]
876 try:
877 for index, group in groups:
878 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000879 if s is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000880 raise error("unmatched group")
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000881 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000882 raise error("invalid group reference")
Barry Warsaw8bee7612004-08-25 02:22:30 +0000883 return sep.join(literals)