blob: df1e6437c7dbb40d6c495016a8736f968b28f0b1 [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 *
Serhiy Storchaka70ca0212013-02-16 16:47:47 +020016from _sre import MAXREPEAT
Guido van Rossum7627c0d2000-03-31 14:58:54 +000017
18SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000019REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000020
Raymond Hettinger049ade22005-02-28 19:27:52 +000021DIGITS = set("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000022
Raymond Hettinger049ade22005-02-28 19:27:52 +000023OCTDIGITS = set("01234567")
24HEXDIGITS = set("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000025
Raymond Hettinger049ade22005-02-28 19:27:52 +000026WHITESPACE = set(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000027
Guido van Rossum7627c0d2000-03-31 14:58:54 +000028ESCAPES = {
Fredrik Lundhf2989b22001-02-18 12:05:16 +000029 r"\a": (LITERAL, ord("\a")),
30 r"\b": (LITERAL, ord("\b")),
31 r"\f": (LITERAL, ord("\f")),
32 r"\n": (LITERAL, ord("\n")),
33 r"\r": (LITERAL, ord("\r")),
34 r"\t": (LITERAL, ord("\t")),
35 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000036 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000037}
38
39CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000040 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000041 r"\b": (AT, AT_BOUNDARY),
42 r"\B": (AT, AT_NON_BOUNDARY),
43 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
44 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
45 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
46 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
47 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
48 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000049 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000050}
51
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000052FLAGS = {
Fredrik Lundh436c3d582000-06-29 08:58:44 +000053 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000054 "i": SRE_FLAG_IGNORECASE,
55 "L": SRE_FLAG_LOCALE,
56 "m": SRE_FLAG_MULTILINE,
57 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000058 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000059 # extensions
Antoine Pitroufd036452008-08-19 17:56:33 +000060 "a": SRE_FLAG_ASCII,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000061 "t": SRE_FLAG_TEMPLATE,
62 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000063}
64
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000065class Pattern:
66 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000067 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000068 self.flags = 0
Benjamin Peterson66323412014-11-30 11:49:00 -050069 self.open = []
70 self.groups = 1
Fredrik Lundh90a07912000-06-30 07:50:59 +000071 self.groupdict = {}
Serhiy Storchakaa3369a52015-02-21 12:08:52 +020072 self.lookbehind = 0
73
Fredrik Lundhebc37b22000-10-28 19:30:41 +000074 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000075 gid = self.groups
Benjamin Peterson66323412014-11-30 11:49:00 -050076 self.groups = gid + 1
Raymond Hettingerf13eb552002-06-02 00:40:05 +000077 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000078 ogid = self.groupdict.get(name, None)
79 if ogid is not None:
Collin Winterce36ad82007-08-30 01:19:48 +000080 raise error("redefinition of group name %s as group %d; "
81 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000082 self.groupdict[name] = gid
Benjamin Peterson66323412014-11-30 11:49:00 -050083 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000084 return gid
Benjamin Peterson66323412014-11-30 11:49:00 -050085 def closegroup(self, gid):
86 self.open.remove(gid)
Fredrik Lundhebc37b22000-10-28 19:30:41 +000087 def checkgroup(self, gid):
Benjamin Peterson66323412014-11-30 11:49:00 -050088 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000089
90class SubPattern:
91 # a subpattern, in intermediate form
92 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000093 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000094 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000095 data = []
96 self.data = data
97 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000098 def dump(self, level=0):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +030099 nl = True
Guido van Rossum13257902007-06-07 23:15:56 +0000100 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000101 for op, av in self.data:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300102 print(level*" " + op, end='')
103 if op == IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000104 # member sublanguage
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300105 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000106 for op, a in av:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000107 print((level+1)*" " + op, a)
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300108 elif op == BRANCH:
109 print()
110 for i, a in enumerate(av[1]):
111 if i:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000112 print(level*" " + "or")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300113 a.dump(level+1)
114 elif op == GROUPREF_EXISTS:
115 condgroup, item_yes, item_no = av
116 print('', condgroup)
117 item_yes.dump(level+1)
118 if item_no:
119 print(level*" " + "else")
120 item_no.dump(level+1)
Guido van Rossum13257902007-06-07 23:15:56 +0000121 elif isinstance(av, seqtypes):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300122 nl = False
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000123 for a in av:
124 if isinstance(a, SubPattern):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300125 if not nl:
126 print()
127 a.dump(level+1)
128 nl = True
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000129 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300130 if not nl:
131 print(' ', end='')
132 print(a, end='')
133 nl = False
134 if not nl:
135 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000136 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300137 print('', av)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000138 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000139 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000140 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000141 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000142 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000143 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000144 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000145 if isinstance(index, slice):
146 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000147 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000148 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000149 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000150 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000151 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000152 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000153 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000154 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000155 # determine the width (min, max) for this subpattern
156 if self.width:
157 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000158 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000159 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
160 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000161 for op, av in self.data:
162 if op is BRANCH:
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300163 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000164 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000165 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000166 l, h = av.getwidth()
167 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000168 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000169 lo = lo + i
170 hi = hi + j
171 elif op is CALL:
172 i, j = av.getwidth()
173 lo = lo + i
174 hi = hi + j
175 elif op is SUBPATTERN:
176 i, j = av[1].getwidth()
177 lo = lo + i
178 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000179 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000180 i, j = av[2].getwidth()
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300181 lo = lo + i * av[0]
182 hi = hi + j * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000183 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000184 lo = lo + 1
185 hi = hi + 1
Benjamin Peterson66323412014-11-30 11:49:00 -0500186 elif op == SUCCESS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000187 break
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300188 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000189 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000190
191class Tokenizer:
192 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200193 self.istext = isinstance(string, str)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000194 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000195 self.index = 0
196 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000197 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000198 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000199 self.next = None
200 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000201 char = self.string[self.index:self.index+1]
202 # Special case for the str8, since indexing returns a integer
203 # XXX This is only needed for test_bug_926075 in test_re.py
Antoine Pitrou463badf2012-06-23 13:29:19 +0200204 if char and not self.istext:
Thomas Wouters40a088d2008-03-18 20:19:54 +0000205 char = chr(char[0])
Guido van Rossum75a902d2007-10-19 22:06:24 +0000206 if char == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000207 try:
208 c = self.string[self.index + 1]
209 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000210 raise error("bogus escape (end of line)")
Antoine Pitrou463badf2012-06-23 13:29:19 +0200211 if not self.istext:
Antoine Pitrou22628c42008-07-22 17:53:22 +0000212 c = chr(c)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000213 char = char + c
214 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000215 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000216 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000217 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000218 if skip:
219 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000220 return 1
221 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000222 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000223 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000224 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000225 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200226 def getwhile(self, n, charset):
227 result = ''
228 for _ in range(n):
229 c = self.next
230 if c not in charset:
231 break
232 result += c
233 self.__next()
234 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000235 def tell(self):
236 return self.index, self.next
237 def seek(self, index):
238 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000239
Georg Brandl1d472b72013-04-14 11:40:00 +0200240# The following three functions are not used in this module anymore, but we keep
241# them here (with DeprecationWarnings) for backwards compatibility.
242
Fredrik Lundh4781b072000-06-29 12:38:45 +0000243def isident(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200244 import warnings
245 warnings.warn('sre_parse.isident() will be removed in 3.5',
246 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000247 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
248
249def isdigit(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200250 import warnings
251 warnings.warn('sre_parse.isdigit() will be removed in 3.5',
252 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000253 return "0" <= char <= "9"
254
255def isname(name):
Georg Brandl1d472b72013-04-14 11:40:00 +0200256 import warnings
257 warnings.warn('sre_parse.isname() will be removed in 3.5',
258 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000259 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000260 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000261 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000262 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000263 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000264 return False
265 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000266
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000267def _class_escape(source, escape):
268 # handle escape code inside character class
269 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000270 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000271 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000272 code = CATEGORIES.get(escape)
Ezio Melottife8e6e72013-01-11 08:32:01 +0200273 if code and code[0] == IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000274 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000275 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000276 c = escape[1:2]
277 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000278 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200279 escape += source.getwhile(2, HEXDIGITS)
280 if len(escape) != 4:
281 raise ValueError
282 return LITERAL, int(escape[2:], 16) & 0xff
283 elif c == "u" and source.istext:
284 # unicode escape (exactly four digits)
285 escape += source.getwhile(4, HEXDIGITS)
286 if len(escape) != 6:
287 raise ValueError
288 return LITERAL, int(escape[2:], 16)
289 elif c == "U" and source.istext:
290 # unicode escape (exactly eight digits)
291 escape += source.getwhile(8, HEXDIGITS)
292 if len(escape) != 10:
293 raise ValueError
294 c = int(escape[2:], 16)
295 chr(c) # raise ValueError for invalid code
296 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000297 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000298 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200299 escape += source.getwhile(2, OCTDIGITS)
300 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000301 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200302 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000303 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000304 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000305 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000306 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000307 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000308
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000309def _escape(source, escape, state):
310 # handle escape code in expression
311 code = CATEGORIES.get(escape)
312 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000313 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000314 code = ESCAPES.get(escape)
315 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000316 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000317 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000318 c = escape[1:2]
319 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000320 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200321 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000322 if len(escape) != 4:
323 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000324 return LITERAL, int(escape[2:], 16) & 0xff
Antoine Pitrou463badf2012-06-23 13:29:19 +0200325 elif c == "u" and source.istext:
326 # unicode escape (exactly four digits)
327 escape += source.getwhile(4, HEXDIGITS)
328 if len(escape) != 6:
329 raise ValueError
330 return LITERAL, int(escape[2:], 16)
331 elif c == "U" and source.istext:
332 # unicode escape (exactly eight digits)
333 escape += source.getwhile(8, HEXDIGITS)
334 if len(escape) != 10:
335 raise ValueError
336 c = int(escape[2:], 16)
337 chr(c) # raise ValueError for invalid code
338 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000339 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000340 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200341 escape += source.getwhile(2, OCTDIGITS)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000342 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000343 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000344 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000345 if source.next in DIGITS:
346 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000347 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
348 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000349 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000350 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000351 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000352 # not an octal escape, so this is a group reference
353 group = int(escape[1:])
354 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000355 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000356 raise error("cannot refer to open group")
Serhiy Storchakaa3369a52015-02-21 12:08:52 +0200357 if state.lookbehind:
358 import warnings
359 warnings.warn('group references in lookbehind '
360 'assertions are not supported',
361 RuntimeWarning)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000362 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000363 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000364 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000365 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000366 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000367 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000368 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000369
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000370def _parse_sub(source, state, nested=1):
371 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000372
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000373 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000374 itemsappend = items.append
375 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000376 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000377 itemsappend(_parse(source, state))
378 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000379 continue
380 if not nested:
381 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000382 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000383 break
384 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000385 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000386
387 if len(items) == 1:
388 return items[0]
389
390 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000391 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000392
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000393 # check if all items share a common prefix
394 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000395 prefix = None
396 for item in items:
397 if not item:
398 break
399 if prefix is None:
400 prefix = item[0]
401 elif item[0] != prefix:
402 break
403 else:
404 # all subitems start with a common "prefix".
405 # move it out of the branch
406 for item in items:
407 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000408 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000409 continue # check next one
410 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000411
412 # check if the branch can be replaced by a character set
413 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000414 if len(item) != 1 or item[0][0] != LITERAL:
415 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000416 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000417 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000418 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000419 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000420 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000421 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000422 setappend(item[0])
423 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000424 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000425
426 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000427 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000428
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000429def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000430 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000431 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000432 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000433 if source.match("|"):
Collin Winterce36ad82007-08-30 01:19:48 +0000434 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000435 else:
436 item_no = None
437 if source.next and not source.match(")", 0):
Collin Winterce36ad82007-08-30 01:19:48 +0000438 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000439 subpattern = SubPattern(state)
440 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
441 return subpattern
442
Raymond Hettinger049ade22005-02-28 19:27:52 +0000443_PATTERNENDERS = set("|)")
444_ASSERTCHARS = set("=!<")
445_LOOKBEHINDASSERTCHARS = set("=!")
446_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
447
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000448def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000449 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000450 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000451
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000452 # precompute constants into local variables
453 subpatternappend = subpattern.append
454 sourceget = source.get
455 sourcematch = source.match
456 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000457 PATTERNENDERS = _PATTERNENDERS
458 ASSERTCHARS = _ASSERTCHARS
459 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
460 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000461
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000462 while 1:
463
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000464 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000465 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000466 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000467 if this is None:
468 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000469
Fredrik Lundh90a07912000-06-30 07:50:59 +0000470 if state.flags & SRE_FLAG_VERBOSE:
471 # skip whitespace and comments
472 if this in WHITESPACE:
473 continue
474 if this == "#":
475 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000476 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000477 if this in (None, "\n"):
478 break
479 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000480
Fredrik Lundh90a07912000-06-30 07:50:59 +0000481 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000482 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000483
Fredrik Lundh90a07912000-06-30 07:50:59 +0000484 elif this == "[":
485 # character set
486 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000487 setappend = set.append
488## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000489## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000490 if sourcematch("^"):
491 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000492 # check remaining characters
493 start = set[:]
494 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000495 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000496 if this == "]" and set != start:
497 break
498 elif this and this[0] == "\\":
499 code1 = _class_escape(source, this)
500 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000501 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000502 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000503 raise error("unexpected end of regular expression")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000504 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000505 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000506 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000507 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000508 if code1[0] is IN:
509 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000510 setappend(code1)
511 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000512 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000513 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000514 if this[0] == "\\":
515 code2 = _class_escape(source, this)
516 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000517 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000518 if code1[0] != LITERAL or code2[0] != LITERAL:
Collin Winterce36ad82007-08-30 01:19:48 +0000519 raise error("bad character range")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000520 lo = code1[1]
521 hi = code2[1]
522 if hi < lo:
Collin Winterce36ad82007-08-30 01:19:48 +0000523 raise error("bad character range")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000524 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000525 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000526 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000527 else:
528 if code1[0] is IN:
529 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000530 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000531
Fredrik Lundh770617b2001-01-14 15:06:11 +0000532 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000533 if _len(set)==1 and set[0][0] is LITERAL:
534 subpatternappend(set[0]) # optimization
535 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
536 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000537 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000538 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000539 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000540
Fredrik Lundh90a07912000-06-30 07:50:59 +0000541 elif this and this[0] in REPEAT_CHARS:
542 # repeat previous item
543 if this == "?":
544 min, max = 0, 1
545 elif this == "*":
546 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000547
Fredrik Lundh90a07912000-06-30 07:50:59 +0000548 elif this == "+":
549 min, max = 1, MAXREPEAT
550 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000551 if source.next == "}":
552 subpatternappend((LITERAL, ord(this)))
553 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000554 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000555 min, max = 0, MAXREPEAT
556 lo = hi = ""
557 while source.next in DIGITS:
558 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000559 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000560 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000561 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000562 else:
563 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000564 if not sourcematch("}"):
565 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000566 source.seek(here)
567 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000568 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000569 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200570 if min >= MAXREPEAT:
571 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000572 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000573 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200574 if max >= MAXREPEAT:
575 raise OverflowError("the repetition number is too large")
576 if max < min:
577 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000578 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000579 raise error("not supported")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000580 # figure out which item to repeat
581 if subpattern:
582 item = subpattern[-1:]
583 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000584 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000585 if not item or (_len(item) == 1 and item[0][0] == AT):
Collin Winterce36ad82007-08-30 01:19:48 +0000586 raise error("nothing to repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000587 if item[0][0] in REPEATCODES:
Collin Winterce36ad82007-08-30 01:19:48 +0000588 raise error("multiple repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000589 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000590 subpattern[-1] = (MIN_REPEAT, (min, max, item))
591 else:
592 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000593
Fredrik Lundh90a07912000-06-30 07:50:59 +0000594 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000595 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000596
Fredrik Lundh90a07912000-06-30 07:50:59 +0000597 elif this == "(":
598 group = 1
599 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000600 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000601 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000602 group = 0
603 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000604 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000605 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000606 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000607 # named group: skip forward to end of name
608 name = ""
609 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000610 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000611 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000612 raise error("unterminated name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000613 if char == ">":
614 break
615 name = name + char
616 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200617 if not name:
618 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200619 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400620 raise error("bad character in group name %r" % name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000621 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000622 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000623 name = ""
624 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000625 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000626 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000627 raise error("unterminated name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000628 if char == ")":
629 break
630 name = name + char
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200631 if not name:
632 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200633 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400634 raise error("bad character in backref group name "
635 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000636 gid = state.groupdict.get(name)
637 if gid is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700638 msg = "unknown group name: {0!r}".format(name)
639 raise error(msg)
Serhiy Storchakaa3369a52015-02-21 12:08:52 +0200640 if state.lookbehind:
641 import warnings
642 warnings.warn('group references in lookbehind '
643 'assertions are not supported',
644 RuntimeWarning)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000645 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000646 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000647 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000648 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000649 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000650 raise error("unexpected end of pattern")
651 raise error("unknown specifier: ?P%s" % char)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000652 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000653 # non-capturing group
654 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000655 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000656 # comment
657 while 1:
658 if source.next is None or source.next == ")":
659 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000660 sourceget()
661 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000662 raise error("unbalanced parenthesis")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000663 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000664 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000665 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000666 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000667 dir = 1
668 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000669 if source.next not in LOOKBEHINDASSERTCHARS:
Collin Winterce36ad82007-08-30 01:19:48 +0000670 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000671 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000672 char = sourceget()
Serhiy Storchakaa3369a52015-02-21 12:08:52 +0200673 state.lookbehind += 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000674 p = _parse_sub(source, state)
Serhiy Storchakaa3369a52015-02-21 12:08:52 +0200675 if dir < 0:
676 state.lookbehind -= 1
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000677 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000678 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000679 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000680 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000681 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000682 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000683 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000684 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000685 # conditional backreference group
686 condname = ""
687 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000688 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000689 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000690 raise error("unterminated name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000691 if char == ")":
692 break
693 condname = condname + char
694 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200695 if not condname:
696 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200697 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000698 condgroup = state.groupdict.get(condname)
699 if condgroup is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700700 msg = "unknown group name: {0!r}".format(condname)
701 raise error(msg)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000702 else:
703 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000704 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000705 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000706 raise error("bad character in group name")
Serhiy Storchakaa3369a52015-02-21 12:08:52 +0200707 if state.lookbehind:
708 import warnings
709 warnings.warn('group references in lookbehind '
710 'assertions are not supported',
711 RuntimeWarning)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000712 else:
713 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000714 if not source.next in FLAGS:
Collin Winterce36ad82007-08-30 01:19:48 +0000715 raise error("unexpected end of pattern")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000716 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000717 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000718 if group:
719 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000720 if group == 2:
721 # anonymous group
722 group = None
723 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000724 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000725 if condgroup:
726 p = _parse_sub_cond(source, state, condgroup)
727 else:
728 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000729 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000730 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000731 if group is not None:
Benjamin Peterson66323412014-11-30 11:49:00 -0500732 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000733 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000734 else:
735 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000736 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000737 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000738 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000739 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000740 break
Collin Winterce36ad82007-08-30 01:19:48 +0000741 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000742
Fredrik Lundh90a07912000-06-30 07:50:59 +0000743 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000744 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000745
Fredrik Lundh90a07912000-06-30 07:50:59 +0000746 elif this == "$":
747 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000748
Fredrik Lundh90a07912000-06-30 07:50:59 +0000749 elif this and this[0] == "\\":
750 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000751 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000752
Fredrik Lundh90a07912000-06-30 07:50:59 +0000753 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000754 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000755
756 return subpattern
757
Antoine Pitroufd036452008-08-19 17:56:33 +0000758def fix_flags(src, flags):
759 # Check and fix flags according to the type of pattern (str or bytes)
760 if isinstance(src, str):
761 if not flags & SRE_FLAG_ASCII:
762 flags |= SRE_FLAG_UNICODE
763 elif flags & SRE_FLAG_UNICODE:
764 raise ValueError("ASCII and UNICODE flags are incompatible")
765 else:
766 if flags & SRE_FLAG_UNICODE:
767 raise ValueError("can't use UNICODE flag with a bytes pattern")
768 return flags
769
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000770def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000771 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000772
773 source = Tokenizer(str)
774
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000775 if pattern is None:
776 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000777 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000778 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000779
780 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000781 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000782
783 tail = source.get()
784 if tail == ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000785 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000786 elif tail:
Collin Winterce36ad82007-08-30 01:19:48 +0000787 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000788
Fredrik Lundh770617b2001-01-14 15:06:11 +0000789 if flags & SRE_FLAG_DEBUG:
790 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000791
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000792 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
793 # the VERBOSE flag was switched on inside the pattern. to be
794 # on the safe side, we'll parse the whole thing again...
795 return parse(str, p.pattern.flags)
796
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000797 return p
798
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000799def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000800 # parse 're' replacement string into list of literals and
801 # group references
802 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000803 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300804 groups = []
805 literals = []
806 literal = []
807 lappend = literal.append
808 def addgroup(index):
809 if literal:
810 literals.append(''.join(literal))
811 del literal[:]
812 groups.append((len(literals), index))
813 literals.append(None)
814 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000815 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000816 if this is None:
817 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300818 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000819 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300820 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000821 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000822 name = ""
823 if s.match("<"):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300824 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000825 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000826 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000827 raise error("unterminated group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000828 if char == ">":
829 break
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300830 name += char
Fredrik Lundh90a07912000-06-30 07:50:59 +0000831 if not name:
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200832 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000833 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000834 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000835 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000836 raise error("negative group number")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000837 except ValueError:
Georg Brandl1d472b72013-04-14 11:40:00 +0200838 if not name.isidentifier():
Collin Winterce36ad82007-08-30 01:19:48 +0000839 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000840 try:
841 index = pattern.groupindex[name]
842 except KeyError:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700843 msg = "unknown group name: {0!r}".format(name)
844 raise IndexError(msg)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300845 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000846 elif c == "0":
847 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300848 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000849 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300850 this += sget()
851 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000852 elif c in DIGITS:
853 isoctal = False
854 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300855 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000856 if (c in OCTDIGITS and this[2] in OCTDIGITS and
857 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300858 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000859 isoctal = True
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300860 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000861 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300862 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000863 else:
864 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300865 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000866 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000867 pass
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300868 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000869 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300870 lappend(this)
871 if literal:
872 literals.append(''.join(literal))
873 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000874 # The tokenizer implicitly decodes bytes objects as latin-1, we must
875 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300876 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000877 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000878
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000879def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000880 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000881 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000882 groups, literals = template
883 literals = literals[:]
884 try:
885 for index, group in groups:
886 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000887 if s is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000888 raise error("unmatched group")
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000889 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000890 raise error("invalid group reference")
Barry Warsaw8bee7612004-08-25 02:22:30 +0000891 return sep.join(literals)