blob: 399e7b7f3f22142d7cf6d14c7b2670fcbc281839 [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
Fredrik Lundhebc37b22000-10-28 19:30:41 +000069 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000070 self.groups = 1
71 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000072 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000073 gid = self.groups
74 self.groups = gid + 1
Raymond Hettingerf13eb552002-06-02 00:40:05 +000075 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000076 ogid = self.groupdict.get(name, None)
77 if ogid is not None:
Collin Winterce36ad82007-08-30 01:19:48 +000078 raise error("redefinition of group name %s as group %d; "
79 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000080 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000081 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000082 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000083 def closegroup(self, gid):
84 self.open.remove(gid)
85 def checkgroup(self, gid):
86 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000087
88class SubPattern:
89 # a subpattern, in intermediate form
90 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000091 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000092 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000093 data = []
94 self.data = data
95 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000096 def dump(self, level=0):
97 nl = 1
Guido van Rossum13257902007-06-07 23:15:56 +000098 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000099 for op, av in self.data:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000100 print(level*" " + op, end=' '); nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000101 if op == "in":
102 # member sublanguage
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000103 print(); nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000104 for op, a in av:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000105 print((level+1)*" " + op, a)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000106 elif op == "branch":
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000107 print(); nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000108 i = 0
109 for a in av[1]:
110 if i > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000111 print(level*" " + "or")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000112 a.dump(level+1); nl = 1
113 i = i + 1
Guido van Rossum13257902007-06-07 23:15:56 +0000114 elif isinstance(av, seqtypes):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000115 for a in av:
116 if isinstance(a, SubPattern):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000117 if not nl: print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000118 a.dump(level+1); nl = 1
119 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000120 print(a, end=' ') ; nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000121 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000122 print(av, end=' ') ; nl = 0
123 if not nl: print()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000124 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000125 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000126 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000127 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000128 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000129 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000130 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000131 if isinstance(index, slice):
132 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000133 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000134 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000135 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000136 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000137 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000138 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000139 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000140 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000141 # determine the width (min, max) for this subpattern
142 if self.width:
143 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000144 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000145 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
146 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000147 for op, av in self.data:
148 if op is BRANCH:
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300149 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000150 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000151 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000152 l, h = av.getwidth()
153 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000154 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000155 lo = lo + i
156 hi = hi + j
157 elif op is CALL:
158 i, j = av.getwidth()
159 lo = lo + i
160 hi = hi + j
161 elif op is SUBPATTERN:
162 i, j = av[1].getwidth()
163 lo = lo + i
164 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000165 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000166 i, j = av[2].getwidth()
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300167 lo = lo + i * av[0]
168 hi = hi + j * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000169 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000170 lo = lo + 1
171 hi = hi + 1
172 elif op == SUCCESS:
173 break
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300174 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000175 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000176
177class Tokenizer:
178 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200179 self.istext = isinstance(string, str)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000180 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000181 self.index = 0
182 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000183 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000184 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000185 self.next = None
186 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000187 char = self.string[self.index:self.index+1]
188 # Special case for the str8, since indexing returns a integer
189 # XXX This is only needed for test_bug_926075 in test_re.py
Antoine Pitrou463badf2012-06-23 13:29:19 +0200190 if char and not self.istext:
Thomas Wouters40a088d2008-03-18 20:19:54 +0000191 char = chr(char[0])
Guido van Rossum75a902d2007-10-19 22:06:24 +0000192 if char == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000193 try:
194 c = self.string[self.index + 1]
195 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000196 raise error("bogus escape (end of line)")
Antoine Pitrou463badf2012-06-23 13:29:19 +0200197 if not self.istext:
Antoine Pitrou22628c42008-07-22 17:53:22 +0000198 c = chr(c)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000199 char = char + c
200 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000201 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000202 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000203 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000204 if skip:
205 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000206 return 1
207 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000208 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000209 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000210 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000211 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200212 def getwhile(self, n, charset):
213 result = ''
214 for _ in range(n):
215 c = self.next
216 if c not in charset:
217 break
218 result += c
219 self.__next()
220 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000221 def tell(self):
222 return self.index, self.next
223 def seek(self, index):
224 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000225
Georg Brandl1d472b72013-04-14 11:40:00 +0200226# The following three functions are not used in this module anymore, but we keep
227# them here (with DeprecationWarnings) for backwards compatibility.
228
Fredrik Lundh4781b072000-06-29 12:38:45 +0000229def isident(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200230 import warnings
231 warnings.warn('sre_parse.isident() will be removed in 3.5',
232 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000233 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
234
235def isdigit(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200236 import warnings
237 warnings.warn('sre_parse.isdigit() will be removed in 3.5',
238 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000239 return "0" <= char <= "9"
240
241def isname(name):
Georg Brandl1d472b72013-04-14 11:40:00 +0200242 import warnings
243 warnings.warn('sre_parse.isname() will be removed in 3.5',
244 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000245 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000246 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000247 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000248 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000249 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000250 return False
251 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000252
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000253def _class_escape(source, escape):
254 # handle escape code inside character class
255 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000256 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000257 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000258 code = CATEGORIES.get(escape)
Ezio Melottife8e6e72013-01-11 08:32:01 +0200259 if code and code[0] == IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000260 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000261 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000262 c = escape[1:2]
263 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000264 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200265 escape += source.getwhile(2, HEXDIGITS)
266 if len(escape) != 4:
267 raise ValueError
268 return LITERAL, int(escape[2:], 16) & 0xff
269 elif c == "u" and source.istext:
270 # unicode escape (exactly four digits)
271 escape += source.getwhile(4, HEXDIGITS)
272 if len(escape) != 6:
273 raise ValueError
274 return LITERAL, int(escape[2:], 16)
275 elif c == "U" and source.istext:
276 # unicode escape (exactly eight digits)
277 escape += source.getwhile(8, HEXDIGITS)
278 if len(escape) != 10:
279 raise ValueError
280 c = int(escape[2:], 16)
281 chr(c) # raise ValueError for invalid code
282 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000283 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000284 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200285 escape += source.getwhile(2, OCTDIGITS)
286 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000287 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200288 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000289 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000290 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000291 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000292 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000293 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000294
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000295def _escape(source, escape, state):
296 # handle escape code in expression
297 code = CATEGORIES.get(escape)
298 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000299 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000300 code = ESCAPES.get(escape)
301 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000302 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +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
Antoine Pitrou463badf2012-06-23 13:29:19 +0200307 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000308 if len(escape) != 4:
309 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000310 return LITERAL, int(escape[2:], 16) & 0xff
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:
315 raise ValueError
316 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:
321 raise ValueError
322 c = int(escape[2:], 16)
323 chr(c) # raise ValueError for invalid code
324 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000325 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000326 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200327 escape += source.getwhile(2, OCTDIGITS)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000328 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000329 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000330 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000331 if source.next in DIGITS:
332 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000333 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
334 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000335 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000336 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000337 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000338 # not an octal escape, so this is a group reference
339 group = int(escape[1:])
340 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000341 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000342 raise error("cannot refer to open group")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000343 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000344 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000345 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000346 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000347 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000348 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000349 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000350
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000351def _parse_sub(source, state, nested=1):
352 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000353
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000354 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000355 itemsappend = items.append
356 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000357 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000358 itemsappend(_parse(source, state))
359 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000360 continue
361 if not nested:
362 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000363 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000364 break
365 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000366 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000367
368 if len(items) == 1:
369 return items[0]
370
371 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000372 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000373
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000374 # check if all items share a common prefix
375 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000376 prefix = None
377 for item in items:
378 if not item:
379 break
380 if prefix is None:
381 prefix = item[0]
382 elif item[0] != prefix:
383 break
384 else:
385 # all subitems start with a common "prefix".
386 # move it out of the branch
387 for item in items:
388 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000389 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000390 continue # check next one
391 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000392
393 # check if the branch can be replaced by a character set
394 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000395 if len(item) != 1 or item[0][0] != LITERAL:
396 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000397 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000398 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000399 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000400 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000401 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000402 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000403 setappend(item[0])
404 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000405 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000406
407 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000408 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000409
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000410def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000411 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000412 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000413 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000414 if source.match("|"):
Collin Winterce36ad82007-08-30 01:19:48 +0000415 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000416 else:
417 item_no = None
418 if source.next and not source.match(")", 0):
Collin Winterce36ad82007-08-30 01:19:48 +0000419 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000420 subpattern = SubPattern(state)
421 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
422 return subpattern
423
Raymond Hettinger049ade22005-02-28 19:27:52 +0000424_PATTERNENDERS = set("|)")
425_ASSERTCHARS = set("=!<")
426_LOOKBEHINDASSERTCHARS = set("=!")
427_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
428
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000429def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000430 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000431 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000432
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000433 # precompute constants into local variables
434 subpatternappend = subpattern.append
435 sourceget = source.get
436 sourcematch = source.match
437 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000438 PATTERNENDERS = _PATTERNENDERS
439 ASSERTCHARS = _ASSERTCHARS
440 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
441 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000442
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000443 while 1:
444
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000445 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000446 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000447 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000448 if this is None:
449 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000450
Fredrik Lundh90a07912000-06-30 07:50:59 +0000451 if state.flags & SRE_FLAG_VERBOSE:
452 # skip whitespace and comments
453 if this in WHITESPACE:
454 continue
455 if this == "#":
456 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000457 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000458 if this in (None, "\n"):
459 break
460 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000461
Fredrik Lundh90a07912000-06-30 07:50:59 +0000462 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000463 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000464
Fredrik Lundh90a07912000-06-30 07:50:59 +0000465 elif this == "[":
466 # character set
467 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000468 setappend = set.append
469## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000470## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000471 if sourcematch("^"):
472 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000473 # check remaining characters
474 start = set[:]
475 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000476 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000477 if this == "]" and set != start:
478 break
479 elif this and this[0] == "\\":
480 code1 = _class_escape(source, this)
481 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000482 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000483 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000484 raise error("unexpected end of regular expression")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000485 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000486 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000487 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000488 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000489 if code1[0] is IN:
490 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000491 setappend(code1)
492 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000493 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000494 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000495 if this[0] == "\\":
496 code2 = _class_escape(source, this)
497 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000498 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000499 if code1[0] != LITERAL or code2[0] != LITERAL:
Collin Winterce36ad82007-08-30 01:19:48 +0000500 raise error("bad character range")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000501 lo = code1[1]
502 hi = code2[1]
503 if hi < lo:
Collin Winterce36ad82007-08-30 01:19:48 +0000504 raise error("bad character range")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000505 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000506 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000507 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000508 else:
509 if code1[0] is IN:
510 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000511 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000512
Fredrik Lundh770617b2001-01-14 15:06:11 +0000513 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000514 if _len(set)==1 and set[0][0] is LITERAL:
515 subpatternappend(set[0]) # optimization
516 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
517 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000518 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000519 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000520 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000521
Fredrik Lundh90a07912000-06-30 07:50:59 +0000522 elif this and this[0] in REPEAT_CHARS:
523 # repeat previous item
524 if this == "?":
525 min, max = 0, 1
526 elif this == "*":
527 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000528
Fredrik Lundh90a07912000-06-30 07:50:59 +0000529 elif this == "+":
530 min, max = 1, MAXREPEAT
531 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000532 if source.next == "}":
533 subpatternappend((LITERAL, ord(this)))
534 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000535 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000536 min, max = 0, MAXREPEAT
537 lo = hi = ""
538 while source.next in DIGITS:
539 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000540 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000541 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000542 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000543 else:
544 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000545 if not sourcematch("}"):
546 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000547 source.seek(here)
548 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000549 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000550 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200551 if min >= MAXREPEAT:
552 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000553 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000554 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200555 if max >= MAXREPEAT:
556 raise OverflowError("the repetition number is too large")
557 if max < min:
558 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000559 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000560 raise error("not supported")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000561 # figure out which item to repeat
562 if subpattern:
563 item = subpattern[-1:]
564 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000565 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000566 if not item or (_len(item) == 1 and item[0][0] == AT):
Collin Winterce36ad82007-08-30 01:19:48 +0000567 raise error("nothing to repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000568 if item[0][0] in REPEATCODES:
Collin Winterce36ad82007-08-30 01:19:48 +0000569 raise error("multiple repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000570 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000571 subpattern[-1] = (MIN_REPEAT, (min, max, item))
572 else:
573 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000574
Fredrik Lundh90a07912000-06-30 07:50:59 +0000575 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000576 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000577
Fredrik Lundh90a07912000-06-30 07:50:59 +0000578 elif this == "(":
579 group = 1
580 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000581 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000582 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000583 group = 0
584 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000585 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000586 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000587 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000588 # named group: skip forward to end of name
589 name = ""
590 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000591 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000592 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000593 raise error("unterminated name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000594 if char == ">":
595 break
596 name = name + char
597 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200598 if not name:
599 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200600 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400601 raise error("bad character in group name %r" % name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000602 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000603 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000604 name = ""
605 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000606 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000607 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000608 raise error("unterminated name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000609 if char == ")":
610 break
611 name = name + char
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200612 if not name:
613 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200614 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400615 raise error("bad character in backref group name "
616 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000617 gid = state.groupdict.get(name)
618 if gid is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000619 raise error("unknown group name")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000620 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000621 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000622 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000623 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000624 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000625 raise error("unexpected end of pattern")
626 raise error("unknown specifier: ?P%s" % char)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000627 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000628 # non-capturing group
629 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000630 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000631 # comment
632 while 1:
633 if source.next is None or source.next == ")":
634 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000635 sourceget()
636 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000637 raise error("unbalanced parenthesis")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000638 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000639 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000640 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000641 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000642 dir = 1
643 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000644 if source.next not in LOOKBEHINDASSERTCHARS:
Collin Winterce36ad82007-08-30 01:19:48 +0000645 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000646 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000647 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000648 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000649 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000650 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000651 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000652 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000653 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000654 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000655 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000656 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000657 # conditional backreference group
658 condname = ""
659 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000660 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000661 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000662 raise error("unterminated name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000663 if char == ")":
664 break
665 condname = condname + char
666 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200667 if not condname:
668 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200669 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000670 condgroup = state.groupdict.get(condname)
671 if condgroup is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000672 raise error("unknown group name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000673 else:
674 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000675 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000676 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000677 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000678 else:
679 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000680 if not source.next in FLAGS:
Collin Winterce36ad82007-08-30 01:19:48 +0000681 raise error("unexpected end of pattern")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000682 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000683 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000684 if group:
685 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000686 if group == 2:
687 # anonymous group
688 group = None
689 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000690 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000691 if condgroup:
692 p = _parse_sub_cond(source, state, condgroup)
693 else:
694 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000695 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000696 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000697 if group is not None:
698 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000699 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000700 else:
701 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000702 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000703 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000704 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000705 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000706 break
Collin Winterce36ad82007-08-30 01:19:48 +0000707 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000708
Fredrik Lundh90a07912000-06-30 07:50:59 +0000709 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000710 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000711
Fredrik Lundh90a07912000-06-30 07:50:59 +0000712 elif this == "$":
713 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000714
Fredrik Lundh90a07912000-06-30 07:50:59 +0000715 elif this and this[0] == "\\":
716 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000717 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000718
Fredrik Lundh90a07912000-06-30 07:50:59 +0000719 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000720 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000721
722 return subpattern
723
Antoine Pitroufd036452008-08-19 17:56:33 +0000724def fix_flags(src, flags):
725 # Check and fix flags according to the type of pattern (str or bytes)
726 if isinstance(src, str):
727 if not flags & SRE_FLAG_ASCII:
728 flags |= SRE_FLAG_UNICODE
729 elif flags & SRE_FLAG_UNICODE:
730 raise ValueError("ASCII and UNICODE flags are incompatible")
731 else:
732 if flags & SRE_FLAG_UNICODE:
733 raise ValueError("can't use UNICODE flag with a bytes pattern")
734 return flags
735
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000736def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000737 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000738
739 source = Tokenizer(str)
740
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000741 if pattern is None:
742 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000743 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000744 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000745
746 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000747 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000748
749 tail = source.get()
750 if tail == ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000751 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000752 elif tail:
Collin Winterce36ad82007-08-30 01:19:48 +0000753 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000754
Fredrik Lundh770617b2001-01-14 15:06:11 +0000755 if flags & SRE_FLAG_DEBUG:
756 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000757
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000758 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
759 # the VERBOSE flag was switched on inside the pattern. to be
760 # on the safe side, we'll parse the whole thing again...
761 return parse(str, p.pattern.flags)
762
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000763 return p
764
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000765def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000766 # parse 're' replacement string into list of literals and
767 # group references
768 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000769 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300770 groups = []
771 literals = []
772 literal = []
773 lappend = literal.append
774 def addgroup(index):
775 if literal:
776 literals.append(''.join(literal))
777 del literal[:]
778 groups.append((len(literals), index))
779 literals.append(None)
780 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000781 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000782 if this is None:
783 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300784 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000785 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300786 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000787 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000788 name = ""
789 if s.match("<"):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300790 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000791 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000792 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000793 raise error("unterminated group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000794 if char == ">":
795 break
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300796 name += char
Fredrik Lundh90a07912000-06-30 07:50:59 +0000797 if not name:
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200798 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000799 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000800 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000801 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000802 raise error("negative group number")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000803 except ValueError:
Georg Brandl1d472b72013-04-14 11:40:00 +0200804 if not name.isidentifier():
Collin Winterce36ad82007-08-30 01:19:48 +0000805 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000806 try:
807 index = pattern.groupindex[name]
808 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +0000809 raise IndexError("unknown group name")
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300810 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000811 elif c == "0":
812 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300813 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000814 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300815 this += sget()
816 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000817 elif c in DIGITS:
818 isoctal = False
819 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300820 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000821 if (c in OCTDIGITS and this[2] in OCTDIGITS and
822 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300823 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000824 isoctal = True
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300825 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000826 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300827 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000828 else:
829 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300830 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000831 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000832 pass
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300833 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000834 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300835 lappend(this)
836 if literal:
837 literals.append(''.join(literal))
838 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000839 # The tokenizer implicitly decodes bytes objects as latin-1, we must
840 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300841 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000842 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000843
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000844def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000845 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000846 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000847 groups, literals = template
848 literals = literals[:]
849 try:
850 for index, group in groups:
851 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000852 if s is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000853 raise error("unmatched group")
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000854 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000855 raise error("invalid group reference")
Barry Warsaw8bee7612004-08-25 02:22:30 +0000856 return sep.join(literals)