blob: 68efece3062767bb68bfc864bfddf4a643cbc552 [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
Serhiy Storchakae2ccf562014-10-10 11:14:49 +030021DIGITS = frozenset("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000022
Serhiy Storchakae2ccf562014-10-10 11:14:49 +030023OCTDIGITS = frozenset("01234567")
24HEXDIGITS = frozenset("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000025
Serhiy Storchakae2ccf562014-10-10 11:14:49 +030026WHITESPACE = frozenset(" \t\n\r\v\f")
27
28_REPEATCODES = frozenset((MIN_REPEAT, MAX_REPEAT))
29_UNITCODES = frozenset((ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000030
Guido van Rossum7627c0d2000-03-31 14:58:54 +000031ESCAPES = {
Fredrik Lundhf2989b22001-02-18 12:05:16 +000032 r"\a": (LITERAL, ord("\a")),
33 r"\b": (LITERAL, ord("\b")),
34 r"\f": (LITERAL, ord("\f")),
35 r"\n": (LITERAL, ord("\n")),
36 r"\r": (LITERAL, ord("\r")),
37 r"\t": (LITERAL, ord("\t")),
38 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000039 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000040}
41
42CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000043 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000044 r"\b": (AT, AT_BOUNDARY),
45 r"\B": (AT, AT_NON_BOUNDARY),
46 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
47 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
48 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
49 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
50 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
51 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000052 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000053}
54
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000055FLAGS = {
Fredrik Lundh436c3d582000-06-29 08:58:44 +000056 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000057 "i": SRE_FLAG_IGNORECASE,
58 "L": SRE_FLAG_LOCALE,
59 "m": SRE_FLAG_MULTILINE,
60 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000061 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000062 # extensions
Antoine Pitroufd036452008-08-19 17:56:33 +000063 "a": SRE_FLAG_ASCII,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000064 "t": SRE_FLAG_TEMPLATE,
65 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000066}
67
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000068class Pattern:
69 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000070 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000071 self.flags = 0
Fredrik Lundhebc37b22000-10-28 19:30:41 +000072 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000073 self.groups = 1
74 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000075 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000076 gid = self.groups
77 self.groups = gid + 1
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +030078 if self.groups > MAXGROUPS:
79 raise error("groups number is too large")
Raymond Hettingerf13eb552002-06-02 00:40:05 +000080 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000081 ogid = self.groupdict.get(name, None)
82 if ogid is not None:
Collin Winterce36ad82007-08-30 01:19:48 +000083 raise error("redefinition of group name %s as group %d; "
84 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000085 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000086 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000087 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000088 def closegroup(self, gid):
89 self.open.remove(gid)
90 def checkgroup(self, gid):
91 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000092
93class SubPattern:
94 # a subpattern, in intermediate form
95 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000096 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000097 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000098 data = []
99 self.data = data
100 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000101 def dump(self, level=0):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300102 nl = True
Guido van Rossum13257902007-06-07 23:15:56 +0000103 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000104 for op, av in self.data:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300105 print(level*" " + op, end='')
106 if op == IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000107 # member sublanguage
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300108 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000109 for op, a in av:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000110 print((level+1)*" " + op, a)
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300111 elif op == BRANCH:
112 print()
113 for i, a in enumerate(av[1]):
114 if i:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000115 print(level*" " + "or")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300116 a.dump(level+1)
117 elif op == GROUPREF_EXISTS:
118 condgroup, item_yes, item_no = av
119 print('', condgroup)
120 item_yes.dump(level+1)
121 if item_no:
122 print(level*" " + "else")
123 item_no.dump(level+1)
Guido van Rossum13257902007-06-07 23:15:56 +0000124 elif isinstance(av, seqtypes):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300125 nl = False
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000126 for a in av:
127 if isinstance(a, SubPattern):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300128 if not nl:
129 print()
130 a.dump(level+1)
131 nl = True
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000132 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300133 if not nl:
134 print(' ', end='')
135 print(a, end='')
136 nl = False
137 if not nl:
138 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000139 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300140 print('', av)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000141 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000142 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000143 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000144 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000145 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000146 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000147 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000148 if isinstance(index, slice):
149 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000150 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000151 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000152 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000153 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000154 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000155 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000156 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000157 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000158 # determine the width (min, max) for this subpattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300159 if self.width is not None:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000160 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000161 lo = hi = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000162 for op, av in self.data:
163 if op is BRANCH:
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300164 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000165 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000166 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000167 l, h = av.getwidth()
168 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000169 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000170 lo = lo + i
171 hi = hi + j
172 elif op is CALL:
173 i, j = av.getwidth()
174 lo = lo + i
175 hi = hi + j
176 elif op is SUBPATTERN:
177 i, j = av[1].getwidth()
178 lo = lo + i
179 hi = hi + j
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300180 elif op in _REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000181 i, j = av[2].getwidth()
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300182 lo = lo + i * av[0]
183 hi = hi + j * av[1]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300184 elif op in _UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000185 lo = lo + 1
186 hi = hi + 1
187 elif op == SUCCESS:
188 break
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300189 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000190 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000191
192class Tokenizer:
193 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200194 self.istext = isinstance(string, str)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300195 if not self.istext:
196 string = str(string, 'latin1')
Fredrik Lundh90a07912000-06-30 07:50:59 +0000197 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000198 self.index = 0
199 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000200 def __next(self):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300201 index = self.index
202 try:
203 char = self.string[index]
204 except IndexError:
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000205 self.next = None
206 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000207 if char == "\\":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300208 index += 1
Fredrik Lundh90a07912000-06-30 07:50:59 +0000209 try:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300210 char += self.string[index]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000211 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000212 raise error("bogus escape (end of line)")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300213 self.index = index + 1
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000214 self.next = char
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300215 def match(self, char):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000216 if char == self.next:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300217 self.__next()
218 return True
219 return False
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
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300233 def getuntil(self, terminator):
234 result = ''
235 while True:
236 c = self.next
237 self.__next()
238 if c is None:
239 raise error("unterminated name")
240 if c == terminator:
241 break
242 result += c
243 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000244 def tell(self):
245 return self.index, self.next
246 def seek(self, index):
247 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000248
Georg Brandl1d472b72013-04-14 11:40:00 +0200249# The following three functions are not used in this module anymore, but we keep
250# them here (with DeprecationWarnings) for backwards compatibility.
251
Fredrik Lundh4781b072000-06-29 12:38:45 +0000252def isident(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200253 import warnings
254 warnings.warn('sre_parse.isident() will be removed in 3.5',
255 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000256 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
257
258def isdigit(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200259 import warnings
260 warnings.warn('sre_parse.isdigit() will be removed in 3.5',
261 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000262 return "0" <= char <= "9"
263
264def isname(name):
Georg Brandl1d472b72013-04-14 11:40:00 +0200265 import warnings
266 warnings.warn('sre_parse.isname() will be removed in 3.5',
267 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000268 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000269 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000270 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000271 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000272 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000273 return False
274 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000275
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000276def _class_escape(source, escape):
277 # handle escape code inside character class
278 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000279 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000280 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000281 code = CATEGORIES.get(escape)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300282 if code and code[0] is IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000283 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000284 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000285 c = escape[1:2]
286 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000287 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200288 escape += source.getwhile(2, HEXDIGITS)
289 if len(escape) != 4:
290 raise ValueError
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300291 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200292 elif c == "u" and source.istext:
293 # unicode escape (exactly four digits)
294 escape += source.getwhile(4, HEXDIGITS)
295 if len(escape) != 6:
296 raise ValueError
297 return LITERAL, int(escape[2:], 16)
298 elif c == "U" and source.istext:
299 # unicode escape (exactly eight digits)
300 escape += source.getwhile(8, HEXDIGITS)
301 if len(escape) != 10:
302 raise ValueError
303 c = int(escape[2:], 16)
304 chr(c) # raise ValueError for invalid code
305 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000306 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000307 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200308 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300309 c = int(escape[1:], 8)
310 if c > 0o377:
311 raise error('octal escape value %r outside of '
312 'range 0-0o377' % escape)
313 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000314 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200315 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000316 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000317 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000318 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000319 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000320 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000321
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000322def _escape(source, escape, state):
323 # handle escape code in expression
324 code = CATEGORIES.get(escape)
325 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000326 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000327 code = ESCAPES.get(escape)
328 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000329 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000330 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000331 c = escape[1:2]
332 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000333 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200334 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000335 if len(escape) != 4:
336 raise ValueError
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300337 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200338 elif c == "u" and source.istext:
339 # unicode escape (exactly four digits)
340 escape += source.getwhile(4, HEXDIGITS)
341 if len(escape) != 6:
342 raise ValueError
343 return LITERAL, int(escape[2:], 16)
344 elif c == "U" and source.istext:
345 # unicode escape (exactly eight digits)
346 escape += source.getwhile(8, HEXDIGITS)
347 if len(escape) != 10:
348 raise ValueError
349 c = int(escape[2:], 16)
350 chr(c) # raise ValueError for invalid code
351 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000352 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000353 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200354 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300355 return LITERAL, int(escape[1:], 8)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000356 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000357 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000358 if source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300359 escape += source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000360 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
361 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000362 # got three octal digits; this is an octal escape
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300363 escape += source.get()
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300364 c = int(escape[1:], 8)
365 if c > 0o377:
366 raise error('octal escape value %r outside of '
367 'range 0-0o377' % escape)
368 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000369 # not an octal escape, so this is a group reference
370 group = int(escape[1:])
371 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000372 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000373 raise error("cannot refer to open group")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000374 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000375 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000376 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000377 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000378 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000379 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000380 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000381
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300382def _parse_sub(source, state, nested=True):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000383 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000384
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000385 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000386 itemsappend = items.append
387 sourcematch = source.match
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300388 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000389 itemsappend(_parse(source, state))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300390 if not sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000391 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300392 if nested and source.next is not None and source.next != ")":
393 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000394
395 if len(items) == 1:
396 return items[0]
397
398 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000399 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000400
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000401 # check if all items share a common prefix
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300402 while True:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000403 prefix = None
404 for item in items:
405 if not item:
406 break
407 if prefix is None:
408 prefix = item[0]
409 elif item[0] != prefix:
410 break
411 else:
412 # all subitems start with a common "prefix".
413 # move it out of the branch
414 for item in items:
415 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000416 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000417 continue # check next one
418 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000419
420 # check if the branch can be replaced by a character set
421 for item in items:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300422 if len(item) != 1 or item[0][0] is not LITERAL:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000423 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000424 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000425 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000426 # branch (the compiler may optimize this even more)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300427 subpatternappend((IN, [item[0] for item in items]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000428 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000429
430 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000431 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000432
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000433def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000434 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000435 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000436 item_no = _parse(source, state)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300437 if source.next == "|":
Collin Winterce36ad82007-08-30 01:19:48 +0000438 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000439 else:
440 item_no = None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300441 if source.next is not None and source.next != ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000442 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000443 subpattern = SubPattern(state)
444 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
445 return subpattern
446
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000447def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000448 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000449 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000450
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000451 # precompute constants into local variables
452 subpatternappend = subpattern.append
453 sourceget = source.get
454 sourcematch = source.match
455 _len = len
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300456 _ord = ord
457 verbose = state.flags & SRE_FLAG_VERBOSE
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000458
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300459 while True:
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000460
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300461 this = source.next
Fredrik Lundh90a07912000-06-30 07:50:59 +0000462 if this is None:
463 break # end of pattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300464 if this in "|)":
465 break # end of subpattern
466 sourceget()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000467
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300468 if verbose:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000469 # skip whitespace and comments
470 if this in WHITESPACE:
471 continue
472 if this == "#":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300473 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000474 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300475 if this is None or this == "\n":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000476 break
477 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000478
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300479 if this[0] == "\\":
480 code = _escape(source, this, state)
481 subpatternappend(code)
482
483 elif this not in SPECIAL_CHARS:
484 subpatternappend((LITERAL, _ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000485
Fredrik Lundh90a07912000-06-30 07:50:59 +0000486 elif this == "[":
487 # character set
488 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000489 setappend = set.append
490## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000491## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000492 if sourcematch("^"):
493 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000494 # check remaining characters
495 start = set[:]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300496 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000497 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300498 if this is None:
499 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000500 if this == "]" and set != start:
501 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300502 elif this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000503 code1 = _class_escape(source, this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000504 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300505 code1 = LITERAL, _ord(this)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000506 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000507 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000508 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300509 if this is None:
510 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000511 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000512 if code1[0] is IN:
513 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000514 setappend(code1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300515 setappend((LITERAL, _ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000516 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300517 if this[0] == "\\":
518 code2 = _class_escape(source, this)
Guido van Rossum41c99e72003-04-14 17:59:34 +0000519 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300520 code2 = LITERAL, _ord(this)
521 if code1[0] != LITERAL or code2[0] != LITERAL:
522 raise error("bad character range")
523 lo = code1[1]
524 hi = code2[1]
525 if hi < lo:
526 raise error("bad character range")
527 setappend((RANGE, (lo, hi)))
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
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300542 elif this in REPEAT_CHARS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000543 # 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 == "}":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300553 subpatternappend((LITERAL, _ord(this)))
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000554 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:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300559 lo += sourceget()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000560 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000561 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300562 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("}"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300566 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")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300588 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
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300605 char = sourceget()
606 if char is None:
607 raise error("unexpected end of pattern")
608 if char == "P":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000609 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000610 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000611 # named group: skip forward to end of name
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300612 name = source.getuntil(">")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000613 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200614 if not name:
615 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200616 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400617 raise error("bad character in group name %r" % name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000618 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000619 # named backreference
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300620 name = source.getuntil(")")
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200621 if not name:
622 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200623 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400624 raise error("bad character in backref group name "
625 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000626 gid = state.groupdict.get(name)
627 if gid is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700628 msg = "unknown group name: {0!r}".format(name)
629 raise error(msg)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000630 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000631 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000632 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000633 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000634 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000635 raise error("unexpected end of pattern")
636 raise error("unknown specifier: ?P%s" % char)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300637 elif char == ":":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000638 # non-capturing group
639 group = 2
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300640 elif char == "#":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000641 # comment
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300642 while True:
643 if source.next is None:
644 raise error("unbalanced parenthesis")
645 if sourceget() == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000646 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000647 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300648 elif char in "=!<":
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000649 # lookahead assertions
Fredrik Lundh6f013982000-07-03 18:44:21 +0000650 dir = 1
651 if char == "<":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300652 char = sourceget()
653 if char is None or char not in "=!":
Collin Winterce36ad82007-08-30 01:19:48 +0000654 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000655 dir = -1 # lookbehind
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000656 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000657 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000658 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000659 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000660 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000661 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000662 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000663 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300664 elif char == "(":
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000665 # conditional backreference group
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300666 condname = source.getuntil(")")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000667 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200668 if not condname:
669 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200670 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000671 condgroup = state.groupdict.get(condname)
672 if condgroup is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700673 msg = "unknown group name: {0!r}".format(condname)
674 raise error(msg)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000675 else:
676 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000677 condgroup = int(condname)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300678 if condgroup < 0:
679 raise ValueError
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000680 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000681 raise error("bad character in group name")
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300682 if not condgroup:
683 raise error("bad group number")
684 if condgroup >= MAXGROUPS:
685 raise error("the group number is too large")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300686 elif char in FLAGS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000687 # flags
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300688 state.flags |= FLAGS[char]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000689 while source.next in FLAGS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300690 state.flags |= FLAGS[sourceget()]
691 verbose = state.flags & SRE_FLAG_VERBOSE
692 else:
693 raise error("unexpected end of pattern " + char)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000694 if group:
695 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000696 if group == 2:
697 # anonymous group
698 group = None
699 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000700 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000701 if condgroup:
702 p = _parse_sub_cond(source, state, condgroup)
703 else:
704 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000705 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000706 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000707 if group is not None:
708 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000709 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000710 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300711 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000712 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000713 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000714 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000715 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000716 break
Collin Winterce36ad82007-08-30 01:19:48 +0000717 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000718
Fredrik Lundh90a07912000-06-30 07:50:59 +0000719 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000720 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000721
Fredrik Lundh90a07912000-06-30 07:50:59 +0000722 elif this == "$":
723 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000724
Fredrik Lundh90a07912000-06-30 07:50:59 +0000725 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000726 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000727
728 return subpattern
729
Antoine Pitroufd036452008-08-19 17:56:33 +0000730def fix_flags(src, flags):
731 # Check and fix flags according to the type of pattern (str or bytes)
732 if isinstance(src, str):
733 if not flags & SRE_FLAG_ASCII:
734 flags |= SRE_FLAG_UNICODE
735 elif flags & SRE_FLAG_UNICODE:
736 raise ValueError("ASCII and UNICODE flags are incompatible")
737 else:
738 if flags & SRE_FLAG_UNICODE:
739 raise ValueError("can't use UNICODE flag with a bytes pattern")
740 return flags
741
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000742def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000743 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000744
745 source = Tokenizer(str)
746
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000747 if pattern is None:
748 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000749 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000750 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000751
752 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000753 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000754
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300755 if source.next is not None:
756 if source.next == ")":
757 raise error("unbalanced parenthesis")
758 else:
759 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000760
Fredrik Lundh770617b2001-01-14 15:06:11 +0000761 if flags & SRE_FLAG_DEBUG:
762 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000763
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000764 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
765 # the VERBOSE flag was switched on inside the pattern. to be
766 # on the safe side, we'll parse the whole thing again...
767 return parse(str, p.pattern.flags)
768
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000769 return p
770
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000771def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000772 # parse 're' replacement string into list of literals and
773 # group references
774 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000775 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300776 groups = []
777 literals = []
778 literal = []
779 lappend = literal.append
780 def addgroup(index):
781 if literal:
782 literals.append(''.join(literal))
783 del literal[:]
784 groups.append((len(literals), index))
785 literals.append(None)
786 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000787 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000788 if this is None:
789 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300790 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000791 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300792 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000793 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000794 name = ""
795 if s.match("<"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300796 name = s.getuntil(">")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000797 if not name:
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200798 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000799 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000800 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000801 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000802 raise error("negative group number")
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300803 if index >= MAXGROUPS:
804 raise error("the group number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000805 except ValueError:
Georg Brandl1d472b72013-04-14 11:40:00 +0200806 if not name.isidentifier():
Collin Winterce36ad82007-08-30 01:19:48 +0000807 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000808 try:
809 index = pattern.groupindex[name]
810 except KeyError:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700811 msg = "unknown group name: {0!r}".format(name)
812 raise IndexError(msg)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300813 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000814 elif c == "0":
815 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300816 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000817 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300818 this += sget()
819 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000820 elif c in DIGITS:
821 isoctal = False
822 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300823 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000824 if (c in OCTDIGITS and this[2] in OCTDIGITS and
825 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300826 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000827 isoctal = True
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300828 c = int(this[1:], 8)
829 if c > 0o377:
830 raise error('octal escape value %r outside of '
831 'range 0-0o377' % this)
832 lappend(chr(c))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000833 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300834 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000835 else:
836 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300837 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000838 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000839 pass
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300840 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000841 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300842 lappend(this)
843 if literal:
844 literals.append(''.join(literal))
845 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000846 # The tokenizer implicitly decodes bytes objects as latin-1, we must
847 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300848 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000849 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000850
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000851def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000852 g = match.group
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300853 empty = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000854 groups, literals = template
855 literals = literals[:]
856 try:
857 for index, group in groups:
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300858 literals[index] = g(group) or empty
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000859 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000860 raise error("invalid group reference")
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300861 return empty.join(literals)