blob: e6f1f1d839a22cefe6573326d15c23d327f16bc6 [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:
82 raise error("groups number is too large")
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 Storchaka1b2004f2014-11-10 18:28:53 +0200238 raise error("bogus escape (end of line)",
239 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 Storchakaad446d52014-11-10 13:49:00 +0200266 raise self.error("unterminated name")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300267 if c == terminator:
268 break
269 result += c
270 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000271 def tell(self):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200272 return self.index - len(self.next or '')
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000273 def seek(self, index):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200274 self.index = index
275 self.__next()
276
277 def error(self, msg, offset=0):
278 return error(msg, self.string, self.tell() - offset)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000279
Georg Brandl1d472b72013-04-14 11:40:00 +0200280# The following three functions are not used in this module anymore, but we keep
281# them here (with DeprecationWarnings) for backwards compatibility.
282
Fredrik Lundh4781b072000-06-29 12:38:45 +0000283def isident(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200284 import warnings
285 warnings.warn('sre_parse.isident() will be removed in 3.5',
286 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000287 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
288
289def isdigit(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200290 import warnings
291 warnings.warn('sre_parse.isdigit() will be removed in 3.5',
292 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000293 return "0" <= char <= "9"
294
295def isname(name):
Georg Brandl1d472b72013-04-14 11:40:00 +0200296 import warnings
297 warnings.warn('sre_parse.isname() will be removed in 3.5',
298 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000299 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000300 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000301 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000302 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000303 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000304 return False
305 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000306
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000307def _class_escape(source, escape):
308 # handle escape code inside character class
309 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000310 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000311 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000312 code = CATEGORIES.get(escape)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300313 if code and code[0] is IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000314 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000315 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000316 c = escape[1:2]
317 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000318 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200319 escape += source.getwhile(2, HEXDIGITS)
320 if len(escape) != 4:
321 raise ValueError
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300322 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200323 elif c == "u" and source.istext:
324 # unicode escape (exactly four digits)
325 escape += source.getwhile(4, HEXDIGITS)
326 if len(escape) != 6:
327 raise ValueError
328 return LITERAL, int(escape[2:], 16)
329 elif c == "U" and source.istext:
330 # unicode escape (exactly eight digits)
331 escape += source.getwhile(8, HEXDIGITS)
332 if len(escape) != 10:
333 raise ValueError
334 c = int(escape[2:], 16)
335 chr(c) # raise ValueError for invalid code
336 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000337 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000338 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200339 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300340 c = int(escape[1:], 8)
341 if c > 0o377:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200342 raise source.error('octal escape value %r outside of '
343 'range 0-0o377' % escape, len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300344 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000345 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200346 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000347 if len(escape) == 2:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200348 if c in ASCIILETTERS:
349 import warnings
350 warnings.warn('bad escape %s' % escape,
351 DeprecationWarning, stacklevel=8)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000352 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000353 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000354 pass
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200355 raise source.error("bogus escape: %r" % escape, len(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000356
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000357def _escape(source, escape, state):
358 # handle escape code in expression
359 code = CATEGORIES.get(escape)
360 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000361 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000362 code = ESCAPES.get(escape)
363 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000364 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000365 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000366 c = escape[1:2]
367 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000368 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200369 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000370 if len(escape) != 4:
371 raise ValueError
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300372 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200373 elif c == "u" and source.istext:
374 # unicode escape (exactly four digits)
375 escape += source.getwhile(4, HEXDIGITS)
376 if len(escape) != 6:
377 raise ValueError
378 return LITERAL, int(escape[2:], 16)
379 elif c == "U" and source.istext:
380 # unicode escape (exactly eight digits)
381 escape += source.getwhile(8, HEXDIGITS)
382 if len(escape) != 10:
383 raise ValueError
384 c = int(escape[2:], 16)
385 chr(c) # raise ValueError for invalid code
386 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000387 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000388 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200389 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300390 return LITERAL, int(escape[1:], 8)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000391 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000392 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000393 if source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300394 escape += source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000395 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
396 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000397 # got three octal digits; this is an octal escape
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300398 escape += source.get()
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300399 c = int(escape[1:], 8)
400 if c > 0o377:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200401 raise source.error('octal escape value %r outside of '
402 'range 0-0o377' % escape,
403 len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300404 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000405 # not an octal escape, so this is a group reference
406 group = int(escape[1:])
407 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000408 if not state.checkgroup(group):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200409 raise source.error("cannot refer to open group",
410 len(escape))
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200411 state.checklookbehindgroup(group, source)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000412 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000413 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000414 if len(escape) == 2:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200415 if c in ASCIILETTERS:
416 import warnings
417 warnings.warn('bad escape %s' % escape,
418 DeprecationWarning, stacklevel=8)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000419 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000420 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000421 pass
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200422 raise source.error("bogus escape: %r" % escape, len(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000423
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300424def _parse_sub(source, state, nested=True):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000425 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000426
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000427 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000428 itemsappend = items.append
429 sourcematch = source.match
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300430 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000431 itemsappend(_parse(source, state))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300432 if not sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000433 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300434 if nested and source.next is not None and source.next != ")":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200435 raise source.error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000436
437 if len(items) == 1:
438 return items[0]
439
440 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000441 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000442
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000443 # check if all items share a common prefix
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300444 while True:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000445 prefix = None
446 for item in items:
447 if not item:
448 break
449 if prefix is None:
450 prefix = item[0]
451 elif item[0] != prefix:
452 break
453 else:
454 # all subitems start with a common "prefix".
455 # move it out of the branch
456 for item in items:
457 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000458 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000459 continue # check next one
460 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000461
462 # check if the branch can be replaced by a character set
463 for item in items:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300464 if len(item) != 1 or item[0][0] is not LITERAL:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000465 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000466 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000467 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000468 # branch (the compiler may optimize this even more)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300469 subpatternappend((IN, [item[0] for item in items]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000470 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000471
472 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000473 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000474
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000475def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000476 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000477 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000478 item_no = _parse(source, state)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300479 if source.next == "|":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200480 raise source.error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000481 else:
482 item_no = None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300483 if source.next is not None and source.next != ")":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200484 raise source.error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000485 subpattern = SubPattern(state)
486 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
487 return subpattern
488
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000489def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000490 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000491 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000492
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000493 # precompute constants into local variables
494 subpatternappend = subpattern.append
495 sourceget = source.get
496 sourcematch = source.match
497 _len = len
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300498 _ord = ord
499 verbose = state.flags & SRE_FLAG_VERBOSE
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000500
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300501 while True:
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000502
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300503 this = source.next
Fredrik Lundh90a07912000-06-30 07:50:59 +0000504 if this is None:
505 break # end of pattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300506 if this in "|)":
507 break # end of subpattern
508 sourceget()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000509
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300510 if verbose:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000511 # skip whitespace and comments
512 if this in WHITESPACE:
513 continue
514 if this == "#":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300515 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000516 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300517 if this is None or this == "\n":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000518 break
519 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000520
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300521 if this[0] == "\\":
522 code = _escape(source, this, state)
523 subpatternappend(code)
524
525 elif this not in SPECIAL_CHARS:
526 subpatternappend((LITERAL, _ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000527
Fredrik Lundh90a07912000-06-30 07:50:59 +0000528 elif this == "[":
529 # character set
530 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000531 setappend = set.append
532## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000533## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000534 if sourcematch("^"):
535 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000536 # check remaining characters
537 start = set[:]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300538 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000539 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300540 if this is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200541 raise source.error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000542 if this == "]" and set != start:
543 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300544 elif this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000545 code1 = _class_escape(source, this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000546 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300547 code1 = LITERAL, _ord(this)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000548 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000549 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000550 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300551 if this is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200552 raise source.error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000553 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000554 if code1[0] is IN:
555 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000556 setappend(code1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300557 setappend((LITERAL, _ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000558 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300559 if this[0] == "\\":
560 code2 = _class_escape(source, this)
Guido van Rossum41c99e72003-04-14 17:59:34 +0000561 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300562 code2 = LITERAL, _ord(this)
563 if code1[0] != LITERAL or code2[0] != LITERAL:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200564 raise source.error("bad character range", len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300565 lo = code1[1]
566 hi = code2[1]
567 if hi < lo:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200568 raise source.error("bad character range", len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300569 setappend((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000570 else:
571 if code1[0] is IN:
572 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000573 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000574
Fredrik Lundh770617b2001-01-14 15:06:11 +0000575 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000576 if _len(set)==1 and set[0][0] is LITERAL:
577 subpatternappend(set[0]) # optimization
578 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
579 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000580 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000581 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000582 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000583
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300584 elif this in REPEAT_CHARS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000585 # repeat previous item
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200586 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000587 if this == "?":
588 min, max = 0, 1
589 elif this == "*":
590 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000591
Fredrik Lundh90a07912000-06-30 07:50:59 +0000592 elif this == "+":
593 min, max = 1, MAXREPEAT
594 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000595 if source.next == "}":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300596 subpatternappend((LITERAL, _ord(this)))
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000597 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000598 min, max = 0, MAXREPEAT
599 lo = hi = ""
600 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300601 lo += sourceget()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000602 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000603 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300604 hi += sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000605 else:
606 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000607 if not sourcematch("}"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300608 subpatternappend((LITERAL, _ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000609 source.seek(here)
610 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000611 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000612 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200613 if min >= MAXREPEAT:
614 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000615 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000616 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200617 if max >= MAXREPEAT:
618 raise OverflowError("the repetition number is too large")
619 if max < min:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200620 raise source.error("bad repeat interval",
621 source.tell() - here)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000622 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200623 raise source.error("not supported", len(this))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000624 # figure out which item to repeat
625 if subpattern:
626 item = subpattern[-1:]
627 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000628 item = None
Serhiy Storchakaab140882014-11-11 21:13:28 +0200629 if not item or (_len(item) == 1 and item[0][0] is AT):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200630 raise source.error("nothing to repeat",
631 source.tell() - here + len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300632 if item[0][0] in _REPEATCODES:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200633 raise source.error("multiple repeat",
634 source.tell() - here + len(this))
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000635 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000636 subpattern[-1] = (MIN_REPEAT, (min, max, item))
637 else:
638 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000639
Fredrik Lundh90a07912000-06-30 07:50:59 +0000640 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000641 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000642
Fredrik Lundh90a07912000-06-30 07:50:59 +0000643 elif this == "(":
644 group = 1
645 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000646 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000647 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000648 group = 0
649 # options
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300650 char = sourceget()
651 if char is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200652 raise self.error("unexpected end of pattern")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300653 if char == "P":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000654 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000655 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000656 # named group: skip forward to end of name
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300657 name = source.getuntil(">")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000658 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200659 if not name:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200660 raise source.error("missing group name", 1)
Georg Brandl1d472b72013-04-14 11:40:00 +0200661 if not name.isidentifier():
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200662 raise source.error("bad character in group name "
663 "%r" % name,
664 len(name) + 1)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000665 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000666 # named backreference
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300667 name = source.getuntil(")")
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200668 if not name:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200669 raise source.error("missing group name", 1)
Georg Brandl1d472b72013-04-14 11:40:00 +0200670 if not name.isidentifier():
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200671 raise source.error("bad character in backref "
672 "group name %r" % name,
673 len(name) + 1)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000674 gid = state.groupdict.get(name)
675 if gid is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700676 msg = "unknown group name: {0!r}".format(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")
685 raise source.error("unknown specifier: ?P%s" % char,
686 len(char))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300687 elif char == ":":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000688 # non-capturing group
689 group = 2
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 Storchakaad446d52014-11-10 13:49:00 +0200694 raise source.error("unbalanced parenthesis")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300695 if sourceget() == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000696 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000697 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300698 elif char in "=!<":
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000699 # lookahead assertions
Fredrik Lundh6f013982000-07-03 18:44:21 +0000700 dir = 1
701 if char == "<":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300702 char = sourceget()
703 if char is None or char not in "=!":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200704 raise source.error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000705 dir = -1 # lookbehind
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200706 lookbehindgroups = state.lookbehindgroups
707 if lookbehindgroups is None:
708 state.lookbehindgroups = state.groups
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000709 p = _parse_sub(source, state)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200710 if dir < 0:
711 if lookbehindgroups is None:
712 state.lookbehindgroups = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000713 if not sourcematch(")"):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200714 raise source.error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000715 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000716 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000717 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000718 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000719 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300720 elif char == "(":
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000721 # conditional backreference group
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300722 condname = source.getuntil(")")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000723 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200724 if not condname:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200725 raise source.error("missing group name", 1)
Georg Brandl1d472b72013-04-14 11:40:00 +0200726 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000727 condgroup = state.groupdict.get(condname)
728 if condgroup is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700729 msg = "unknown group name: {0!r}".format(condname)
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200730 raise source.error(msg, len(condname) + 1)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000731 else:
732 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000733 condgroup = int(condname)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300734 if condgroup < 0:
735 raise ValueError
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000736 except ValueError:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200737 raise source.error("bad character in group name",
738 len(condname) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300739 if not condgroup:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200740 raise source.error("bad group number",
741 len(condname) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300742 if condgroup >= MAXGROUPS:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200743 raise source.error("the group number is too large",
744 len(condname) + 1)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200745 state.checklookbehindgroup(condgroup, source)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300746 elif char in FLAGS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000747 # flags
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300748 state.flags |= FLAGS[char]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000749 while source.next in FLAGS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300750 state.flags |= FLAGS[sourceget()]
751 verbose = state.flags & SRE_FLAG_VERBOSE
752 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200753 raise source.error("unexpected end of pattern")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000754 if group:
755 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000756 if group == 2:
757 # anonymous group
758 group = None
759 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200760 try:
761 group = state.opengroup(name)
762 except error as err:
763 raise source.error(err.msg, len(name) + 1)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000764 if condgroup:
765 p = _parse_sub_cond(source, state, condgroup)
766 else:
767 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000768 if not sourcematch(")"):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200769 raise source.error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000770 if group is not None:
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200771 state.closegroup(group, p)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000772 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000773 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300774 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000775 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000776 if char is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200777 raise source.error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000778 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000779 break
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200780 raise source.error("unknown extension", len(char))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000781
Fredrik Lundh90a07912000-06-30 07:50:59 +0000782 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000783 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000784
Fredrik Lundh90a07912000-06-30 07:50:59 +0000785 elif this == "$":
786 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000787
Fredrik Lundh90a07912000-06-30 07:50:59 +0000788 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200789 raise source.error("parser error", len(this))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000790
791 return subpattern
792
Antoine Pitroufd036452008-08-19 17:56:33 +0000793def fix_flags(src, flags):
794 # Check and fix flags according to the type of pattern (str or bytes)
795 if isinstance(src, str):
Serhiy Storchaka22a309a2014-12-01 11:50:07 +0200796 if flags & SRE_FLAG_LOCALE:
797 import warnings
798 warnings.warn("LOCALE flag with a str pattern is deprecated. "
799 "Will be an error in 3.6",
800 DeprecationWarning, stacklevel=6)
Antoine Pitroufd036452008-08-19 17:56:33 +0000801 if not flags & SRE_FLAG_ASCII:
802 flags |= SRE_FLAG_UNICODE
803 elif flags & SRE_FLAG_UNICODE:
804 raise ValueError("ASCII and UNICODE flags are incompatible")
805 else:
806 if flags & SRE_FLAG_UNICODE:
807 raise ValueError("can't use UNICODE flag with a bytes pattern")
Serhiy Storchaka22a309a2014-12-01 11:50:07 +0200808 if flags & SRE_FLAG_LOCALE and flags & SRE_FLAG_ASCII:
809 import warnings
810 warnings.warn("ASCII and LOCALE flags are incompatible. "
811 "Will be an error in 3.6",
812 DeprecationWarning, stacklevel=6)
Antoine Pitroufd036452008-08-19 17:56:33 +0000813 return flags
814
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000815def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000816 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000817
818 source = Tokenizer(str)
819
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000820 if pattern is None:
821 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000822 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000823 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000824
825 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000826 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000827
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300828 if source.next is not None:
829 if source.next == ")":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200830 raise source.error("unbalanced parenthesis")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300831 else:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200832 raise source.error("bogus characters at end of regular expression",
833 len(tail))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000834
Fredrik Lundh770617b2001-01-14 15:06:11 +0000835 if flags & SRE_FLAG_DEBUG:
836 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000837
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000838 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
839 # the VERBOSE flag was switched on inside the pattern. to be
840 # on the safe side, we'll parse the whole thing again...
841 return parse(str, p.pattern.flags)
842
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000843 return p
844
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000845def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000846 # parse 're' replacement string into list of literals and
847 # group references
848 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000849 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300850 groups = []
851 literals = []
852 literal = []
853 lappend = literal.append
854 def addgroup(index):
855 if literal:
856 literals.append(''.join(literal))
857 del literal[:]
858 groups.append((len(literals), index))
859 literals.append(None)
860 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000861 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000862 if this is None:
863 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300864 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000865 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300866 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000867 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000868 name = ""
869 if s.match("<"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300870 name = s.getuntil(">")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000871 if not name:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200872 raise s.error("missing group name", 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000873 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000874 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000875 if index < 0:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200876 raise s.error("negative group number", len(name) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300877 if index >= MAXGROUPS:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200878 raise s.error("the group number is too large",
879 len(name) + 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000880 except ValueError:
Georg Brandl1d472b72013-04-14 11:40:00 +0200881 if not name.isidentifier():
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200882 raise s.error("bad character in group name",
883 len(name) + 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000884 try:
885 index = pattern.groupindex[name]
886 except KeyError:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700887 msg = "unknown group name: {0!r}".format(name)
888 raise IndexError(msg)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300889 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000890 elif c == "0":
891 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300892 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000893 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300894 this += sget()
895 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000896 elif c in DIGITS:
897 isoctal = False
898 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300899 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000900 if (c in OCTDIGITS and this[2] in OCTDIGITS and
901 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300902 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000903 isoctal = True
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300904 c = int(this[1:], 8)
905 if c > 0o377:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200906 raise s.error('octal escape value %r outside of '
907 'range 0-0o377' % this, len(this))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300908 lappend(chr(c))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000909 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300910 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000911 else:
912 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300913 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000914 except KeyError:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200915 if c in ASCIILETTERS:
916 import warnings
917 warnings.warn('bad escape %s' % this,
Serhiy Storchaka15fa1c42015-03-25 01:21:50 +0200918 DeprecationWarning, stacklevel=4)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300919 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000920 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300921 lappend(this)
922 if literal:
923 literals.append(''.join(literal))
924 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000925 # The tokenizer implicitly decodes bytes objects as latin-1, we must
926 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300927 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000928 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000929
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000930def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000931 g = match.group
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300932 empty = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000933 groups, literals = template
934 literals = literals[:]
935 try:
936 for index, group in groups:
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300937 literals[index] = g(group) or empty
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000938 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000939 raise error("invalid group reference")
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300940 return empty.join(literals)