blob: 0bce71e9c97ce7f0defe45dd2b679643413f83fe [file] [log] [blame]
Guido van Rossum7627c0d2000-03-31 14:58:54 +00001#
2# Secret Labs' Regular Expression Engine
Guido van Rossum7627c0d2000-03-31 14:58:54 +00003#
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +00004# convert re-style regular expression to sre pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +00005#
Fredrik Lundh770617b2001-01-14 15:06:11 +00006# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
Guido van Rossum7627c0d2000-03-31 14:58:54 +00007#
Fredrik Lundh29c4ba92000-08-01 18:20:07 +00008# See the sre.py file for information on usage and redistribution.
Guido van Rossum7627c0d2000-03-31 14:58:54 +00009#
10
Fred Drakeb8f22742001-09-04 19:10:20 +000011"""Internal support module for sre"""
12
Fredrik Lundh470ea5a2001-01-14 21:00:44 +000013# XXX: show string offset and offending character for all errors
14
Guido van Rossum7627c0d2000-03-31 14:58:54 +000015from sre_constants import *
16
17SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000018REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000019
Serhiy Storchakae2ccf562014-10-10 11:14:49 +030020DIGITS = frozenset("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000021
Serhiy Storchakae2ccf562014-10-10 11:14:49 +030022OCTDIGITS = frozenset("01234567")
23HEXDIGITS = frozenset("0123456789abcdefABCDEF")
Serhiy Storchakaa54aae02015-03-24 22:58:14 +020024ASCIILETTERS = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000025
Serhiy Storchakae2ccf562014-10-10 11:14:49 +030026WHITESPACE = frozenset(" \t\n\r\v\f")
27
Raymond Hettingerdf1b6992014-11-09 15:56:33 -080028_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 Lundh90a07912000-06-30 07:50:59 +000072 self.groupdict = {}
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +020073 self.subpatterns = [None] # group 0
74 self.lookbehindgroups = None
75 @property
76 def groups(self):
77 return len(self.subpatterns)
Fredrik Lundhebc37b22000-10-28 19:30:41 +000078 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000079 gid = self.groups
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +020080 self.subpatterns.append(None)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +030081 if self.groups > MAXGROUPS:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +020082 raise error("too many groups")
Raymond Hettingerf13eb552002-06-02 00:40:05 +000083 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000084 ogid = self.groupdict.get(name, None)
85 if ogid is not None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +020086 raise error("redefinition of group name %r as group %d; "
87 "was group %d" % (name, gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000088 self.groupdict[name] = gid
89 return gid
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +020090 def closegroup(self, gid, p):
91 self.subpatterns[gid] = p
Fredrik Lundhebc37b22000-10-28 19:30:41 +000092 def checkgroup(self, gid):
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +020093 return gid < self.groups and self.subpatterns[gid] is not None
94
95 def checklookbehindgroup(self, gid, source):
96 if self.lookbehindgroups is not None:
97 if not self.checkgroup(gid):
98 raise source.error('cannot refer to an open group')
99 if gid >= self.lookbehindgroups:
100 raise source.error('cannot refer to group defined in the same '
101 'lookbehind subpattern')
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000102
103class SubPattern:
104 # a subpattern, in intermediate form
105 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000106 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +0000107 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000108 data = []
109 self.data = data
110 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000111 def dump(self, level=0):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300112 nl = True
Guido van Rossum13257902007-06-07 23:15:56 +0000113 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000114 for op, av in self.data:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200115 print(level*" " + str(op), end='')
Serhiy Storchakaab140882014-11-11 21:13:28 +0200116 if op is IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000117 # member sublanguage
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300118 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000119 for op, a in av:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200120 print((level+1)*" " + str(op), a)
Serhiy Storchakaab140882014-11-11 21:13:28 +0200121 elif op is BRANCH:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300122 print()
123 for i, a in enumerate(av[1]):
124 if i:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200125 print(level*" " + "OR")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300126 a.dump(level+1)
Serhiy Storchakaab140882014-11-11 21:13:28 +0200127 elif op is GROUPREF_EXISTS:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300128 condgroup, item_yes, item_no = av
129 print('', condgroup)
130 item_yes.dump(level+1)
131 if item_no:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200132 print(level*" " + "ELSE")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300133 item_no.dump(level+1)
Guido van Rossum13257902007-06-07 23:15:56 +0000134 elif isinstance(av, seqtypes):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300135 nl = False
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000136 for a in av:
137 if isinstance(a, SubPattern):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300138 if not nl:
139 print()
140 a.dump(level+1)
141 nl = True
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000142 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300143 if not nl:
144 print(' ', end='')
145 print(a, end='')
146 nl = False
147 if not nl:
148 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000149 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300150 print('', av)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000151 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000152 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000153 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000154 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000155 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000156 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000157 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000158 if isinstance(index, slice):
159 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000160 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000161 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000162 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000163 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000164 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000165 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000166 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000167 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000168 # determine the width (min, max) for this subpattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300169 if self.width is not None:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000170 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000171 lo = hi = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000172 for op, av in self.data:
173 if op is BRANCH:
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300174 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000175 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000176 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000177 l, h = av.getwidth()
178 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000179 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000180 lo = lo + i
181 hi = hi + j
182 elif op is CALL:
183 i, j = av.getwidth()
184 lo = lo + i
185 hi = hi + j
186 elif op is SUBPATTERN:
187 i, j = av[1].getwidth()
188 lo = lo + i
189 hi = hi + j
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300190 elif op in _REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000191 i, j = av[2].getwidth()
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300192 lo = lo + i * av[0]
193 hi = hi + j * av[1]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300194 elif op in _UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000195 lo = lo + 1
196 hi = hi + 1
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200197 elif op is GROUPREF:
198 i, j = self.pattern.subpatterns[av].getwidth()
199 lo = lo + i
200 hi = hi + j
201 elif op is GROUPREF_EXISTS:
202 i, j = av[1].getwidth()
203 if av[2] is not None:
204 l, h = av[2].getwidth()
205 i = min(i, l)
206 j = max(j, h)
207 else:
208 i = 0
209 lo = lo + i
210 hi = hi + j
211 elif op is SUCCESS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000212 break
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300213 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000214 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000215
216class Tokenizer:
217 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200218 self.istext = isinstance(string, str)
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200219 self.string = string
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300220 if not self.istext:
221 string = str(string, 'latin1')
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200222 self.decoded_string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000223 self.index = 0
Serhiy Storchakab99c1322014-11-10 14:38:16 +0200224 self.next = None
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000225 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000226 def __next(self):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300227 index = self.index
228 try:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200229 char = self.decoded_string[index]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300230 except IndexError:
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000231 self.next = None
232 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000233 if char == "\\":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300234 index += 1
Fredrik Lundh90a07912000-06-30 07:50:59 +0000235 try:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200236 char += self.decoded_string[index]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000237 except IndexError:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200238 raise error("bad escape (end of pattern)",
Serhiy Storchaka1b2004f2014-11-10 18:28:53 +0200239 self.string, len(self.string) - 1) from None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300240 self.index = index + 1
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000241 self.next = char
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300242 def match(self, char):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000243 if char == self.next:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300244 self.__next()
245 return True
246 return False
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000247 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000248 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000249 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000250 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200251 def getwhile(self, n, charset):
252 result = ''
253 for _ in range(n):
254 c = self.next
255 if c not in charset:
256 break
257 result += c
258 self.__next()
259 return result
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300260 def getuntil(self, terminator):
261 result = ''
262 while True:
263 c = self.next
264 self.__next()
265 if c is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200266 if not result:
267 raise self.error("missing group name")
268 raise self.error("missing %s, unterminated name" % terminator,
269 len(result))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300270 if c == terminator:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200271 if not result:
272 raise self.error("missing group name", 1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300273 break
274 result += c
275 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000276 def tell(self):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200277 return self.index - len(self.next or '')
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000278 def seek(self, index):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200279 self.index = index
280 self.__next()
281
282 def error(self, msg, offset=0):
283 return error(msg, self.string, self.tell() - offset)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000284
Georg Brandl1d472b72013-04-14 11:40:00 +0200285# The following three functions are not used in this module anymore, but we keep
286# them here (with DeprecationWarnings) for backwards compatibility.
287
Fredrik Lundh4781b072000-06-29 12:38:45 +0000288def isident(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200289 import warnings
290 warnings.warn('sre_parse.isident() will be removed in 3.5',
291 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000292 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
293
294def isdigit(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200295 import warnings
296 warnings.warn('sre_parse.isdigit() will be removed in 3.5',
297 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000298 return "0" <= char <= "9"
299
300def isname(name):
Georg Brandl1d472b72013-04-14 11:40:00 +0200301 import warnings
302 warnings.warn('sre_parse.isname() will be removed in 3.5',
303 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000304 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000305 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000306 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000307 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000308 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000309 return False
310 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000311
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000312def _class_escape(source, escape):
313 # handle escape code inside character class
314 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000315 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000316 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000317 code = CATEGORIES.get(escape)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300318 if code and code[0] is IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000319 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000320 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000321 c = escape[1:2]
322 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000323 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200324 escape += source.getwhile(2, HEXDIGITS)
325 if len(escape) != 4:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200326 raise source.error("incomplete escape %s" % escape, len(escape))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300327 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200328 elif c == "u" and source.istext:
329 # unicode escape (exactly four digits)
330 escape += source.getwhile(4, HEXDIGITS)
331 if len(escape) != 6:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200332 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200333 return LITERAL, int(escape[2:], 16)
334 elif c == "U" and source.istext:
335 # unicode escape (exactly eight digits)
336 escape += source.getwhile(8, HEXDIGITS)
337 if len(escape) != 10:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200338 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200339 c = int(escape[2:], 16)
340 chr(c) # raise ValueError for invalid code
341 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000342 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000343 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200344 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300345 c = int(escape[1:], 8)
346 if c > 0o377:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200347 raise source.error('octal escape value %s outside of '
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200348 'range 0-0o377' % escape, len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300349 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000350 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200351 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000352 if len(escape) == 2:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200353 if c in ASCIILETTERS:
354 import warnings
355 warnings.warn('bad escape %s' % escape,
356 DeprecationWarning, stacklevel=8)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000357 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000358 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000359 pass
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200360 raise source.error("bad escape %s" % escape, len(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000361
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000362def _escape(source, escape, state):
363 # handle escape code in expression
364 code = CATEGORIES.get(escape)
365 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000366 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000367 code = ESCAPES.get(escape)
368 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000369 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000370 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000371 c = escape[1:2]
372 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000373 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200374 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000375 if len(escape) != 4:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200376 raise source.error("incomplete escape %s" % escape, len(escape))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300377 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200378 elif c == "u" and source.istext:
379 # unicode escape (exactly four digits)
380 escape += source.getwhile(4, HEXDIGITS)
381 if len(escape) != 6:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200382 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200383 return LITERAL, int(escape[2:], 16)
384 elif c == "U" and source.istext:
385 # unicode escape (exactly eight digits)
386 escape += source.getwhile(8, HEXDIGITS)
387 if len(escape) != 10:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200388 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200389 c = int(escape[2:], 16)
390 chr(c) # raise ValueError for invalid code
391 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000392 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000393 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200394 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300395 return LITERAL, int(escape[1:], 8)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000396 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000397 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000398 if source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300399 escape += source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000400 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
401 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000402 # got three octal digits; this is an octal escape
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300403 escape += source.get()
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300404 c = int(escape[1:], 8)
405 if c > 0o377:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200406 raise source.error('octal escape value %s outside of '
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200407 'range 0-0o377' % escape,
408 len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300409 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000410 # not an octal escape, so this is a group reference
411 group = int(escape[1:])
412 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000413 if not state.checkgroup(group):
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200414 raise source.error("cannot refer to an open group",
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200415 len(escape))
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200416 state.checklookbehindgroup(group, source)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000417 return GROUPREF, group
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200418 raise source.error("invalid group reference", len(escape))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000419 if len(escape) == 2:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200420 if c in ASCIILETTERS:
421 import warnings
422 warnings.warn('bad escape %s' % escape,
423 DeprecationWarning, stacklevel=8)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000424 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000425 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000426 pass
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200427 raise source.error("bad escape %s" % escape, len(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000428
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300429def _parse_sub(source, state, nested=True):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000430 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000431
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000432 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000433 itemsappend = items.append
434 sourcematch = source.match
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200435 start = source.tell()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300436 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000437 itemsappend(_parse(source, state))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300438 if not sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000439 break
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000440
441 if len(items) == 1:
442 return items[0]
443
444 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000445 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000446
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000447 # check if all items share a common prefix
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300448 while True:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000449 prefix = None
450 for item in items:
451 if not item:
452 break
453 if prefix is None:
454 prefix = item[0]
455 elif item[0] != prefix:
456 break
457 else:
458 # all subitems start with a common "prefix".
459 # move it out of the branch
460 for item in items:
461 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000462 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000463 continue # check next one
464 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000465
466 # check if the branch can be replaced by a character set
467 for item in items:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300468 if len(item) != 1 or item[0][0] is not LITERAL:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000469 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000470 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000471 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000472 # branch (the compiler may optimize this even more)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300473 subpatternappend((IN, [item[0] for item in items]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000474 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000475
476 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000477 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000478
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000479def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000480 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000481 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000482 item_no = _parse(source, state)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300483 if source.next == "|":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200484 raise source.error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000485 else:
486 item_no = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000487 subpattern = SubPattern(state)
488 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
489 return subpattern
490
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000491def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000492 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000493 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000494
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000495 # precompute constants into local variables
496 subpatternappend = subpattern.append
497 sourceget = source.get
498 sourcematch = source.match
499 _len = len
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300500 _ord = ord
501 verbose = state.flags & SRE_FLAG_VERBOSE
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000502
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300503 while True:
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000504
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300505 this = source.next
Fredrik Lundh90a07912000-06-30 07:50:59 +0000506 if this is None:
507 break # end of pattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300508 if this in "|)":
509 break # end of subpattern
510 sourceget()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000511
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300512 if verbose:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000513 # skip whitespace and comments
514 if this in WHITESPACE:
515 continue
516 if this == "#":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300517 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000518 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300519 if this is None or this == "\n":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000520 break
521 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000522
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300523 if this[0] == "\\":
524 code = _escape(source, this, state)
525 subpatternappend(code)
526
527 elif this not in SPECIAL_CHARS:
528 subpatternappend((LITERAL, _ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000529
Fredrik Lundh90a07912000-06-30 07:50:59 +0000530 elif this == "[":
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200531 here = source.tell() - 1
Fredrik Lundh90a07912000-06-30 07:50:59 +0000532 # character set
533 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000534 setappend = set.append
535## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000536## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000537 if sourcematch("^"):
538 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000539 # check remaining characters
540 start = set[:]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300541 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000542 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300543 if this is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200544 raise source.error("unterminated character set",
545 source.tell() - here)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000546 if this == "]" and set != start:
547 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300548 elif this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000549 code1 = _class_escape(source, this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000550 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300551 code1 = LITERAL, _ord(this)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000552 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000553 # potential range
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200554 that = sourceget()
555 if that is None:
556 raise source.error("unterminated character set",
557 source.tell() - here)
558 if that == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000559 if code1[0] is IN:
560 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000561 setappend(code1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300562 setappend((LITERAL, _ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000563 break
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200564 if that[0] == "\\":
565 code2 = _class_escape(source, that)
Guido van Rossum41c99e72003-04-14 17:59:34 +0000566 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200567 code2 = LITERAL, _ord(that)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300568 if code1[0] != LITERAL or code2[0] != LITERAL:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200569 msg = "bad character range %s-%s" % (this, that)
570 raise source.error(msg, len(this) + 1 + len(that))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300571 lo = code1[1]
572 hi = code2[1]
573 if hi < lo:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200574 msg = "bad character range %s-%s" % (this, that)
575 raise source.error(msg, len(this) + 1 + len(that))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300576 setappend((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000577 else:
578 if code1[0] is IN:
579 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000580 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000581
Fredrik Lundh770617b2001-01-14 15:06:11 +0000582 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000583 if _len(set)==1 and set[0][0] is LITERAL:
584 subpatternappend(set[0]) # optimization
585 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
586 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000587 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000588 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000589 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000590
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300591 elif this in REPEAT_CHARS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000592 # repeat previous item
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200593 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000594 if this == "?":
595 min, max = 0, 1
596 elif this == "*":
597 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000598
Fredrik Lundh90a07912000-06-30 07:50:59 +0000599 elif this == "+":
600 min, max = 1, MAXREPEAT
601 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000602 if source.next == "}":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300603 subpatternappend((LITERAL, _ord(this)))
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000604 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000605 min, max = 0, MAXREPEAT
606 lo = hi = ""
607 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300608 lo += sourceget()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000609 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000610 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300611 hi += sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000612 else:
613 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000614 if not sourcematch("}"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300615 subpatternappend((LITERAL, _ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000616 source.seek(here)
617 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000618 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000619 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200620 if min >= MAXREPEAT:
621 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000622 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000623 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200624 if max >= MAXREPEAT:
625 raise OverflowError("the repetition number is too large")
626 if max < min:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200627 raise source.error("min repeat greater than max repeat",
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200628 source.tell() - here)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000629 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200630 raise AssertionError("unsupported quantifier %r" % (char,))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000631 # figure out which item to repeat
632 if subpattern:
633 item = subpattern[-1:]
634 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000635 item = None
Serhiy Storchakaab140882014-11-11 21:13:28 +0200636 if not item or (_len(item) == 1 and item[0][0] is AT):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200637 raise source.error("nothing to repeat",
638 source.tell() - here + len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300639 if item[0][0] in _REPEATCODES:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200640 raise source.error("multiple repeat",
641 source.tell() - here + len(this))
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000642 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000643 subpattern[-1] = (MIN_REPEAT, (min, max, item))
644 else:
645 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000646
Fredrik Lundh90a07912000-06-30 07:50:59 +0000647 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000648 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000649
Fredrik Lundh90a07912000-06-30 07:50:59 +0000650 elif this == "(":
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200651 start = source.tell() - 1
652 group = True
Fredrik Lundh90a07912000-06-30 07:50:59 +0000653 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000654 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000655 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000656 # options
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300657 char = sourceget()
658 if char is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200659 raise source.error("unexpected end of pattern")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300660 if char == "P":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000661 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000662 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000663 # named group: skip forward to end of name
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300664 name = source.getuntil(">")
Georg Brandl1d472b72013-04-14 11:40:00 +0200665 if not name.isidentifier():
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200666 msg = "bad character in group name %r" % name
667 raise source.error(msg, len(name) + 1)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000668 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000669 # named backreference
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300670 name = source.getuntil(")")
Georg Brandl1d472b72013-04-14 11:40:00 +0200671 if not name.isidentifier():
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200672 msg = "bad character in group name %r" % name
673 raise source.error(msg, len(name) + 1)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000674 gid = state.groupdict.get(name)
675 if gid is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200676 msg = "unknown group name %r" % name
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200677 raise source.error(msg, len(name) + 1)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200678 state.checklookbehindgroup(gid, source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000679 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000680 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000681 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000682 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000683 if char is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200684 raise source.error("unexpected end of pattern")
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200685 raise source.error("unknown extension ?P" + char,
686 len(char) + 2)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300687 elif char == ":":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000688 # non-capturing group
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200689 group = None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300690 elif char == "#":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000691 # comment
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300692 while True:
693 if source.next is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200694 raise source.error("missing ), unterminated comment",
695 source.tell() - start)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300696 if sourceget() == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000697 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000698 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300699 elif char in "=!<":
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000700 # lookahead assertions
Fredrik Lundh6f013982000-07-03 18:44:21 +0000701 dir = 1
702 if char == "<":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300703 char = sourceget()
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200704 if char is None:
705 raise source.error("unexpected end of pattern")
706 if char not in "=!":
707 raise source.error("unknown extension ?<" + char,
708 len(char) + 2)
Fredrik Lundh6f013982000-07-03 18:44:21 +0000709 dir = -1 # lookbehind
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200710 lookbehindgroups = state.lookbehindgroups
711 if lookbehindgroups is None:
712 state.lookbehindgroups = state.groups
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000713 p = _parse_sub(source, state)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200714 if dir < 0:
715 if lookbehindgroups is None:
716 state.lookbehindgroups = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000717 if not sourcematch(")"):
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200718 raise source.error("missing ), unterminated subpattern",
719 source.tell() - start)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000720 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000721 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000722 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000723 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000724 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300725 elif char == "(":
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000726 # conditional backreference group
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300727 condname = source.getuntil(")")
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200728 group = None
Georg Brandl1d472b72013-04-14 11:40:00 +0200729 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000730 condgroup = state.groupdict.get(condname)
731 if condgroup is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200732 msg = "unknown group name %r" % condname
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200733 raise source.error(msg, len(condname) + 1)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000734 else:
735 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000736 condgroup = int(condname)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300737 if condgroup < 0:
738 raise ValueError
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000739 except ValueError:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200740 msg = "bad character in group name %r" % condname
741 raise source.error(msg, len(condname) + 1) from None
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300742 if not condgroup:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200743 raise source.error("bad group number",
744 len(condname) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300745 if condgroup >= MAXGROUPS:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200746 raise source.error("invalid group reference",
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200747 len(condname) + 1)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200748 state.checklookbehindgroup(condgroup, source)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300749 elif char in FLAGS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000750 # flags
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200751 while True:
752 state.flags |= FLAGS[char]
753 char = sourceget()
754 if char is None:
755 raise source.error("missing )")
756 if char == ")":
757 break
758 if char not in FLAGS:
759 raise source.error("unknown flag", len(char))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300760 verbose = state.flags & SRE_FLAG_VERBOSE
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200761 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300762 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200763 raise source.error("unknown extension ?" + char,
764 len(char) + 1)
765
766 # parse group contents
767 if group is not None:
768 try:
769 group = state.opengroup(name)
770 except error as err:
771 raise source.error(err.msg, len(name) + 1) from None
772 if condgroup:
773 p = _parse_sub_cond(source, state, condgroup)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000774 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200775 p = _parse_sub(source, state)
776 if not source.match(")"):
777 raise source.error("missing ), unterminated subpattern",
778 source.tell() - start)
779 if group is not None:
780 state.closegroup(group, p)
781 subpatternappend((SUBPATTERN, (group, p)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000782
Fredrik Lundh90a07912000-06-30 07:50:59 +0000783 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000784 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000785
Fredrik Lundh90a07912000-06-30 07:50:59 +0000786 elif this == "$":
787 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000788
Fredrik Lundh90a07912000-06-30 07:50:59 +0000789 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200790 raise AssertionError("unsupported special character %r" % (char,))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000791
792 return subpattern
793
Antoine Pitroufd036452008-08-19 17:56:33 +0000794def fix_flags(src, flags):
795 # Check and fix flags according to the type of pattern (str or bytes)
796 if isinstance(src, str):
Serhiy Storchaka22a309a2014-12-01 11:50:07 +0200797 if flags & SRE_FLAG_LOCALE:
798 import warnings
799 warnings.warn("LOCALE flag with a str pattern is deprecated. "
800 "Will be an error in 3.6",
801 DeprecationWarning, stacklevel=6)
Antoine Pitroufd036452008-08-19 17:56:33 +0000802 if not flags & SRE_FLAG_ASCII:
803 flags |= SRE_FLAG_UNICODE
804 elif flags & SRE_FLAG_UNICODE:
805 raise ValueError("ASCII and UNICODE flags are incompatible")
806 else:
807 if flags & SRE_FLAG_UNICODE:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200808 raise ValueError("cannot use UNICODE flag with a bytes pattern")
Serhiy Storchaka22a309a2014-12-01 11:50:07 +0200809 if flags & SRE_FLAG_LOCALE and flags & SRE_FLAG_ASCII:
810 import warnings
811 warnings.warn("ASCII and LOCALE flags are incompatible. "
812 "Will be an error in 3.6",
813 DeprecationWarning, stacklevel=6)
Antoine Pitroufd036452008-08-19 17:56:33 +0000814 return flags
815
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000816def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000817 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000818
819 source = Tokenizer(str)
820
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000821 if pattern is None:
822 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000823 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000824 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000825
826 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000827 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000828
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300829 if source.next is not None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200830 assert source.next == ")"
831 raise source.error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000832
Fredrik Lundh770617b2001-01-14 15:06:11 +0000833 if flags & SRE_FLAG_DEBUG:
834 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000835
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000836 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
837 # the VERBOSE flag was switched on inside the pattern. to be
838 # on the safe side, we'll parse the whole thing again...
839 return parse(str, p.pattern.flags)
840
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000841 return p
842
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000843def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000844 # parse 're' replacement string into list of literals and
845 # group references
846 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000847 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300848 groups = []
849 literals = []
850 literal = []
851 lappend = literal.append
852 def addgroup(index):
853 if literal:
854 literals.append(''.join(literal))
855 del literal[:]
856 groups.append((len(literals), index))
857 literals.append(None)
858 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000859 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000860 if this is None:
861 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300862 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000863 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300864 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000865 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000866 name = ""
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200867 if not s.match("<"):
868 raise s.error("missing <")
869 name = s.getuntil(">")
870 if name.isidentifier():
Fredrik Lundh90a07912000-06-30 07:50:59 +0000871 try:
872 index = pattern.groupindex[name]
873 except KeyError:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200874 raise IndexError("unknown group name %r" % name)
875 else:
876 try:
877 index = int(name)
878 if index < 0:
879 raise ValueError
880 except ValueError:
881 raise s.error("bad character in group name %r" % name,
882 len(name) + 1) from None
883 if index >= MAXGROUPS:
884 raise s.error("invalid group reference",
885 len(name) + 1)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300886 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000887 elif c == "0":
888 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300889 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000890 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300891 this += sget()
892 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000893 elif c in DIGITS:
894 isoctal = False
895 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300896 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000897 if (c in OCTDIGITS and this[2] in OCTDIGITS and
898 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300899 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000900 isoctal = True
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300901 c = int(this[1:], 8)
902 if c > 0o377:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200903 raise s.error('octal escape value %s outside of '
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200904 'range 0-0o377' % this, len(this))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300905 lappend(chr(c))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000906 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300907 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000908 else:
909 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300910 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000911 except KeyError:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200912 if c in ASCIILETTERS:
913 import warnings
914 warnings.warn('bad escape %s' % this,
Serhiy Storchaka15fa1c42015-03-25 01:21:50 +0200915 DeprecationWarning, stacklevel=4)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300916 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000917 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300918 lappend(this)
919 if literal:
920 literals.append(''.join(literal))
921 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000922 # The tokenizer implicitly decodes bytes objects as latin-1, we must
923 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300924 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000925 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000926
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000927def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000928 g = match.group
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300929 empty = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000930 groups, literals = template
931 literals = literals[:]
932 try:
933 for index, group in groups:
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300934 literals[index] = g(group) or empty
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000935 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000936 raise error("invalid group reference")
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300937 return empty.join(literals)