blob: 521e379e72065931bb2184350450d9a21c765b16 [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 Storchakab5d0a212015-11-05 17:49:26 +020073 self.groupwidths = [None] # group 0
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +020074 self.lookbehindgroups = None
75 @property
76 def groups(self):
Serhiy Storchakab5d0a212015-11-05 17:49:26 +020077 return len(self.groupwidths)
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 Storchakab5d0a212015-11-05 17:49:26 +020080 self.groupwidths.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):
Serhiy Storchakab5d0a212015-11-05 17:49:26 +020091 self.groupwidths[gid] = p.getwidth()
Fredrik Lundhebc37b22000-10-28 19:30:41 +000092 def checkgroup(self, gid):
Serhiy Storchakab5d0a212015-11-05 17:49:26 +020093 return gid < self.groups and self.groupwidths[gid] is not None
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +020094
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:
Serhiy Storchakab5d0a212015-11-05 17:49:26 +0200198 i, j = self.pattern.groupwidths[av]
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200199 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
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000285def _class_escape(source, escape):
286 # handle escape code inside character class
287 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000288 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000289 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000290 code = CATEGORIES.get(escape)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300291 if code and code[0] is IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000292 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000293 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000294 c = escape[1:2]
295 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000296 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200297 escape += source.getwhile(2, HEXDIGITS)
298 if len(escape) != 4:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200299 raise source.error("incomplete escape %s" % escape, len(escape))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300300 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200301 elif c == "u" and source.istext:
302 # unicode escape (exactly four digits)
303 escape += source.getwhile(4, HEXDIGITS)
304 if len(escape) != 6:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200305 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200306 return LITERAL, int(escape[2:], 16)
307 elif c == "U" and source.istext:
308 # unicode escape (exactly eight digits)
309 escape += source.getwhile(8, HEXDIGITS)
310 if len(escape) != 10:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200311 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200312 c = int(escape[2:], 16)
313 chr(c) # raise ValueError for invalid code
314 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000315 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000316 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200317 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300318 c = int(escape[1:], 8)
319 if c > 0o377:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200320 raise source.error('octal escape value %s outside of '
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200321 'range 0-0o377' % escape, len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300322 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000323 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200324 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000325 if len(escape) == 2:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200326 if c in ASCIILETTERS:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300327 raise source.error('bad escape %s' % escape, len(escape))
Fredrik Lundh0640e112000-06-30 13:55:15 +0000328 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000329 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000330 pass
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200331 raise source.error("bad escape %s" % escape, len(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000332
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000333def _escape(source, escape, state):
334 # handle escape code in expression
335 code = CATEGORIES.get(escape)
336 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000337 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000338 code = ESCAPES.get(escape)
339 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000340 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000341 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000342 c = escape[1:2]
343 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000344 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200345 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000346 if len(escape) != 4:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200347 raise source.error("incomplete escape %s" % escape, len(escape))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300348 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200349 elif c == "u" and source.istext:
350 # unicode escape (exactly four digits)
351 escape += source.getwhile(4, HEXDIGITS)
352 if len(escape) != 6:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200353 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200354 return LITERAL, int(escape[2:], 16)
355 elif c == "U" and source.istext:
356 # unicode escape (exactly eight digits)
357 escape += source.getwhile(8, HEXDIGITS)
358 if len(escape) != 10:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200359 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200360 c = int(escape[2:], 16)
361 chr(c) # raise ValueError for invalid code
362 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000363 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000364 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200365 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300366 return LITERAL, int(escape[1:], 8)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000367 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000368 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000369 if source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300370 escape += source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000371 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
372 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000373 # got three octal digits; this is an octal escape
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300374 escape += source.get()
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300375 c = int(escape[1:], 8)
376 if c > 0o377:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200377 raise source.error('octal escape value %s outside of '
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200378 'range 0-0o377' % escape,
379 len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300380 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000381 # not an octal escape, so this is a group reference
382 group = int(escape[1:])
383 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000384 if not state.checkgroup(group):
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200385 raise source.error("cannot refer to an open group",
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200386 len(escape))
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200387 state.checklookbehindgroup(group, source)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000388 return GROUPREF, group
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200389 raise source.error("invalid group reference", len(escape))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000390 if len(escape) == 2:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200391 if c in ASCIILETTERS:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300392 raise source.error("bad escape %s" % escape, len(escape))
Fredrik Lundh0640e112000-06-30 13:55:15 +0000393 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000394 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000395 pass
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200396 raise source.error("bad escape %s" % escape, len(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000397
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300398def _parse_sub(source, state, nested=True):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000399 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000400
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000401 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000402 itemsappend = items.append
403 sourcematch = source.match
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200404 start = source.tell()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300405 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000406 itemsappend(_parse(source, state))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300407 if not sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000408 break
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000409
410 if len(items) == 1:
411 return items[0]
412
413 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000414 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000415
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000416 # check if all items share a common prefix
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300417 while True:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000418 prefix = None
419 for item in items:
420 if not item:
421 break
422 if prefix is None:
423 prefix = item[0]
424 elif item[0] != prefix:
425 break
426 else:
427 # all subitems start with a common "prefix".
428 # move it out of the branch
429 for item in items:
430 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000431 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000432 continue # check next one
433 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000434
435 # check if the branch can be replaced by a character set
436 for item in items:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300437 if len(item) != 1 or item[0][0] is not LITERAL:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000438 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000439 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000440 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000441 # branch (the compiler may optimize this even more)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300442 subpatternappend((IN, [item[0] for item in items]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000443 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000444
445 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000446 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000447
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000448def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000449 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000450 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000451 item_no = _parse(source, state)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300452 if source.next == "|":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200453 raise source.error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000454 else:
455 item_no = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000456 subpattern = SubPattern(state)
457 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
458 return subpattern
459
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000460def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000461 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000462 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000463
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000464 # precompute constants into local variables
465 subpatternappend = subpattern.append
466 sourceget = source.get
467 sourcematch = source.match
468 _len = len
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300469 _ord = ord
470 verbose = state.flags & SRE_FLAG_VERBOSE
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000471
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300472 while True:
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000473
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300474 this = source.next
Fredrik Lundh90a07912000-06-30 07:50:59 +0000475 if this is None:
476 break # end of pattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300477 if this in "|)":
478 break # end of subpattern
479 sourceget()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000480
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300481 if verbose:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000482 # skip whitespace and comments
483 if this in WHITESPACE:
484 continue
485 if this == "#":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300486 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000487 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300488 if this is None or this == "\n":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000489 break
490 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000491
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300492 if this[0] == "\\":
493 code = _escape(source, this, state)
494 subpatternappend(code)
495
496 elif this not in SPECIAL_CHARS:
497 subpatternappend((LITERAL, _ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000498
Fredrik Lundh90a07912000-06-30 07:50:59 +0000499 elif this == "[":
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200500 here = source.tell() - 1
Fredrik Lundh90a07912000-06-30 07:50:59 +0000501 # character set
502 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000503 setappend = set.append
504## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000505## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000506 if sourcematch("^"):
507 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000508 # check remaining characters
509 start = set[:]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300510 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000511 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300512 if this is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200513 raise source.error("unterminated character set",
514 source.tell() - here)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000515 if this == "]" and set != start:
516 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300517 elif this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000518 code1 = _class_escape(source, this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000519 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300520 code1 = LITERAL, _ord(this)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000521 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000522 # potential range
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200523 that = sourceget()
524 if that is None:
525 raise source.error("unterminated character set",
526 source.tell() - here)
527 if that == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000528 if code1[0] is IN:
529 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000530 setappend(code1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300531 setappend((LITERAL, _ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000532 break
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200533 if that[0] == "\\":
534 code2 = _class_escape(source, that)
Guido van Rossum41c99e72003-04-14 17:59:34 +0000535 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200536 code2 = LITERAL, _ord(that)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300537 if code1[0] != LITERAL or code2[0] != LITERAL:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200538 msg = "bad character range %s-%s" % (this, that)
539 raise source.error(msg, len(this) + 1 + len(that))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300540 lo = code1[1]
541 hi = code2[1]
542 if hi < lo:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200543 msg = "bad character range %s-%s" % (this, that)
544 raise source.error(msg, len(this) + 1 + len(that))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300545 setappend((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000546 else:
547 if code1[0] is IN:
548 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000549 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000550
Fredrik Lundh770617b2001-01-14 15:06:11 +0000551 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000552 if _len(set)==1 and set[0][0] is LITERAL:
553 subpatternappend(set[0]) # optimization
554 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
555 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000556 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000557 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000558 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000559
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300560 elif this in REPEAT_CHARS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000561 # repeat previous item
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200562 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000563 if this == "?":
564 min, max = 0, 1
565 elif this == "*":
566 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000567
Fredrik Lundh90a07912000-06-30 07:50:59 +0000568 elif this == "+":
569 min, max = 1, MAXREPEAT
570 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000571 if source.next == "}":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300572 subpatternappend((LITERAL, _ord(this)))
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000573 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000574 min, max = 0, MAXREPEAT
575 lo = hi = ""
576 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300577 lo += sourceget()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000578 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000579 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300580 hi += sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000581 else:
582 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000583 if not sourcematch("}"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300584 subpatternappend((LITERAL, _ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000585 source.seek(here)
586 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000587 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000588 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200589 if min >= MAXREPEAT:
590 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000591 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000592 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200593 if max >= MAXREPEAT:
594 raise OverflowError("the repetition number is too large")
595 if max < min:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200596 raise source.error("min repeat greater than max repeat",
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200597 source.tell() - here)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000598 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200599 raise AssertionError("unsupported quantifier %r" % (char,))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000600 # figure out which item to repeat
601 if subpattern:
602 item = subpattern[-1:]
603 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000604 item = None
Serhiy Storchakaab140882014-11-11 21:13:28 +0200605 if not item or (_len(item) == 1 and item[0][0] is AT):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200606 raise source.error("nothing to repeat",
607 source.tell() - here + len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300608 if item[0][0] in _REPEATCODES:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200609 raise source.error("multiple repeat",
610 source.tell() - here + len(this))
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000611 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000612 subpattern[-1] = (MIN_REPEAT, (min, max, item))
613 else:
614 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000615
Fredrik Lundh90a07912000-06-30 07:50:59 +0000616 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000617 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000618
Fredrik Lundh90a07912000-06-30 07:50:59 +0000619 elif this == "(":
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200620 start = source.tell() - 1
621 group = True
Fredrik Lundh90a07912000-06-30 07:50:59 +0000622 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000623 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000624 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000625 # options
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300626 char = sourceget()
627 if char is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200628 raise source.error("unexpected end of pattern")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300629 if char == "P":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000630 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000631 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000632 # named group: skip forward to end of name
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300633 name = source.getuntil(">")
Georg Brandl1d472b72013-04-14 11:40:00 +0200634 if not name.isidentifier():
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200635 msg = "bad character in group name %r" % name
636 raise source.error(msg, len(name) + 1)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000637 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000638 # named backreference
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300639 name = source.getuntil(")")
Georg Brandl1d472b72013-04-14 11:40:00 +0200640 if not name.isidentifier():
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200641 msg = "bad character in group name %r" % name
642 raise source.error(msg, len(name) + 1)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000643 gid = state.groupdict.get(name)
644 if gid is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200645 msg = "unknown group name %r" % name
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200646 raise source.error(msg, len(name) + 1)
Serhiy Storchaka485407c2015-07-18 23:27:00 +0300647 if not state.checkgroup(gid):
648 raise source.error("cannot refer to an open group",
649 len(name) + 1)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200650 state.checklookbehindgroup(gid, source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000651 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000652 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000653 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000654 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000655 if char is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200656 raise source.error("unexpected end of pattern")
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200657 raise source.error("unknown extension ?P" + char,
658 len(char) + 2)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300659 elif char == ":":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000660 # non-capturing group
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200661 group = None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300662 elif char == "#":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000663 # comment
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300664 while True:
665 if source.next is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200666 raise source.error("missing ), unterminated comment",
667 source.tell() - start)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300668 if sourceget() == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000669 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000670 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300671 elif char in "=!<":
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000672 # lookahead assertions
Fredrik Lundh6f013982000-07-03 18:44:21 +0000673 dir = 1
674 if char == "<":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300675 char = sourceget()
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200676 if char is None:
677 raise source.error("unexpected end of pattern")
678 if char not in "=!":
679 raise source.error("unknown extension ?<" + char,
680 len(char) + 2)
Fredrik Lundh6f013982000-07-03 18:44:21 +0000681 dir = -1 # lookbehind
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200682 lookbehindgroups = state.lookbehindgroups
683 if lookbehindgroups is None:
684 state.lookbehindgroups = state.groups
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000685 p = _parse_sub(source, state)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200686 if dir < 0:
687 if lookbehindgroups is None:
688 state.lookbehindgroups = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000689 if not sourcematch(")"):
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200690 raise source.error("missing ), unterminated subpattern",
691 source.tell() - start)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000692 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000693 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000694 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000695 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000696 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300697 elif char == "(":
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000698 # conditional backreference group
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300699 condname = source.getuntil(")")
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200700 group = None
Georg Brandl1d472b72013-04-14 11:40:00 +0200701 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000702 condgroup = state.groupdict.get(condname)
703 if condgroup is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200704 msg = "unknown group name %r" % condname
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200705 raise source.error(msg, len(condname) + 1)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000706 else:
707 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000708 condgroup = int(condname)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300709 if condgroup < 0:
710 raise ValueError
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000711 except ValueError:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200712 msg = "bad character in group name %r" % condname
713 raise source.error(msg, len(condname) + 1) from None
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300714 if not condgroup:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200715 raise source.error("bad group number",
716 len(condname) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300717 if condgroup >= MAXGROUPS:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200718 raise source.error("invalid group reference",
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200719 len(condname) + 1)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200720 state.checklookbehindgroup(condgroup, source)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300721 elif char in FLAGS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000722 # flags
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200723 while True:
724 state.flags |= FLAGS[char]
725 char = sourceget()
726 if char is None:
727 raise source.error("missing )")
728 if char == ")":
729 break
730 if char not in FLAGS:
731 raise source.error("unknown flag", len(char))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300732 verbose = state.flags & SRE_FLAG_VERBOSE
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200733 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300734 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200735 raise source.error("unknown extension ?" + char,
736 len(char) + 1)
737
738 # parse group contents
739 if group is not None:
740 try:
741 group = state.opengroup(name)
742 except error as err:
743 raise source.error(err.msg, len(name) + 1) from None
744 if condgroup:
745 p = _parse_sub_cond(source, state, condgroup)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000746 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200747 p = _parse_sub(source, state)
748 if not source.match(")"):
749 raise source.error("missing ), unterminated subpattern",
750 source.tell() - start)
751 if group is not None:
752 state.closegroup(group, p)
753 subpatternappend((SUBPATTERN, (group, p)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000754
Fredrik Lundh90a07912000-06-30 07:50:59 +0000755 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000756 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000757
Fredrik Lundh90a07912000-06-30 07:50:59 +0000758 elif this == "$":
759 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000760
Fredrik Lundh90a07912000-06-30 07:50:59 +0000761 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200762 raise AssertionError("unsupported special character %r" % (char,))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000763
764 return subpattern
765
Antoine Pitroufd036452008-08-19 17:56:33 +0000766def fix_flags(src, flags):
767 # Check and fix flags according to the type of pattern (str or bytes)
768 if isinstance(src, str):
Serhiy Storchaka22a309a2014-12-01 11:50:07 +0200769 if flags & SRE_FLAG_LOCALE:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300770 raise ValueError("cannot use LOCALE flag with a str pattern")
Antoine Pitroufd036452008-08-19 17:56:33 +0000771 if not flags & SRE_FLAG_ASCII:
772 flags |= SRE_FLAG_UNICODE
773 elif flags & SRE_FLAG_UNICODE:
774 raise ValueError("ASCII and UNICODE flags are incompatible")
775 else:
776 if flags & SRE_FLAG_UNICODE:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200777 raise ValueError("cannot use UNICODE flag with a bytes pattern")
Serhiy Storchaka22a309a2014-12-01 11:50:07 +0200778 if flags & SRE_FLAG_LOCALE and flags & SRE_FLAG_ASCII:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300779 raise ValueError("ASCII and LOCALE flags are incompatible")
Antoine Pitroufd036452008-08-19 17:56:33 +0000780 return flags
781
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000782def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000783 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000784
785 source = Tokenizer(str)
786
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000787 if pattern is None:
788 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000789 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000790 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000791
792 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000793 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000794
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300795 if source.next is not None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200796 assert source.next == ")"
797 raise source.error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000798
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000799 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
800 # the VERBOSE flag was switched on inside the pattern. to be
801 # on the safe side, we'll parse the whole thing again...
802 return parse(str, p.pattern.flags)
803
Serhiy Storchakaa01a1442016-03-06 09:15:47 +0200804 if flags & SRE_FLAG_DEBUG:
805 p.dump()
806
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000807 return p
808
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000809def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000810 # parse 're' replacement string into list of literals and
811 # group references
812 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000813 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300814 groups = []
815 literals = []
816 literal = []
817 lappend = literal.append
818 def addgroup(index):
819 if literal:
820 literals.append(''.join(literal))
821 del literal[:]
822 groups.append((len(literals), index))
823 literals.append(None)
Serhiy Storchaka07360df2015-03-30 01:01:48 +0300824 groupindex = pattern.groupindex
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300825 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000826 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000827 if this is None:
828 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300829 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000830 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300831 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000832 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000833 name = ""
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200834 if not s.match("<"):
835 raise s.error("missing <")
836 name = s.getuntil(">")
837 if name.isidentifier():
Fredrik Lundh90a07912000-06-30 07:50:59 +0000838 try:
Serhiy Storchaka07360df2015-03-30 01:01:48 +0300839 index = groupindex[name]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000840 except KeyError:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200841 raise IndexError("unknown group name %r" % name)
842 else:
843 try:
844 index = int(name)
845 if index < 0:
846 raise ValueError
847 except ValueError:
848 raise s.error("bad character in group name %r" % name,
849 len(name) + 1) from None
850 if index >= MAXGROUPS:
851 raise s.error("invalid group reference",
852 len(name) + 1)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300853 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000854 elif c == "0":
855 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300856 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000857 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300858 this += sget()
859 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000860 elif c in DIGITS:
861 isoctal = False
862 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300863 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000864 if (c in OCTDIGITS and this[2] in OCTDIGITS and
865 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300866 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000867 isoctal = True
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300868 c = int(this[1:], 8)
869 if c > 0o377:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200870 raise s.error('octal escape value %s outside of '
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200871 'range 0-0o377' % this, len(this))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300872 lappend(chr(c))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000873 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300874 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000875 else:
876 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300877 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000878 except KeyError:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200879 if c in ASCIILETTERS:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300880 raise s.error('bad escape %s' % this, len(this))
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300881 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000882 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300883 lappend(this)
884 if literal:
885 literals.append(''.join(literal))
886 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000887 # The tokenizer implicitly decodes bytes objects as latin-1, we must
888 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300889 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000890 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000891
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000892def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000893 g = match.group
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300894 empty = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000895 groups, literals = template
896 literals = literals[:]
897 try:
898 for index, group in groups:
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300899 literals[index] = g(group) or empty
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000900 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000901 raise error("invalid group reference")
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300902 return empty.join(literals)