blob: b56d437c3479d04fc1f0351071bad85c9d8d7be1 [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)
298 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000299 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200300 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000301 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000302 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000303 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000304 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000305 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000306
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000307def _escape(source, escape, state):
308 # handle escape code in expression
309 code = CATEGORIES.get(escape)
310 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000311 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000312 code = ESCAPES.get(escape)
313 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000314 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000315 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000316 c = escape[1:2]
317 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000318 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200319 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000320 if len(escape) != 4:
321 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000322 return LITERAL, int(escape[2:], 16) & 0xff
Antoine Pitrou463badf2012-06-23 13:29:19 +0200323 elif c == "u" and source.istext:
324 # unicode escape (exactly four digits)
325 escape += source.getwhile(4, HEXDIGITS)
326 if len(escape) != 6:
327 raise ValueError
328 return LITERAL, int(escape[2:], 16)
329 elif c == "U" and source.istext:
330 # unicode escape (exactly eight digits)
331 escape += source.getwhile(8, HEXDIGITS)
332 if len(escape) != 10:
333 raise ValueError
334 c = int(escape[2:], 16)
335 chr(c) # raise ValueError for invalid code
336 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000337 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000338 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200339 escape += source.getwhile(2, OCTDIGITS)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000340 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000341 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000342 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000343 if source.next in DIGITS:
344 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000345 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
346 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000347 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000348 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000349 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000350 # not an octal escape, so this is a group reference
351 group = int(escape[1:])
352 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000353 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000354 raise error("cannot refer to open group")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000355 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000356 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000357 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000358 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000359 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000360 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000361 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000362
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000363def _parse_sub(source, state, nested=1):
364 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000365
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000366 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000367 itemsappend = items.append
368 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000369 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000370 itemsappend(_parse(source, state))
371 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000372 continue
373 if not nested:
374 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000375 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000376 break
377 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000378 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000379
380 if len(items) == 1:
381 return items[0]
382
383 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000384 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000385
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000386 # check if all items share a common prefix
387 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000388 prefix = None
389 for item in items:
390 if not item:
391 break
392 if prefix is None:
393 prefix = item[0]
394 elif item[0] != prefix:
395 break
396 else:
397 # all subitems start with a common "prefix".
398 # move it out of the branch
399 for item in items:
400 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000401 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000402 continue # check next one
403 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000404
405 # check if the branch can be replaced by a character set
406 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000407 if len(item) != 1 or item[0][0] != LITERAL:
408 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000409 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000410 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000411 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000412 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000413 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000414 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000415 setappend(item[0])
416 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000417 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000418
419 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000420 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000421
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000422def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000423 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000424 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000425 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000426 if source.match("|"):
Collin Winterce36ad82007-08-30 01:19:48 +0000427 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000428 else:
429 item_no = None
430 if source.next and not source.match(")", 0):
Collin Winterce36ad82007-08-30 01:19:48 +0000431 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000432 subpattern = SubPattern(state)
433 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
434 return subpattern
435
Raymond Hettinger049ade22005-02-28 19:27:52 +0000436_PATTERNENDERS = set("|)")
437_ASSERTCHARS = set("=!<")
438_LOOKBEHINDASSERTCHARS = set("=!")
439_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
440
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000441def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000442 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000443 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000444
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000445 # precompute constants into local variables
446 subpatternappend = subpattern.append
447 sourceget = source.get
448 sourcematch = source.match
449 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000450 PATTERNENDERS = _PATTERNENDERS
451 ASSERTCHARS = _ASSERTCHARS
452 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
453 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000454
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000455 while 1:
456
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000457 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000458 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000459 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000460 if this is None:
461 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000462
Fredrik Lundh90a07912000-06-30 07:50:59 +0000463 if state.flags & SRE_FLAG_VERBOSE:
464 # skip whitespace and comments
465 if this in WHITESPACE:
466 continue
467 if this == "#":
468 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000469 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000470 if this in (None, "\n"):
471 break
472 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000473
Fredrik Lundh90a07912000-06-30 07:50:59 +0000474 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000475 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000476
Fredrik Lundh90a07912000-06-30 07:50:59 +0000477 elif this == "[":
478 # character set
479 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000480 setappend = set.append
481## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000482## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000483 if sourcematch("^"):
484 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000485 # check remaining characters
486 start = set[:]
487 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000488 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000489 if this == "]" and set != start:
490 break
491 elif this and this[0] == "\\":
492 code1 = _class_escape(source, this)
493 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000494 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000495 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000496 raise error("unexpected end of regular expression")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000497 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000498 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000499 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000500 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000501 if code1[0] is IN:
502 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000503 setappend(code1)
504 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000505 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000506 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000507 if this[0] == "\\":
508 code2 = _class_escape(source, this)
509 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000510 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000511 if code1[0] != LITERAL or code2[0] != LITERAL:
Collin Winterce36ad82007-08-30 01:19:48 +0000512 raise error("bad character range")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000513 lo = code1[1]
514 hi = code2[1]
515 if hi < lo:
Collin Winterce36ad82007-08-30 01:19:48 +0000516 raise error("bad character range")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000517 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000518 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000519 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000520 else:
521 if code1[0] is IN:
522 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000523 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000524
Fredrik Lundh770617b2001-01-14 15:06:11 +0000525 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000526 if _len(set)==1 and set[0][0] is LITERAL:
527 subpatternappend(set[0]) # optimization
528 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
529 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000530 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000531 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000532 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000533
Fredrik Lundh90a07912000-06-30 07:50:59 +0000534 elif this and this[0] in REPEAT_CHARS:
535 # repeat previous item
536 if this == "?":
537 min, max = 0, 1
538 elif this == "*":
539 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000540
Fredrik Lundh90a07912000-06-30 07:50:59 +0000541 elif this == "+":
542 min, max = 1, MAXREPEAT
543 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000544 if source.next == "}":
545 subpatternappend((LITERAL, ord(this)))
546 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000547 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000548 min, max = 0, MAXREPEAT
549 lo = hi = ""
550 while source.next in DIGITS:
551 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000552 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000553 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000554 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000555 else:
556 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000557 if not sourcematch("}"):
558 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000559 source.seek(here)
560 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000561 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000562 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200563 if min >= MAXREPEAT:
564 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000565 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000566 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200567 if max >= MAXREPEAT:
568 raise OverflowError("the repetition number is too large")
569 if max < min:
570 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000571 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000572 raise error("not supported")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000573 # figure out which item to repeat
574 if subpattern:
575 item = subpattern[-1:]
576 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000577 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000578 if not item or (_len(item) == 1 and item[0][0] == AT):
Collin Winterce36ad82007-08-30 01:19:48 +0000579 raise error("nothing to repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000580 if item[0][0] in REPEATCODES:
Collin Winterce36ad82007-08-30 01:19:48 +0000581 raise error("multiple repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000582 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000583 subpattern[-1] = (MIN_REPEAT, (min, max, item))
584 else:
585 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000586
Fredrik Lundh90a07912000-06-30 07:50:59 +0000587 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000588 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000589
Fredrik Lundh90a07912000-06-30 07:50:59 +0000590 elif this == "(":
591 group = 1
592 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000593 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000594 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000595 group = 0
596 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000597 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000598 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000599 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000600 # named group: skip forward to end of name
601 name = ""
602 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000603 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000604 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000605 raise error("unterminated name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000606 if char == ">":
607 break
608 name = name + char
609 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200610 if not name:
611 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200612 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400613 raise error("bad character in group name %r" % name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000614 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000615 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000616 name = ""
617 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000618 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000619 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000620 raise error("unterminated name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000621 if char == ")":
622 break
623 name = name + char
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200624 if not name:
625 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200626 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400627 raise error("bad character in backref group name "
628 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000629 gid = state.groupdict.get(name)
630 if gid is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700631 msg = "unknown group name: {0!r}".format(name)
632 raise error(msg)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000633 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000634 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000635 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000636 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000637 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000638 raise error("unexpected end of pattern")
639 raise error("unknown specifier: ?P%s" % char)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000640 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000641 # non-capturing group
642 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000643 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000644 # comment
645 while 1:
646 if source.next is None or source.next == ")":
647 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000648 sourceget()
649 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000650 raise error("unbalanced parenthesis")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000651 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000652 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000653 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000654 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000655 dir = 1
656 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000657 if source.next not in LOOKBEHINDASSERTCHARS:
Collin Winterce36ad82007-08-30 01:19:48 +0000658 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000659 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000660 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000661 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000662 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000663 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000664 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000665 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000666 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000667 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000668 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000669 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000670 # conditional backreference group
671 condname = ""
672 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000673 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000674 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000675 raise error("unterminated name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000676 if char == ")":
677 break
678 condname = condname + char
679 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200680 if not condname:
681 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200682 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000683 condgroup = state.groupdict.get(condname)
684 if condgroup is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700685 msg = "unknown group name: {0!r}".format(condname)
686 raise error(msg)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000687 else:
688 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000689 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000690 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000691 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000692 else:
693 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000694 if not source.next in FLAGS:
Collin Winterce36ad82007-08-30 01:19:48 +0000695 raise error("unexpected end of pattern")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000696 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000697 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000698 if group:
699 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000700 if group == 2:
701 # anonymous group
702 group = None
703 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000704 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000705 if condgroup:
706 p = _parse_sub_cond(source, state, condgroup)
707 else:
708 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000709 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000710 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000711 if group is not None:
712 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000713 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000714 else:
715 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000716 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000717 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000718 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000719 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000720 break
Collin Winterce36ad82007-08-30 01:19:48 +0000721 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000722
Fredrik Lundh90a07912000-06-30 07:50:59 +0000723 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000724 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000725
Fredrik Lundh90a07912000-06-30 07:50:59 +0000726 elif this == "$":
727 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000728
Fredrik Lundh90a07912000-06-30 07:50:59 +0000729 elif this and this[0] == "\\":
730 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000731 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000732
Fredrik Lundh90a07912000-06-30 07:50:59 +0000733 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000734 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000735
736 return subpattern
737
Antoine Pitroufd036452008-08-19 17:56:33 +0000738def fix_flags(src, flags):
739 # Check and fix flags according to the type of pattern (str or bytes)
740 if isinstance(src, str):
741 if not flags & SRE_FLAG_ASCII:
742 flags |= SRE_FLAG_UNICODE
743 elif flags & SRE_FLAG_UNICODE:
744 raise ValueError("ASCII and UNICODE flags are incompatible")
745 else:
746 if flags & SRE_FLAG_UNICODE:
747 raise ValueError("can't use UNICODE flag with a bytes pattern")
748 return flags
749
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000750def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000751 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000752
753 source = Tokenizer(str)
754
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000755 if pattern is None:
756 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000757 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000758 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000759
760 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000761 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000762
763 tail = source.get()
764 if tail == ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000765 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000766 elif tail:
Collin Winterce36ad82007-08-30 01:19:48 +0000767 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000768
Fredrik Lundh770617b2001-01-14 15:06:11 +0000769 if flags & SRE_FLAG_DEBUG:
770 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000771
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000772 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
773 # the VERBOSE flag was switched on inside the pattern. to be
774 # on the safe side, we'll parse the whole thing again...
775 return parse(str, p.pattern.flags)
776
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000777 return p
778
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000779def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000780 # parse 're' replacement string into list of literals and
781 # group references
782 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000783 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300784 groups = []
785 literals = []
786 literal = []
787 lappend = literal.append
788 def addgroup(index):
789 if literal:
790 literals.append(''.join(literal))
791 del literal[:]
792 groups.append((len(literals), index))
793 literals.append(None)
794 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000795 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000796 if this is None:
797 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300798 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000799 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300800 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000801 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000802 name = ""
803 if s.match("<"):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300804 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000805 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000806 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000807 raise error("unterminated group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000808 if char == ">":
809 break
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300810 name += char
Fredrik Lundh90a07912000-06-30 07:50:59 +0000811 if not name:
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200812 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000813 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000814 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000815 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000816 raise error("negative group number")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000817 except ValueError:
Georg Brandl1d472b72013-04-14 11:40:00 +0200818 if not name.isidentifier():
Collin Winterce36ad82007-08-30 01:19:48 +0000819 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000820 try:
821 index = pattern.groupindex[name]
822 except KeyError:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700823 msg = "unknown group name: {0!r}".format(name)
824 raise IndexError(msg)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300825 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000826 elif c == "0":
827 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300828 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000829 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300830 this += sget()
831 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000832 elif c in DIGITS:
833 isoctal = False
834 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300835 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000836 if (c in OCTDIGITS and this[2] in OCTDIGITS and
837 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300838 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000839 isoctal = True
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300840 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000841 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300842 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000843 else:
844 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300845 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000846 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000847 pass
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300848 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000849 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300850 lappend(this)
851 if literal:
852 literals.append(''.join(literal))
853 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000854 # The tokenizer implicitly decodes bytes objects as latin-1, we must
855 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300856 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000857 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000858
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000859def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000860 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000861 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000862 groups, literals = template
863 literals = literals[:]
864 try:
865 for index, group in groups:
866 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000867 if s is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000868 raise error("unmatched group")
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000869 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000870 raise error("invalid group reference")
Barry Warsaw8bee7612004-08-25 02:22:30 +0000871 return sep.join(literals)