blob: 83119168e6376ee83bb41f7b75d2c9a0cd3058d7 [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 Storchaka3557b052017-10-24 23:31:42 +030068TYPE_FLAGS = SRE_FLAG_ASCII | SRE_FLAG_LOCALE | SRE_FLAG_UNICODE
69GLOBAL_FLAGS = SRE_FLAG_DEBUG | SRE_FLAG_TEMPLATE
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +030070
71class Verbose(Exception):
72 pass
73
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +030074class State:
75 # keeps track of state for parsing
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
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +0300111 def __init__(self, state, data=None):
112 self.state = state
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
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300117
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000118 def dump(self, level=0):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300119 nl = True
Guido van Rossum13257902007-06-07 23:15:56 +0000120 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000121 for op, av in self.data:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200122 print(level*" " + str(op), end='')
Serhiy Storchakaab140882014-11-11 21:13:28 +0200123 if op is IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000124 # member sublanguage
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300125 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000126 for op, a in av:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200127 print((level+1)*" " + str(op), a)
Serhiy Storchakaab140882014-11-11 21:13:28 +0200128 elif op is BRANCH:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300129 print()
130 for i, a in enumerate(av[1]):
131 if i:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200132 print(level*" " + "OR")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300133 a.dump(level+1)
Serhiy Storchakaab140882014-11-11 21:13:28 +0200134 elif op is GROUPREF_EXISTS:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300135 condgroup, item_yes, item_no = av
136 print('', condgroup)
137 item_yes.dump(level+1)
138 if item_no:
Serhiy Storchakac7f7d382014-11-09 20:48:36 +0200139 print(level*" " + "ELSE")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300140 item_no.dump(level+1)
Guido van Rossum13257902007-06-07 23:15:56 +0000141 elif isinstance(av, seqtypes):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300142 nl = False
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000143 for a in av:
144 if isinstance(a, SubPattern):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300145 if not nl:
146 print()
147 a.dump(level+1)
148 nl = True
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000149 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300150 if not nl:
151 print(' ', end='')
152 print(a, end='')
153 nl = False
154 if not nl:
155 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000156 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300157 print('', av)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000158 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000159 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000160 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000161 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000162 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000163 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000164 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000165 if isinstance(index, slice):
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +0300166 return SubPattern(self.state, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000167 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000168 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000169 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000170 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000171 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000172 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000173 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000174 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000175 # determine the width (min, max) for this subpattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300176 if self.width is not None:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000177 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000178 lo = hi = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000179 for op, av in self.data:
180 if op is BRANCH:
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300181 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000182 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000183 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000184 l, h = av.getwidth()
185 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000186 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000187 lo = lo + i
188 hi = hi + j
189 elif op is CALL:
190 i, j = av.getwidth()
191 lo = lo + i
192 hi = hi + j
193 elif op is SUBPATTERN:
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300194 i, j = av[-1].getwidth()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000195 lo = lo + i
196 hi = hi + j
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300197 elif op in _REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000198 i, j = av[2].getwidth()
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300199 lo = lo + i * av[0]
200 hi = hi + j * av[1]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300201 elif op in _UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000202 lo = lo + 1
203 hi = hi + 1
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200204 elif op is GROUPREF:
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +0300205 i, j = self.state.groupwidths[av]
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200206 lo = lo + i
207 hi = hi + j
208 elif op is GROUPREF_EXISTS:
209 i, j = av[1].getwidth()
210 if av[2] is not None:
211 l, h = av[2].getwidth()
212 i = min(i, l)
213 j = max(j, h)
214 else:
215 i = 0
216 lo = lo + i
217 hi = hi + j
218 elif op is SUCCESS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000219 break
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300220 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000221 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000222
223class Tokenizer:
224 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200225 self.istext = isinstance(string, str)
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200226 self.string = string
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300227 if not self.istext:
228 string = str(string, 'latin1')
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200229 self.decoded_string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000230 self.index = 0
Serhiy Storchakab99c1322014-11-10 14:38:16 +0200231 self.next = None
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000232 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000233 def __next(self):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300234 index = self.index
235 try:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200236 char = self.decoded_string[index]
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300237 except IndexError:
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000238 self.next = None
239 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000240 if char == "\\":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300241 index += 1
Fredrik Lundh90a07912000-06-30 07:50:59 +0000242 try:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200243 char += self.decoded_string[index]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000244 except IndexError:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200245 raise error("bad escape (end of pattern)",
Serhiy Storchaka1b2004f2014-11-10 18:28:53 +0200246 self.string, len(self.string) - 1) from None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300247 self.index = index + 1
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000248 self.next = char
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300249 def match(self, char):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000250 if char == self.next:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300251 self.__next()
252 return True
253 return False
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000254 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000255 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000256 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000257 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200258 def getwhile(self, n, charset):
259 result = ''
260 for _ in range(n):
261 c = self.next
262 if c not in charset:
263 break
264 result += c
265 self.__next()
266 return result
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200267 def getuntil(self, terminator, name):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300268 result = ''
269 while True:
270 c = self.next
271 self.__next()
272 if c is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200273 if not result:
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200274 raise self.error("missing " + name)
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200275 raise self.error("missing %s, unterminated name" % terminator,
276 len(result))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300277 if c == terminator:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200278 if not result:
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200279 raise self.error("missing " + name, 1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300280 break
281 result += c
282 return result
Serhiy Storchakabd48d272016-09-11 12:50:02 +0300283 @property
284 def pos(self):
285 return self.index - len(self.next or '')
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000286 def tell(self):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200287 return self.index - len(self.next or '')
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000288 def seek(self, index):
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200289 self.index = index
290 self.__next()
291
292 def error(self, msg, offset=0):
293 return error(msg, self.string, self.tell() - offset)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000294
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000295def _class_escape(source, escape):
296 # handle escape code inside character class
297 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000298 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000299 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000300 code = CATEGORIES.get(escape)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300301 if code and code[0] is IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000302 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000303 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000304 c = escape[1:2]
305 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000306 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200307 escape += source.getwhile(2, HEXDIGITS)
308 if len(escape) != 4:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200309 raise source.error("incomplete escape %s" % escape, len(escape))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300310 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200311 elif c == "u" and source.istext:
312 # unicode escape (exactly four digits)
313 escape += source.getwhile(4, HEXDIGITS)
314 if len(escape) != 6:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200315 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200316 return LITERAL, int(escape[2:], 16)
317 elif c == "U" and source.istext:
318 # unicode escape (exactly eight digits)
319 escape += source.getwhile(8, HEXDIGITS)
320 if len(escape) != 10:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200321 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200322 c = int(escape[2:], 16)
323 chr(c) # raise ValueError for invalid code
324 return LITERAL, c
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200325 elif c == "N" and source.istext:
Zhou Fangyi5df52862018-02-10 06:59:29 +0000326 import unicodedata
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200327 # named unicode escape e.g. \N{EM DASH}
328 if not source.match('{'):
329 raise source.error("missing {")
330 charname = source.getuntil('}', 'character name')
331 try:
332 c = ord(unicodedata.lookup(charname))
333 except KeyError:
334 raise source.error("undefined character name %r" % charname,
335 len(charname) + len(r'\N{}'))
336 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000337 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000338 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200339 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300340 c = int(escape[1:], 8)
341 if c > 0o377:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200342 raise source.error('octal escape value %s outside of '
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200343 'range 0-0o377' % escape, len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300344 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000345 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200346 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000347 if len(escape) == 2:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200348 if c in ASCIILETTERS:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300349 raise source.error('bad escape %s' % escape, len(escape))
Fredrik Lundh0640e112000-06-30 13:55:15 +0000350 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000351 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000352 pass
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200353 raise source.error("bad escape %s" % escape, len(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000354
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000355def _escape(source, escape, state):
356 # handle escape code in expression
357 code = CATEGORIES.get(escape)
358 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000359 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000360 code = ESCAPES.get(escape)
361 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000362 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000363 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000364 c = escape[1:2]
365 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000366 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200367 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000368 if len(escape) != 4:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200369 raise source.error("incomplete escape %s" % escape, len(escape))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300370 return LITERAL, int(escape[2:], 16)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200371 elif c == "u" and source.istext:
372 # unicode escape (exactly four digits)
373 escape += source.getwhile(4, HEXDIGITS)
374 if len(escape) != 6:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200375 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200376 return LITERAL, int(escape[2:], 16)
377 elif c == "U" and source.istext:
378 # unicode escape (exactly eight digits)
379 escape += source.getwhile(8, HEXDIGITS)
380 if len(escape) != 10:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200381 raise source.error("incomplete escape %s" % escape, len(escape))
Antoine Pitrou463badf2012-06-23 13:29:19 +0200382 c = int(escape[2:], 16)
383 chr(c) # raise ValueError for invalid code
384 return LITERAL, c
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200385 elif c == "N" and source.istext:
Zhou Fangyi5df52862018-02-10 06:59:29 +0000386 import unicodedata
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200387 # named unicode escape e.g. \N{EM DASH}
388 if not source.match('{'):
389 raise source.error("missing {")
390 charname = source.getuntil('}', 'character name')
391 try:
392 c = ord(unicodedata.lookup(charname))
393 except KeyError:
394 raise source.error("undefined character name %r" % charname,
395 len(charname) + len(r'\N{}'))
396 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000397 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000398 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200399 escape += source.getwhile(2, OCTDIGITS)
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300400 return LITERAL, int(escape[1:], 8)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000401 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000402 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000403 if source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300404 escape += source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000405 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
406 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000407 # got three octal digits; this is an octal escape
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300408 escape += source.get()
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300409 c = int(escape[1:], 8)
410 if c > 0o377:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200411 raise source.error('octal escape value %s outside of '
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200412 'range 0-0o377' % escape,
413 len(escape))
Serhiy Storchakac563caf2014-09-23 23:22:41 +0300414 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000415 # not an octal escape, so this is a group reference
416 group = int(escape[1:])
417 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000418 if not state.checkgroup(group):
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200419 raise source.error("cannot refer to an open group",
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200420 len(escape))
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200421 state.checklookbehindgroup(group, source)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000422 return GROUPREF, group
Serhiy Storchaka662cef62016-10-23 12:11:19 +0300423 raise source.error("invalid group reference %d" % group, len(escape) - 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000424 if len(escape) == 2:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +0200425 if c in ASCIILETTERS:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300426 raise source.error("bad escape %s" % escape, len(escape))
Fredrik Lundh0640e112000-06-30 13:55:15 +0000427 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000428 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000429 pass
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200430 raise source.error("bad escape %s" % escape, len(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000431
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300432def _uniq(items):
yannvgn9f555512019-07-31 20:50:39 +0200433 return list(dict.fromkeys(items))
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300434
Serhiy Storchakac7ac7282017-05-16 15:16:15 +0300435def _parse_sub(source, state, verbose, nested):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000436 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000437
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000438 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000439 itemsappend = items.append
440 sourcematch = source.match
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200441 start = source.tell()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300442 while True:
Serhiy Storchakac7ac7282017-05-16 15:16:15 +0300443 itemsappend(_parse(source, state, verbose, nested + 1,
444 not nested and not items))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300445 if not sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000446 break
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000447
448 if len(items) == 1:
449 return items[0]
450
451 subpattern = SubPattern(state)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000452
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000453 # check if all items share a common prefix
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300454 while True:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000455 prefix = None
456 for item in items:
457 if not item:
458 break
459 if prefix is None:
460 prefix = item[0]
461 elif item[0] != prefix:
462 break
463 else:
464 # all subitems start with a common "prefix".
465 # move it out of the branch
466 for item in items:
467 del item[0]
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300468 subpattern.append(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000469 continue # check next one
470 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000471
472 # check if the branch can be replaced by a character set
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300473 set = []
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000474 for item in items:
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300475 if len(item) != 1:
476 break
477 op, av = item[0]
478 if op is LITERAL:
479 set.append((op, av))
480 elif op is IN and av[0][0] is not NEGATE:
481 set.extend(av)
482 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000483 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000484 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000485 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000486 # branch (the compiler may optimize this even more)
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300487 subpattern.append((IN, _uniq(set)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000488 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000489
490 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000491 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000492
Serhiy Storchakac7ac7282017-05-16 15:16:15 +0300493def _parse(source, state, verbose, nested, first=False):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000494 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000495 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000496
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000497 # precompute constants into local variables
498 subpatternappend = subpattern.append
499 sourceget = source.get
500 sourcematch = source.match
501 _len = len
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300502 _ord = ord
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000503
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300504 while True:
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000505
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300506 this = source.next
Fredrik Lundh90a07912000-06-30 07:50:59 +0000507 if this is None:
508 break # end of pattern
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300509 if this in "|)":
510 break # end of subpattern
511 sourceget()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000512
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300513 if verbose:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000514 # skip whitespace and comments
515 if this in WHITESPACE:
516 continue
517 if this == "#":
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 or this == "\n":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000521 break
522 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000523
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300524 if this[0] == "\\":
525 code = _escape(source, this, state)
526 subpatternappend(code)
527
528 elif this not in SPECIAL_CHARS:
529 subpatternappend((LITERAL, _ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000530
Fredrik Lundh90a07912000-06-30 07:50:59 +0000531 elif this == "[":
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200532 here = source.tell() - 1
Fredrik Lundh90a07912000-06-30 07:50:59 +0000533 # character set
534 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000535 setappend = set.append
536## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000537## pass # handle character classes
Serhiy Storchaka05cb7282017-11-16 12:38:26 +0200538 if source.next == '[':
539 import warnings
540 warnings.warn(
541 'Possible nested set at position %d' % source.tell(),
542 FutureWarning, stacklevel=nested + 6
543 )
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300544 negate = sourcematch("^")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000545 # check remaining characters
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300546 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000547 this = sourceget()
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300548 if this is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200549 raise source.error("unterminated character set",
550 source.tell() - here)
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300551 if this == "]" and set:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000552 break
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300553 elif this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000554 code1 = _class_escape(source, this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000555 else:
Serhiy Storchaka05cb7282017-11-16 12:38:26 +0200556 if set and this in '-&~|' and source.next == this:
557 import warnings
558 warnings.warn(
559 'Possible set %s at position %d' % (
560 'difference' if this == '-' else
561 'intersection' if this == '&' else
562 'symmetric difference' if this == '~' else
563 'union',
564 source.tell() - 1),
565 FutureWarning, stacklevel=nested + 6
566 )
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300567 code1 = LITERAL, _ord(this)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000568 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000569 # potential range
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200570 that = sourceget()
571 if that is None:
572 raise source.error("unterminated character set",
573 source.tell() - here)
574 if that == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000575 if code1[0] is IN:
576 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000577 setappend(code1)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300578 setappend((LITERAL, _ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000579 break
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200580 if that[0] == "\\":
581 code2 = _class_escape(source, that)
Guido van Rossum41c99e72003-04-14 17:59:34 +0000582 else:
Serhiy Storchaka05cb7282017-11-16 12:38:26 +0200583 if that == '-':
584 import warnings
585 warnings.warn(
586 'Possible set difference at position %d' % (
587 source.tell() - 2),
588 FutureWarning, stacklevel=nested + 6
589 )
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200590 code2 = LITERAL, _ord(that)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300591 if code1[0] != LITERAL or code2[0] != LITERAL:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200592 msg = "bad character range %s-%s" % (this, that)
593 raise source.error(msg, len(this) + 1 + len(that))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300594 lo = code1[1]
595 hi = code2[1]
596 if hi < lo:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200597 msg = "bad character range %s-%s" % (this, that)
598 raise source.error(msg, len(this) + 1 + len(that))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300599 setappend((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000600 else:
601 if code1[0] is IN:
602 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000603 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000604
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300605 set = _uniq(set)
Fredrik Lundh770617b2001-01-14 15:06:11 +0000606 # XXX: <fl> should move set optimization to compiler!
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300607 if _len(set) == 1 and set[0][0] is LITERAL:
608 # optimization
609 if negate:
610 subpatternappend((NOT_LITERAL, set[0][1]))
611 else:
612 subpatternappend(set[0])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000613 else:
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300614 if negate:
615 set.insert(0, (NEGATE, None))
616 # charmap optimization can't be added here because
617 # global flags still are not known
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000618 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000619
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300620 elif this in REPEAT_CHARS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000621 # repeat previous item
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200622 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000623 if this == "?":
624 min, max = 0, 1
625 elif this == "*":
626 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000627
Fredrik Lundh90a07912000-06-30 07:50:59 +0000628 elif this == "+":
629 min, max = 1, MAXREPEAT
630 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000631 if source.next == "}":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300632 subpatternappend((LITERAL, _ord(this)))
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000633 continue
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300634
Fredrik Lundh90a07912000-06-30 07:50:59 +0000635 min, max = 0, MAXREPEAT
636 lo = hi = ""
637 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300638 lo += sourceget()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000639 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000640 while source.next in DIGITS:
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300641 hi += sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000642 else:
643 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000644 if not sourcematch("}"):
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300645 subpatternappend((LITERAL, _ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000646 source.seek(here)
647 continue
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300648
Fredrik Lundh90a07912000-06-30 07:50:59 +0000649 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000650 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200651 if min >= MAXREPEAT:
652 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000653 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000654 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200655 if max >= MAXREPEAT:
656 raise OverflowError("the repetition number is too large")
657 if max < min:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200658 raise source.error("min repeat greater than max repeat",
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200659 source.tell() - here)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000660 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200661 raise AssertionError("unsupported quantifier %r" % (char,))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000662 # figure out which item to repeat
663 if subpattern:
664 item = subpattern[-1:]
665 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000666 item = None
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300667 if not item or item[0][0] is AT:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200668 raise source.error("nothing to repeat",
669 source.tell() - here + len(this))
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300670 if item[0][0] in _REPEATCODES:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200671 raise source.error("multiple repeat",
672 source.tell() - here + len(this))
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300673 if item[0][0] is SUBPATTERN:
674 group, add_flags, del_flags, p = item[0][1]
675 if group is None and not add_flags and not del_flags:
676 item = p
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000677 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000678 subpattern[-1] = (MIN_REPEAT, (min, max, item))
679 else:
680 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000681
Fredrik Lundh90a07912000-06-30 07:50:59 +0000682 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000683 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000684
Fredrik Lundh90a07912000-06-30 07:50:59 +0000685 elif this == "(":
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200686 start = source.tell() - 1
687 group = True
Fredrik Lundh90a07912000-06-30 07:50:59 +0000688 name = None
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300689 add_flags = 0
690 del_flags = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000691 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000692 # options
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300693 char = sourceget()
694 if char is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200695 raise source.error("unexpected end of pattern")
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300696 if char == "P":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000697 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000698 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000699 # named group: skip forward to end of name
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200700 name = source.getuntil(">", "group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200701 if not name.isidentifier():
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200702 msg = "bad character in group name %r" % name
703 raise source.error(msg, len(name) + 1)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000704 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000705 # named backreference
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200706 name = source.getuntil(")", "group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200707 if not name.isidentifier():
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200708 msg = "bad character in group name %r" % name
709 raise source.error(msg, len(name) + 1)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000710 gid = state.groupdict.get(name)
711 if gid is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200712 msg = "unknown group name %r" % name
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200713 raise source.error(msg, len(name) + 1)
Serhiy Storchaka485407c2015-07-18 23:27:00 +0300714 if not state.checkgroup(gid):
715 raise source.error("cannot refer to an open group",
716 len(name) + 1)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200717 state.checklookbehindgroup(gid, source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000718 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000719 continue
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300720
Fredrik Lundh90a07912000-06-30 07:50:59 +0000721 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000722 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000723 if char is None:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200724 raise source.error("unexpected end of pattern")
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200725 raise source.error("unknown extension ?P" + char,
726 len(char) + 2)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300727 elif char == ":":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000728 # non-capturing group
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200729 group = None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300730 elif char == "#":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000731 # comment
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300732 while True:
733 if source.next is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200734 raise source.error("missing ), unterminated comment",
735 source.tell() - start)
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300736 if sourceget() == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000737 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000738 continue
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300739
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300740 elif char in "=!<":
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000741 # lookahead assertions
Fredrik Lundh6f013982000-07-03 18:44:21 +0000742 dir = 1
743 if char == "<":
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300744 char = sourceget()
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200745 if char is None:
746 raise source.error("unexpected end of pattern")
747 if char not in "=!":
748 raise source.error("unknown extension ?<" + char,
749 len(char) + 2)
Fredrik Lundh6f013982000-07-03 18:44:21 +0000750 dir = -1 # lookbehind
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200751 lookbehindgroups = state.lookbehindgroups
752 if lookbehindgroups is None:
753 state.lookbehindgroups = state.groups
Serhiy Storchakac7ac7282017-05-16 15:16:15 +0300754 p = _parse_sub(source, state, verbose, nested + 1)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200755 if dir < 0:
756 if lookbehindgroups is None:
757 state.lookbehindgroups = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000758 if not sourcematch(")"):
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200759 raise source.error("missing ), unterminated subpattern",
760 source.tell() - start)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000761 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000762 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000763 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000764 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000765 continue
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300766
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300767 elif char == "(":
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000768 # conditional backreference group
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200769 condname = source.getuntil(")", "group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200770 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000771 condgroup = state.groupdict.get(condname)
772 if condgroup is None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200773 msg = "unknown group name %r" % condname
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200774 raise source.error(msg, len(condname) + 1)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000775 else:
776 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000777 condgroup = int(condname)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300778 if condgroup < 0:
779 raise ValueError
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000780 except ValueError:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200781 msg = "bad character in group name %r" % condname
782 raise source.error(msg, len(condname) + 1) from None
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300783 if not condgroup:
Serhiy Storchakaad446d52014-11-10 13:49:00 +0200784 raise source.error("bad group number",
785 len(condname) + 1)
Serhiy Storchaka9baa5b22014-09-29 22:49:23 +0300786 if condgroup >= MAXGROUPS:
Serhiy Storchaka662cef62016-10-23 12:11:19 +0300787 msg = "invalid group reference %d" % condgroup
788 raise source.error(msg, len(condname) + 1)
Serhiy Storchaka4eea62f2015-02-21 10:07:35 +0200789 state.checklookbehindgroup(condgroup, source)
Serhiy Storchakac7ac7282017-05-16 15:16:15 +0300790 item_yes = _parse(source, state, verbose, nested + 1)
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300791 if source.match("|"):
Serhiy Storchakac7ac7282017-05-16 15:16:15 +0300792 item_no = _parse(source, state, verbose, nested + 1)
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300793 if source.next == "|":
794 raise source.error("conditional backref with more than two branches")
795 else:
796 item_no = None
797 if not source.match(")"):
798 raise source.error("missing ), unterminated subpattern",
799 source.tell() - start)
800 subpatternappend((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
801 continue
802
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300803 elif char in FLAGS or char == "-":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000804 # flags
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300805 flags = _parse_flags(source, state, char)
806 if flags is None: # global flags
Serhiy Storchaka305ccbe2017-05-10 06:05:20 +0300807 if not first or subpattern:
Serhiy Storchakabd48d272016-09-11 12:50:02 +0300808 import warnings
Serhiy Storchakaabf275a2016-09-17 01:29:58 +0300809 warnings.warn(
Roy Williams171b9a32017-06-09 22:01:16 -0700810 'Flags not at the start of the expression %r%s' % (
Serhiy Storchakaabf275a2016-09-17 01:29:58 +0300811 source.string[:20], # truncate long regexes
812 ' (truncated)' if len(source.string) > 20 else '',
813 ),
Serhiy Storchakac7ac7282017-05-16 15:16:15 +0300814 DeprecationWarning, stacklevel=nested + 6
Serhiy Storchakaabf275a2016-09-17 01:29:58 +0300815 )
Serhiy Storchaka305ccbe2017-05-10 06:05:20 +0300816 if (state.flags & SRE_FLAG_VERBOSE) and not verbose:
817 raise Verbose
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300818 continue
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300819
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300820 add_flags, del_flags = flags
821 group = None
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300822 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200823 raise source.error("unknown extension ?" + char,
824 len(char) + 1)
825
826 # parse group contents
827 if group is not None:
828 try:
829 group = state.opengroup(name)
830 except error as err:
831 raise source.error(err.msg, len(name) + 1) from None
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300832 sub_verbose = ((verbose or (add_flags & SRE_FLAG_VERBOSE)) and
833 not (del_flags & SRE_FLAG_VERBOSE))
Serhiy Storchakac7ac7282017-05-16 15:16:15 +0300834 p = _parse_sub(source, state, sub_verbose, nested + 1)
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200835 if not source.match(")"):
836 raise source.error("missing ), unterminated subpattern",
837 source.tell() - start)
838 if group is not None:
839 state.closegroup(group, p)
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300840 subpatternappend((SUBPATTERN, (group, add_flags, del_flags, p)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000841
Fredrik Lundh90a07912000-06-30 07:50:59 +0000842 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000843 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000844
Fredrik Lundh90a07912000-06-30 07:50:59 +0000845 elif this == "$":
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300846 subpatternappend((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000847
Fredrik Lundh90a07912000-06-30 07:50:59 +0000848 else:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200849 raise AssertionError("unsupported special character %r" % (char,))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000850
Serhiy Storchaka821a9d12017-05-14 08:32:33 +0300851 # unpack non-capturing groups
852 for i in range(len(subpattern))[::-1]:
853 op, av = subpattern[i]
854 if op is SUBPATTERN:
855 group, add_flags, del_flags, p = av
856 if group is None and not add_flags and not del_flags:
857 subpattern[i: i+1] = p
858
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000859 return subpattern
860
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300861def _parse_flags(source, state, char):
862 sourceget = source.get
863 add_flags = 0
864 del_flags = 0
865 if char != "-":
866 while True:
Serhiy Storchaka3557b052017-10-24 23:31:42 +0300867 flag = FLAGS[char]
868 if source.istext:
869 if char == 'L':
870 msg = "bad inline flags: cannot use 'L' flag with a str pattern"
871 raise source.error(msg)
872 else:
873 if char == 'u':
874 msg = "bad inline flags: cannot use 'u' flag with a bytes pattern"
875 raise source.error(msg)
876 add_flags |= flag
877 if (flag & TYPE_FLAGS) and (add_flags & TYPE_FLAGS) != flag:
878 msg = "bad inline flags: flags 'a', 'u' and 'L' are incompatible"
879 raise source.error(msg)
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300880 char = sourceget()
881 if char is None:
882 raise source.error("missing -, : or )")
883 if char in ")-:":
884 break
885 if char not in FLAGS:
886 msg = "unknown flag" if char.isalpha() else "missing -, : or )"
887 raise source.error(msg, len(char))
888 if char == ")":
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300889 state.flags |= add_flags
890 return None
891 if add_flags & GLOBAL_FLAGS:
892 raise source.error("bad inline flags: cannot turn on global flag", 1)
893 if char == "-":
894 char = sourceget()
895 if char is None:
896 raise source.error("missing flag")
897 if char not in FLAGS:
898 msg = "unknown flag" if char.isalpha() else "missing flag"
899 raise source.error(msg, len(char))
900 while True:
Serhiy Storchaka3557b052017-10-24 23:31:42 +0300901 flag = FLAGS[char]
902 if flag & TYPE_FLAGS:
903 msg = "bad inline flags: cannot turn off flags 'a', 'u' and 'L'"
904 raise source.error(msg)
905 del_flags |= flag
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300906 char = sourceget()
907 if char is None:
908 raise source.error("missing :")
909 if char == ":":
910 break
911 if char not in FLAGS:
912 msg = "unknown flag" if char.isalpha() else "missing :"
913 raise source.error(msg, len(char))
914 assert char == ":"
915 if del_flags & GLOBAL_FLAGS:
916 raise source.error("bad inline flags: cannot turn off global flag", 1)
917 if add_flags & del_flags:
918 raise source.error("bad inline flags: flag turned on and off", 1)
919 return add_flags, del_flags
920
Antoine Pitroufd036452008-08-19 17:56:33 +0000921def fix_flags(src, flags):
922 # Check and fix flags according to the type of pattern (str or bytes)
923 if isinstance(src, str):
Serhiy Storchaka22a309a2014-12-01 11:50:07 +0200924 if flags & SRE_FLAG_LOCALE:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300925 raise ValueError("cannot use LOCALE flag with a str pattern")
Antoine Pitroufd036452008-08-19 17:56:33 +0000926 if not flags & SRE_FLAG_ASCII:
927 flags |= SRE_FLAG_UNICODE
928 elif flags & SRE_FLAG_UNICODE:
929 raise ValueError("ASCII and UNICODE flags are incompatible")
930 else:
931 if flags & SRE_FLAG_UNICODE:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200932 raise ValueError("cannot use UNICODE flag with a bytes pattern")
Serhiy Storchaka22a309a2014-12-01 11:50:07 +0200933 if flags & SRE_FLAG_LOCALE and flags & SRE_FLAG_ASCII:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +0300934 raise ValueError("ASCII and LOCALE flags are incompatible")
Antoine Pitroufd036452008-08-19 17:56:33 +0000935 return flags
936
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +0300937def parse(str, flags=0, state=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000938 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000939
940 source = Tokenizer(str)
941
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +0300942 if state is None:
943 state = State()
944 state.flags = flags
945 state.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000946
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300947 try:
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +0300948 p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300949 except Verbose:
950 # the VERBOSE flag was switched on inside the pattern. to be
951 # on the safe side, we'll parse the whole thing again...
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +0300952 state = State()
953 state.flags = flags | SRE_FLAG_VERBOSE
954 state.str = str
Serhiy Storchakad65cd092016-09-11 01:39:01 +0300955 source.seek(0)
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +0300956 p = _parse_sub(source, state, True, 0)
Serhiy Storchakabe9a4e52016-09-10 00:57:55 +0300957
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +0300958 p.state.flags = fix_flags(str, p.state.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000959
Serhiy Storchakae2ccf562014-10-10 11:14:49 +0300960 if source.next is not None:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200961 assert source.next == ")"
962 raise source.error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000963
Serhiy Storchakaa01a1442016-03-06 09:15:47 +0200964 if flags & SRE_FLAG_DEBUG:
965 p.dump()
966
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000967 return p
968
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +0300969def parse_template(source, state):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000970 # parse 're' replacement string into list of literals and
971 # group references
972 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000973 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300974 groups = []
975 literals = []
976 literal = []
977 lappend = literal.append
Serhiy Storchaka662cef62016-10-23 12:11:19 +0300978 def addgroup(index, pos):
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +0300979 if index > state.groups:
Serhiy Storchaka662cef62016-10-23 12:11:19 +0300980 raise s.error("invalid group reference %d" % index, pos)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300981 if literal:
982 literals.append(''.join(literal))
983 del literal[:]
984 groups.append((len(literals), index))
985 literals.append(None)
Serhiy Storchakae0c19dd2018-09-18 09:16:26 +0300986 groupindex = state.groupindex
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300987 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000988 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000989 if this is None:
990 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300991 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000992 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300993 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000994 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000995 name = ""
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200996 if not s.match("<"):
997 raise s.error("missing <")
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200998 name = s.getuntil(">", "group name")
Serhiy Storchaka632a77e2015-03-25 21:03:47 +0200999 if name.isidentifier():
Fredrik Lundh90a07912000-06-30 07:50:59 +00001000 try:
Serhiy Storchaka07360df2015-03-30 01:01:48 +03001001 index = groupindex[name]
Fredrik Lundh90a07912000-06-30 07:50:59 +00001002 except KeyError:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +02001003 raise IndexError("unknown group name %r" % name)
1004 else:
1005 try:
1006 index = int(name)
1007 if index < 0:
1008 raise ValueError
1009 except ValueError:
1010 raise s.error("bad character in group name %r" % name,
1011 len(name) + 1) from None
1012 if index >= MAXGROUPS:
Serhiy Storchaka662cef62016-10-23 12:11:19 +03001013 raise s.error("invalid group reference %d" % index,
Serhiy Storchaka632a77e2015-03-25 21:03:47 +02001014 len(name) + 1)
Serhiy Storchaka662cef62016-10-23 12:11:19 +03001015 addgroup(index, len(name) + 1)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +00001016 elif c == "0":
1017 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +03001018 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +00001019 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +03001020 this += sget()
1021 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +00001022 elif c in DIGITS:
1023 isoctal = False
1024 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +03001025 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +00001026 if (c in OCTDIGITS and this[2] in OCTDIGITS and
1027 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +03001028 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +00001029 isoctal = True
Serhiy Storchakac563caf2014-09-23 23:22:41 +03001030 c = int(this[1:], 8)
1031 if c > 0o377:
Serhiy Storchaka632a77e2015-03-25 21:03:47 +02001032 raise s.error('octal escape value %s outside of '
Serhiy Storchakaad446d52014-11-10 13:49:00 +02001033 'range 0-0o377' % this, len(this))
Serhiy Storchakac563caf2014-09-23 23:22:41 +03001034 lappend(chr(c))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +00001035 if not isoctal:
Serhiy Storchaka662cef62016-10-23 12:11:19 +03001036 addgroup(int(this[1:]), len(this) - 1)
Fredrik Lundh90a07912000-06-30 07:50:59 +00001037 else:
1038 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +03001039 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +00001040 except KeyError:
Serhiy Storchakaa54aae02015-03-24 22:58:14 +02001041 if c in ASCIILETTERS:
Serhiy Storchaka9bd85b82016-06-11 19:15:00 +03001042 raise s.error('bad escape %s' % this, len(this))
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +03001043 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +00001044 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +03001045 lappend(this)
1046 if literal:
1047 literals.append(''.join(literal))
1048 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +00001049 # The tokenizer implicitly decodes bytes objects as latin-1, we must
1050 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +03001051 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +00001052 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +00001053
Fredrik Lundh436c3d582000-06-29 08:58:44 +00001054def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +00001055 g = match.group
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +03001056 empty = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +00001057 groups, literals = template
1058 literals = literals[:]
1059 try:
1060 for index, group in groups:
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +03001061 literals[index] = g(group) or empty
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +00001062 except IndexError:
Serhiy Storchaka662cef62016-10-23 12:11:19 +03001063 raise error("invalid group reference %d" % index)
Serhiy Storchaka7438e4b2014-10-10 11:06:31 +03001064 return empty.join(literals)