blob: 6aa49c3bf6f8ed10ae27b05c8efa963d9b54552f [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
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +030068GLOBAL_FLAGS = (SRE_FLAG_ASCII | SRE_FLAG_LOCALE | SRE_FLAG_UNICODE |
69 SRE_FLAG_DEBUG | SRE_FLAG_TEMPLATE)
70
71class Verbose(Exception):
72 pass
73
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000074class Pattern:
75 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000076 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000077 self.flags = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +000078 self.groupdict = {}
Serhiy Storchakab5d0a212015-11-05 17:49:26 +020079 self.groupwidths = [None] # group 0
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +020080 self.lookbehindgroups = None
81 @property
82 def groups(self):
Serhiy Storchakab5d0a212015-11-05 17:49:26 +020083 return len(self.groupwidths)
Fredrik Lundhebc37b22000-10-28 19:30:41 +000084 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000085 gid = self.groups
Serhiy Storchakab5d0a212015-11-05 17:49:26 +020086 self.groupwidths.append(None)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +030087 if self.groups > MAXGROUPS:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +020088 raise error("too many groups")
Raymond Hettingerf13eb552002-06-02 00:40:05 +000089 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000090 ogid = self.groupdict.get(name, None)
91 if ogid is not None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +020092 raise error("redefinition of group name %r as group %d; "
93 "was group %d" % (name, gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000094 self.groupdict[name] = gid
95 return gid
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +020096 def closegroup(self, gid, p):
Serhiy Storchakab5d0a212015-11-05 17:49:26 +020097 self.groupwidths[gid] = p.getwidth()
Fredrik Lundhebc37b22000-10-28 19:30:41 +000098 def checkgroup(self, gid):
Serhiy Storchakab5d0a212015-11-05 17:49:26 +020099 return gid < self.groups and self.groupwidths[gid] is not None
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200100
101 def checklookbehindgroup(self, gid, source):
102 if self.lookbehindgroups is not None:
103 if not self.checkgroup(gid):
104 raise source.error('cannot refer to an open group')
105 if gid >= self.lookbehindgroups:
106 raise source.error('cannot refer to group defined in the same '
107 'lookbehind subpattern')
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000108
109class SubPattern:
110 # a subpattern, in intermediate form
111 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000112 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +0000113 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000114 data = []
115 self.data = data
116 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000117 def dump(self, level=0):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300118 nl = True
Guido van Rossum13257902007-06-07 23:15:56 +0000119 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000120 for op, av in self.data:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200121 print(level*" " + str(op), end='')
Serhiy Storchakaab140882014-11-11 21:13:28 +0200122 if op is IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000123 # member sublanguage
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300124 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000125 for op, a in av:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200126 print((level+1)*" " + str(op), a)
Serhiy Storchakaab140882014-11-11 21:13:28 +0200127 elif op is BRANCH:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300128 print()
129 for i, a in enumerate(av[1]):
130 if i:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200131 print(level*" " + "OR")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300132 a.dump(level+1)
Serhiy Storchakaab140882014-11-11 21:13:28 +0200133 elif op is GROUPREF_EXISTS:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300134 condgroup, item_yes, item_no = av
135 print('', condgroup)
136 item_yes.dump(level+1)
137 if item_no:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200138 print(level*" " + "ELSE")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300139 item_no.dump(level+1)
Guido van Rossum13257902007-06-07 23:15:56 +0000140 elif isinstance(av, seqtypes):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300141 nl = False
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000142 for a in av:
143 if isinstance(a, SubPattern):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300144 if not nl:
145 print()
146 a.dump(level+1)
147 nl = True
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000148 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300149 if not nl:
150 print(' ', end='')
151 print(a, end='')
152 nl = False
153 if not nl:
154 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000155 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300156 print('', av)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000157 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000158 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000159 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000160 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000161 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000162 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000163 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000164 if isinstance(index, slice):
165 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000166 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000167 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000168 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000169 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000170 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000171 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000172 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000173 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000174 # determine the width (min, max) for this subpattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300175 if self.width is not None:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000176 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000177 lo = hi = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000178 for op, av in self.data:
179 if op is BRANCH:
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300180 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000181 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000182 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000183 l, h = av.getwidth()
184 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000185 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000186 lo = lo + i
187 hi = hi + j
188 elif op is CALL:
189 i, j = av.getwidth()
190 lo = lo + i
191 hi = hi + j
192 elif op is SUBPATTERN:
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300193 i, j = av[-1].getwidth()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000194 lo = lo + i
195 hi = hi + j
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300196 elif op in _REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000197 i, j = av[2].getwidth()
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300198 lo = lo + i * av[0]
199 hi = hi + j * av[1]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300200 elif op in _UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000201 lo = lo + 1
202 hi = hi + 1
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200203 elif op is GROUPREF:
Serhiy Storchakab5d0a212015-11-05 17:49:26 +0200204 i, j = self.pattern.groupwidths[av]
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200205 lo = lo + i
206 hi = hi + j
207 elif op is GROUPREF_EXISTS:
208 i, j = av[1].getwidth()
209 if av[2] is not None:
210 l, h = av[2].getwidth()
211 i = min(i, l)
212 j = max(j, h)
213 else:
214 i = 0
215 lo = lo + i
216 hi = hi + j
217 elif op is SUCCESS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000218 break
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300219 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000220 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000221
222class Tokenizer:
223 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200224 self.istext = isinstance(string, str)
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200225 self.string = string
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300226 if not self.istext:
227 string = str(string, 'latin1')
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200228 self.decoded_string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000229 self.index = 0
Serhiy Storchakab99c1322014-11-10 14:38:16 +0200230 self.next = None
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000231 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000232 def __next(self):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300233 index = self.index
234 try:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200235 char = self.decoded_string[index]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300236 except IndexError:
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000237 self.next = None
238 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000239 if char == "\\":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300240 index += 1
Fredrik Lundh90a07912000-06-30 07:50:59 +0000241 try:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200242 char += self.decoded_string[index]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000243 except IndexError:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200244 raise error("bad escape (end of pattern)",
Serhiy Storchaka1b2004f2014-11-10 18:28:53 +0200245 self.string, len(self.string) - 1) from None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300246 self.index = index + 1
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000247 self.next = char
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300248 def match(self, char):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000249 if char == self.next:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300250 self.__next()
251 return True
252 return False
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000253 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000254 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000255 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000256 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200257 def getwhile(self, n, charset):
258 result = ''
259 for _ in range(n):
260 c = self.next
261 if c not in charset:
262 break
263 result += c
264 self.__next()
265 return result
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300266 def getuntil(self, terminator):
267 result = ''
268 while True:
269 c = self.next
270 self.__next()
271 if c is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200272 if not result:
273 raise self.error("missing group name")
274 raise self.error("missing %s, unterminated name" % terminator,
275 len(result))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300276 if c == terminator:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200277 if not result:
278 raise self.error("missing group name", 1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300279 break
280 result += c
281 return result
Serhiy Storchakabd48d272016-09-11 12:50:02 +0300282 @property
283 def pos(self):
284 return self.index - len(self.next or '')
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000285 def tell(self):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200286 return self.index - len(self.next or '')
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000287 def seek(self, index):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200288 self.index = index
289 self.__next()
290
291 def error(self, msg, offset=0):
292 return error(msg, self.string, self.tell() - offset)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000293
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000294def _class_escape(source, escape):
295 # handle escape code inside character class
296 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000297 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000298 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000299 code = CATEGORIES.get(escape)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300300 if code and code[0] is IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000301 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000302 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000303 c = escape[1:2]
304 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000305 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200306 escape += source.getwhile(2, HEXDIGITS)
307 if len(escape) != 4:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200308 raise source.error("incomplete escape %s" % escape, len(escape))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300309 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200310 elif c == "u" and source.istext:
311 # unicode escape (exactly four digits)
312 escape += source.getwhile(4, HEXDIGITS)
313 if len(escape) != 6:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200314 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200315 return LITERAL, int(escape[2:], 16)
316 elif c == "U" and source.istext:
317 # unicode escape (exactly eight digits)
318 escape += source.getwhile(8, HEXDIGITS)
319 if len(escape) != 10:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200320 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200321 c = int(escape[2:], 16)
322 chr(c) # raise ValueError for invalid code
323 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000324 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000325 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200326 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300327 c = int(escape[1:], 8)
328 if c > 0o377:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200329 raise source.error('octal escape value %s outside of '
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200330 'range 0-0o377' % escape, len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300331 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000332 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200333 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000334 if len(escape) == 2:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200335 if c in ASCIILETTERS:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300336 raise source.error('bad escape %s' % escape, len(escape))
Fredrik Lundh0640e112000-06-30 13:55:15 +0000337 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000338 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000339 pass
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200340 raise source.error("bad escape %s" % escape, len(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000341
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000342def _escape(source, escape, state):
343 # handle escape code in expression
344 code = CATEGORIES.get(escape)
345 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000346 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000347 code = ESCAPES.get(escape)
348 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000349 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000350 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000351 c = escape[1:2]
352 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000353 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200354 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000355 if len(escape) != 4:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200356 raise source.error("incomplete escape %s" % escape, len(escape))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300357 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200358 elif c == "u" and source.istext:
359 # unicode escape (exactly four digits)
360 escape += source.getwhile(4, HEXDIGITS)
361 if len(escape) != 6:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200362 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200363 return LITERAL, int(escape[2:], 16)
364 elif c == "U" and source.istext:
365 # unicode escape (exactly eight digits)
366 escape += source.getwhile(8, HEXDIGITS)
367 if len(escape) != 10:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200368 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200369 c = int(escape[2:], 16)
370 chr(c) # raise ValueError for invalid code
371 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000372 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000373 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200374 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300375 return LITERAL, int(escape[1:], 8)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000376 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000377 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000378 if source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300379 escape += source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000380 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
381 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000382 # got three octal digits; this is an octal escape
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300383 escape += source.get()
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300384 c = int(escape[1:], 8)
385 if c > 0o377:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200386 raise source.error('octal escape value %s outside of '
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200387 'range 0-0o377' % escape,
388 len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300389 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000390 # not an octal escape, so this is a group reference
391 group = int(escape[1:])
392 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000393 if not state.checkgroup(group):
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200394 raise source.error("cannot refer to an open group",
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200395 len(escape))
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200396 state.checklookbehindgroup(group, source)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000397 return GROUPREF, group
Serhiy Storchaka662cef62016-10-23 12:11:19 +0300398 raise source.error("invalid group reference %d" % group, len(escape) - 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000399 if len(escape) == 2:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200400 if c in ASCIILETTERS:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300401 raise source.error("bad escape %s" % escape, len(escape))
Fredrik Lundh0640e112000-06-30 13:55:15 +0000402 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000403 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000404 pass
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200405 raise source.error("bad escape %s" % escape, len(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000406
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300407def _parse_sub(source, state, verbose, nested=True):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000408 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000409
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000410 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000411 itemsappend = items.append
412 sourcematch = source.match
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200413 start = source.tell()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300414 while True:
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300415 itemsappend(_parse(source, state, verbose))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300416 if not sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000417 break
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000418
419 if len(items) == 1:
420 return items[0]
421
422 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000423 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000424
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000425 # check if all items share a common prefix
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300426 while True:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000427 prefix = None
428 for item in items:
429 if not item:
430 break
431 if prefix is None:
432 prefix = item[0]
433 elif item[0] != prefix:
434 break
435 else:
436 # all subitems start with a common "prefix".
437 # move it out of the branch
438 for item in items:
439 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000440 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000441 continue # check next one
442 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000443
444 # check if the branch can be replaced by a character set
445 for item in items:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300446 if len(item) != 1 or item[0][0] is not LITERAL:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000447 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000448 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000449 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000450 # branch (the compiler may optimize this even more)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300451 subpatternappend((IN, [item[0] for item in items]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000452 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000453
454 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000455 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000456
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300457def _parse_sub_cond(source, state, condgroup, verbose):
458 item_yes = _parse(source, state, verbose)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000459 if source.match("|"):
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300460 item_no = _parse(source, state, verbose)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300461 if source.next == "|":
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200462 raise source.error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000463 else:
464 item_no = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000465 subpattern = SubPattern(state)
466 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
467 return subpattern
468
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300469def _parse(source, state, verbose):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000470 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000471 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000472
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000473 # precompute constants into local variables
474 subpatternappend = subpattern.append
475 sourceget = source.get
476 sourcematch = source.match
477 _len = len
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300478 _ord = ord
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000479
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300480 while True:
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000481
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300482 this = source.next
Fredrik Lundh90a07912000-06-30 07:50:59 +0000483 if this is None:
484 break # end of pattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300485 if this in "|)":
486 break # end of subpattern
487 sourceget()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000488
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300489 if verbose:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000490 # skip whitespace and comments
491 if this in WHITESPACE:
492 continue
493 if this == "#":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300494 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000495 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300496 if this is None or this == "\n":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000497 break
498 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000499
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300500 if this[0] == "\\":
501 code = _escape(source, this, state)
502 subpatternappend(code)
503
504 elif this not in SPECIAL_CHARS:
505 subpatternappend((LITERAL, _ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000506
Fredrik Lundh90a07912000-06-30 07:50:59 +0000507 elif this == "[":
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200508 here = source.tell() - 1
Fredrik Lundh90a07912000-06-30 07:50:59 +0000509 # character set
510 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000511 setappend = set.append
512## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000513## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000514 if sourcematch("^"):
515 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000516 # check remaining characters
517 start = set[:]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300518 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000519 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300520 if this is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200521 raise source.error("unterminated character set",
522 source.tell() - here)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000523 if this == "]" and set != start:
524 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300525 elif this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000526 code1 = _class_escape(source, this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000527 else:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300528 code1 = LITERAL, _ord(this)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000529 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000530 # potential range
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200531 that = sourceget()
532 if that is None:
533 raise source.error("unterminated character set",
534 source.tell() - here)
535 if that == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000536 if code1[0] is IN:
537 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000538 setappend(code1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300539 setappend((LITERAL, _ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000540 break
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200541 if that[0] == "\\":
542 code2 = _class_escape(source, that)
Guido van Rossum41c99e72003-04-14 17:59:34 +0000543 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200544 code2 = LITERAL, _ord(that)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300545 if code1[0] != LITERAL or code2[0] != LITERAL:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200546 msg = "bad character range %s-%s" % (this, that)
547 raise source.error(msg, len(this) + 1 + len(that))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300548 lo = code1[1]
549 hi = code2[1]
550 if hi < lo:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200551 msg = "bad character range %s-%s" % (this, that)
552 raise source.error(msg, len(this) + 1 + len(that))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300553 setappend((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000554 else:
555 if code1[0] is IN:
556 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000557 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000558
Fredrik Lundh770617b2001-01-14 15:06:11 +0000559 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000560 if _len(set)==1 and set[0][0] is LITERAL:
561 subpatternappend(set[0]) # optimization
562 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
563 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000564 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000565 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000566 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000567
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300568 elif this in REPEAT_CHARS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000569 # repeat previous item
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200570 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000571 if this == "?":
572 min, max = 0, 1
573 elif this == "*":
574 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000575
Fredrik Lundh90a07912000-06-30 07:50:59 +0000576 elif this == "+":
577 min, max = 1, MAXREPEAT
578 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000579 if source.next == "}":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300580 subpatternappend((LITERAL, _ord(this)))
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000581 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000582 min, max = 0, MAXREPEAT
583 lo = hi = ""
584 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300585 lo += sourceget()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000586 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000587 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300588 hi += sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000589 else:
590 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000591 if not sourcematch("}"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300592 subpatternappend((LITERAL, _ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000593 source.seek(here)
594 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000595 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000596 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200597 if min >= MAXREPEAT:
598 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000599 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000600 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200601 if max >= MAXREPEAT:
602 raise OverflowError("the repetition number is too large")
603 if max < min:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200604 raise source.error("min repeat greater than max repeat",
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200605 source.tell() - here)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000606 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200607 raise AssertionError("unsupported quantifier %r" % (char,))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000608 # figure out which item to repeat
609 if subpattern:
610 item = subpattern[-1:]
611 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000612 item = None
Serhiy Storchakaab140882014-11-11 21:13:28 +0200613 if not item or (_len(item) == 1 and item[0][0] is AT):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200614 raise source.error("nothing to repeat",
615 source.tell() - here + len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300616 if item[0][0] in _REPEATCODES:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200617 raise source.error("multiple repeat",
618 source.tell() - here + len(this))
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000619 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000620 subpattern[-1] = (MIN_REPEAT, (min, max, item))
621 else:
622 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000623
Fredrik Lundh90a07912000-06-30 07:50:59 +0000624 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000625 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000626
Fredrik Lundh90a07912000-06-30 07:50:59 +0000627 elif this == "(":
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200628 start = source.tell() - 1
629 group = True
Fredrik Lundh90a07912000-06-30 07:50:59 +0000630 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000631 condgroup = None
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300632 add_flags = 0
633 del_flags = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000634 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000635 # options
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300636 char = sourceget()
637 if char is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200638 raise source.error("unexpected end of pattern")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300639 if char == "P":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000640 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000641 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000642 # named group: skip forward to end of name
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300643 name = source.getuntil(">")
Georg Brandl1d472b72013-04-14 11:40:00 +0200644 if not name.isidentifier():
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200645 msg = "bad character in group name %r" % name
646 raise source.error(msg, len(name) + 1)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000647 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000648 # named backreference
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300649 name = source.getuntil(")")
Georg Brandl1d472b72013-04-14 11:40:00 +0200650 if not name.isidentifier():
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200651 msg = "bad character in group name %r" % name
652 raise source.error(msg, len(name) + 1)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000653 gid = state.groupdict.get(name)
654 if gid is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200655 msg = "unknown group name %r" % name
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200656 raise source.error(msg, len(name) + 1)
Serhiy Storchaka485407c2015-07-18 23:27:00 +0300657 if not state.checkgroup(gid):
658 raise source.error("cannot refer to an open group",
659 len(name) + 1)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200660 state.checklookbehindgroup(gid, source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000661 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000662 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000663 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000664 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000665 if char is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200666 raise source.error("unexpected end of pattern")
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200667 raise source.error("unknown extension ?P" + char,
668 len(char) + 2)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300669 elif char == ":":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000670 # non-capturing group
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200671 group = None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300672 elif char == "#":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000673 # comment
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300674 while True:
675 if source.next is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200676 raise source.error("missing ), unterminated comment",
677 source.tell() - start)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300678 if sourceget() == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000679 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000680 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300681 elif char in "=!<":
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000682 # lookahead assertions
Fredrik Lundh6f013982000-07-03 18:44:21 +0000683 dir = 1
684 if char == "<":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300685 char = sourceget()
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200686 if char is None:
687 raise source.error("unexpected end of pattern")
688 if char not in "=!":
689 raise source.error("unknown extension ?<" + char,
690 len(char) + 2)
Fredrik Lundh6f013982000-07-03 18:44:21 +0000691 dir = -1 # lookbehind
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200692 lookbehindgroups = state.lookbehindgroups
693 if lookbehindgroups is None:
694 state.lookbehindgroups = state.groups
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300695 p = _parse_sub(source, state, verbose)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200696 if dir < 0:
697 if lookbehindgroups is None:
698 state.lookbehindgroups = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000699 if not sourcematch(")"):
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200700 raise source.error("missing ), unterminated subpattern",
701 source.tell() - start)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000702 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000703 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000704 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000705 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000706 continue
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300707 elif char == "(":
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000708 # conditional backreference group
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300709 condname = source.getuntil(")")
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200710 group = None
Georg Brandl1d472b72013-04-14 11:40:00 +0200711 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000712 condgroup = state.groupdict.get(condname)
713 if condgroup is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200714 msg = "unknown group name %r" % condname
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200715 raise source.error(msg, len(condname) + 1)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000716 else:
717 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000718 condgroup = int(condname)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300719 if condgroup < 0:
720 raise ValueError
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000721 except ValueError:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200722 msg = "bad character in group name %r" % condname
723 raise source.error(msg, len(condname) + 1) from None
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300724 if not condgroup:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200725 raise source.error("bad group number",
726 len(condname) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300727 if condgroup >= MAXGROUPS:
Serhiy Storchaka662cef62016-10-23 12:11:19 +0300728 msg = "invalid group reference %d" % condgroup
729 raise source.error(msg, len(condname) + 1)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200730 state.checklookbehindgroup(condgroup, source)
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300731 elif char in FLAGS or char == "-":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000732 # flags
Serhiy Storchakabd48d272016-09-11 12:50:02 +0300733 pos = source.pos
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300734 flags = _parse_flags(source, state, char)
735 if flags is None: # global flags
Serhiy Storchakabd48d272016-09-11 12:50:02 +0300736 if pos != 3: # "(?x"
737 import warnings
Serhiy Storchakaabf275a2016-09-17 01:29:58 +0300738 warnings.warn(
739 'Flags not at the start of the expression %s%s' % (
740 source.string[:20], # truncate long regexes
741 ' (truncated)' if len(source.string) > 20 else '',
742 ),
743 DeprecationWarning, stacklevel=7
744 )
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300745 continue
746 add_flags, del_flags = flags
747 group = None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300748 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200749 raise source.error("unknown extension ?" + char,
750 len(char) + 1)
751
752 # parse group contents
753 if group is not None:
754 try:
755 group = state.opengroup(name)
756 except error as err:
757 raise source.error(err.msg, len(name) + 1) from None
758 if condgroup:
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300759 p = _parse_sub_cond(source, state, condgroup, verbose)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000760 else:
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300761 sub_verbose = ((verbose or (add_flags & SRE_FLAG_VERBOSE)) and
762 not (del_flags & SRE_FLAG_VERBOSE))
763 p = _parse_sub(source, state, sub_verbose)
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200764 if not source.match(")"):
765 raise source.error("missing ), unterminated subpattern",
766 source.tell() - start)
767 if group is not None:
768 state.closegroup(group, p)
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300769 subpatternappend((SUBPATTERN, (group, add_flags, del_flags, p)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000770
Fredrik Lundh90a07912000-06-30 07:50:59 +0000771 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000772 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000773
Fredrik Lundh90a07912000-06-30 07:50:59 +0000774 elif this == "$":
775 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000776
Fredrik Lundh90a07912000-06-30 07:50:59 +0000777 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200778 raise AssertionError("unsupported special character %r" % (char,))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000779
780 return subpattern
781
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300782def _parse_flags(source, state, char):
783 sourceget = source.get
784 add_flags = 0
785 del_flags = 0
786 if char != "-":
787 while True:
788 add_flags |= FLAGS[char]
789 char = sourceget()
790 if char is None:
791 raise source.error("missing -, : or )")
792 if char in ")-:":
793 break
794 if char not in FLAGS:
795 msg = "unknown flag" if char.isalpha() else "missing -, : or )"
796 raise source.error(msg, len(char))
797 if char == ")":
798 if ((add_flags & SRE_FLAG_VERBOSE) and
799 not (state.flags & SRE_FLAG_VERBOSE)):
800 raise Verbose
801 state.flags |= add_flags
802 return None
803 if add_flags & GLOBAL_FLAGS:
804 raise source.error("bad inline flags: cannot turn on global flag", 1)
805 if char == "-":
806 char = sourceget()
807 if char is None:
808 raise source.error("missing flag")
809 if char not in FLAGS:
810 msg = "unknown flag" if char.isalpha() else "missing flag"
811 raise source.error(msg, len(char))
812 while True:
813 del_flags |= FLAGS[char]
814 char = sourceget()
815 if char is None:
816 raise source.error("missing :")
817 if char == ":":
818 break
819 if char not in FLAGS:
820 msg = "unknown flag" if char.isalpha() else "missing :"
821 raise source.error(msg, len(char))
822 assert char == ":"
823 if del_flags & GLOBAL_FLAGS:
824 raise source.error("bad inline flags: cannot turn off global flag", 1)
825 if add_flags & del_flags:
826 raise source.error("bad inline flags: flag turned on and off", 1)
827 return add_flags, del_flags
828
Antoine Pitroufd036452008-08-19 17:56:33 +0000829def fix_flags(src, flags):
830 # Check and fix flags according to the type of pattern (str or bytes)
831 if isinstance(src, str):
Serhiy Storchaka22a309a2014-12-01 11:50:07 +0200832 if flags & SRE_FLAG_LOCALE:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300833 raise ValueError("cannot use LOCALE flag with a str pattern")
Antoine Pitroufd036452008-08-19 17:56:33 +0000834 if not flags & SRE_FLAG_ASCII:
835 flags |= SRE_FLAG_UNICODE
836 elif flags & SRE_FLAG_UNICODE:
837 raise ValueError("ASCII and UNICODE flags are incompatible")
838 else:
839 if flags & SRE_FLAG_UNICODE:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200840 raise ValueError("cannot use UNICODE flag with a bytes pattern")
Serhiy Storchaka22a309a2014-12-01 11:50:07 +0200841 if flags & SRE_FLAG_LOCALE and flags & SRE_FLAG_ASCII:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300842 raise ValueError("ASCII and LOCALE flags are incompatible")
Antoine Pitroufd036452008-08-19 17:56:33 +0000843 return flags
844
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000845def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000846 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000847
848 source = Tokenizer(str)
849
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000850 if pattern is None:
851 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000852 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000853 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000854
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300855 try:
856 p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, False)
857 except Verbose:
858 # the VERBOSE flag was switched on inside the pattern. to be
859 # on the safe side, we'll parse the whole thing again...
860 pattern = Pattern()
861 pattern.flags = flags | SRE_FLAG_VERBOSE
862 pattern.str = str
Serhiy Storchakad65cd092016-09-11 01:39:01 +0300863 source.seek(0)
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300864 p = _parse_sub(source, pattern, True, False)
865
Antoine Pitroufd036452008-08-19 17:56:33 +0000866 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000867
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300868 if source.next is not None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200869 assert source.next == ")"
870 raise source.error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000871
Serhiy Storchakaa01a1442016-03-06 09:15:47 +0200872 if flags & SRE_FLAG_DEBUG:
873 p.dump()
874
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000875 return p
876
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000877def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000878 # parse 're' replacement string into list of literals and
879 # group references
880 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000881 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300882 groups = []
883 literals = []
884 literal = []
885 lappend = literal.append
Serhiy Storchaka662cef62016-10-23 12:11:19 +0300886 def addgroup(index, pos):
887 if index > pattern.groups:
888 raise s.error("invalid group reference %d" % index, pos)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300889 if literal:
890 literals.append(''.join(literal))
891 del literal[:]
892 groups.append((len(literals), index))
893 literals.append(None)
Serhiy Storchaka07360df2015-03-30 01:01:48 +0300894 groupindex = pattern.groupindex
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300895 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000896 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000897 if this is None:
898 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300899 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000900 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300901 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000902 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000903 name = ""
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200904 if not s.match("<"):
905 raise s.error("missing <")
906 name = s.getuntil(">")
907 if name.isidentifier():
Fredrik Lundh90a07912000-06-30 07:50:59 +0000908 try:
Serhiy Storchaka07360df2015-03-30 01:01:48 +0300909 index = groupindex[name]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000910 except KeyError:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200911 raise IndexError("unknown group name %r" % name)
912 else:
913 try:
914 index = int(name)
915 if index < 0:
916 raise ValueError
917 except ValueError:
918 raise s.error("bad character in group name %r" % name,
919 len(name) + 1) from None
920 if index >= MAXGROUPS:
Serhiy Storchaka662cef62016-10-23 12:11:19 +0300921 raise s.error("invalid group reference %d" % index,
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200922 len(name) + 1)
Serhiy Storchaka662cef62016-10-23 12:11:19 +0300923 addgroup(index, len(name) + 1)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000924 elif c == "0":
925 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300926 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000927 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300928 this += sget()
929 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000930 elif c in DIGITS:
931 isoctal = False
932 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300933 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000934 if (c in OCTDIGITS and this[2] in OCTDIGITS and
935 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300936 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000937 isoctal = True
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300938 c = int(this[1:], 8)
939 if c > 0o377:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200940 raise s.error('octal escape value %s outside of '
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200941 'range 0-0o377' % this, len(this))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300942 lappend(chr(c))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000943 if not isoctal:
Serhiy Storchaka662cef62016-10-23 12:11:19 +0300944 addgroup(int(this[1:]), len(this) - 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000945 else:
946 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300947 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000948 except KeyError:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200949 if c in ASCIILETTERS:
Serhiy Storchaka53c53ea2016-12-06 19:15:29 +0200950 import warnings
951 warnings.warn('bad escape %s' % this,
952 DeprecationWarning, stacklevel=4)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300953 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000954 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300955 lappend(this)
956 if literal:
957 literals.append(''.join(literal))
958 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000959 # The tokenizer implicitly decodes bytes objects as latin-1, we must
960 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300961 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000962 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000963
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000964def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000965 g = match.group
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300966 empty = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000967 groups, literals = template
968 literals = literals[:]
969 try:
970 for index, group in groups:
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300971 literals[index] = g(group) or empty
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000972 except IndexError:
Serhiy Storchaka662cef62016-10-23 12:11:19 +0300973 raise error("invalid group reference %d" % index)
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +0300974 return empty.join(literals)