blob: 8a77790b08d80db3cca8c959ab1e9de5a59c9f3a [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
Barry Warsaw8bee7612004-08-25 02:22:30 +000015import sys
Guido van Rossum7627c0d2000-03-31 14:58:54 +000016
17from sre_constants import *
18
19SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000020REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000021
Raymond Hettinger049ade22005-02-28 19:27:52 +000022DIGITS = set("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000023
Raymond Hettinger049ade22005-02-28 19:27:52 +000024OCTDIGITS = set("01234567")
25HEXDIGITS = set("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000026
Raymond Hettinger049ade22005-02-28 19:27:52 +000027WHITESPACE = set(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000028
Guido van Rossum7627c0d2000-03-31 14:58:54 +000029ESCAPES = {
Fredrik Lundhf2989b22001-02-18 12:05:16 +000030 r"\a": (LITERAL, ord("\a")),
31 r"\b": (LITERAL, ord("\b")),
32 r"\f": (LITERAL, ord("\f")),
33 r"\n": (LITERAL, ord("\n")),
34 r"\r": (LITERAL, ord("\r")),
35 r"\t": (LITERAL, ord("\t")),
36 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000037 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000038}
39
40CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000041 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000042 r"\b": (AT, AT_BOUNDARY),
43 r"\B": (AT, AT_NON_BOUNDARY),
44 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
45 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
46 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
47 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
48 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
49 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000050 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000051}
52
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000053FLAGS = {
Fredrik Lundh436c3d582000-06-29 08:58:44 +000054 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000055 "i": SRE_FLAG_IGNORECASE,
56 "L": SRE_FLAG_LOCALE,
57 "m": SRE_FLAG_MULTILINE,
58 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000059 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000060 # extensions
Antoine Pitroufd036452008-08-19 17:56:33 +000061 "a": SRE_FLAG_ASCII,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000062 "t": SRE_FLAG_TEMPLATE,
63 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000064}
65
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000066class Pattern:
67 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000068 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000069 self.flags = 0
Fredrik Lundhebc37b22000-10-28 19:30:41 +000070 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000071 self.groups = 1
72 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000073 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000074 gid = self.groups
75 self.groups = gid + 1
Raymond Hettingerf13eb552002-06-02 00:40:05 +000076 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000077 ogid = self.groupdict.get(name, None)
78 if ogid is not None:
Collin Winterce36ad82007-08-30 01:19:48 +000079 raise error("redefinition of group name %s as group %d; "
80 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000081 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000082 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000083 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000084 def closegroup(self, gid):
85 self.open.remove(gid)
86 def checkgroup(self, gid):
87 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000088
89class SubPattern:
90 # a subpattern, in intermediate form
91 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000092 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000093 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000094 data = []
95 self.data = data
96 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000097 def dump(self, level=0):
98 nl = 1
Guido van Rossum13257902007-06-07 23:15:56 +000099 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000100 for op, av in self.data:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000101 print(level*" " + op, end=' '); nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000102 if op == "in":
103 # member sublanguage
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000104 print(); nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000105 for op, a in av:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000106 print((level+1)*" " + op, a)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000107 elif op == "branch":
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000108 print(); nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000109 i = 0
110 for a in av[1]:
111 if i > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000112 print(level*" " + "or")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000113 a.dump(level+1); nl = 1
114 i = i + 1
Guido van Rossum13257902007-06-07 23:15:56 +0000115 elif isinstance(av, seqtypes):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000116 for a in av:
117 if isinstance(a, SubPattern):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000118 if not nl: print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000119 a.dump(level+1); nl = 1
120 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000121 print(a, end=' ') ; nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000122 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000123 print(av, end=' ') ; nl = 0
124 if not nl: print()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000125 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000126 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000127 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000128 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000129 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000130 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000131 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000132 if isinstance(index, slice):
133 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000134 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000135 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000136 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000137 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000138 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000139 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000140 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000141 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000142 # determine the width (min, max) for this subpattern
143 if self.width:
144 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000145 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000146 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
147 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000148 for op, av in self.data:
149 if op is BRANCH:
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300150 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000151 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000152 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000153 l, h = av.getwidth()
154 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000155 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000156 lo = lo + i
157 hi = hi + j
158 elif op is CALL:
159 i, j = av.getwidth()
160 lo = lo + i
161 hi = hi + j
162 elif op is SUBPATTERN:
163 i, j = av[1].getwidth()
164 lo = lo + i
165 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000166 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000167 i, j = av[2].getwidth()
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300168 lo = lo + i * av[0]
169 hi = hi + j * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000170 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000171 lo = lo + 1
172 hi = hi + 1
173 elif op == SUCCESS:
174 break
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300175 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000176 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000177
178class Tokenizer:
179 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200180 self.istext = isinstance(string, str)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000181 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000182 self.index = 0
183 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000184 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000185 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000186 self.next = None
187 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000188 char = self.string[self.index:self.index+1]
189 # Special case for the str8, since indexing returns a integer
190 # XXX This is only needed for test_bug_926075 in test_re.py
Antoine Pitrou463badf2012-06-23 13:29:19 +0200191 if char and not self.istext:
Thomas Wouters40a088d2008-03-18 20:19:54 +0000192 char = chr(char[0])
Guido van Rossum75a902d2007-10-19 22:06:24 +0000193 if char == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000194 try:
195 c = self.string[self.index + 1]
196 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000197 raise error("bogus escape (end of line)")
Antoine Pitrou463badf2012-06-23 13:29:19 +0200198 if not self.istext:
Antoine Pitrou22628c42008-07-22 17:53:22 +0000199 c = chr(c)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000200 char = char + c
201 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000202 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000203 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000204 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000205 if skip:
206 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000207 return 1
208 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000209 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000210 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000211 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000212 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200213 def getwhile(self, n, charset):
214 result = ''
215 for _ in range(n):
216 c = self.next
217 if c not in charset:
218 break
219 result += c
220 self.__next()
221 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000222 def tell(self):
223 return self.index, self.next
224 def seek(self, index):
225 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000226
Georg Brandl1d472b72013-04-14 11:40:00 +0200227# The following three functions are not used in this module anymore, but we keep
228# them here (with DeprecationWarnings) for backwards compatibility.
229
Fredrik Lundh4781b072000-06-29 12:38:45 +0000230def isident(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200231 import warnings
232 warnings.warn('sre_parse.isident() will be removed in 3.5',
233 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000234 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
235
236def isdigit(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200237 import warnings
238 warnings.warn('sre_parse.isdigit() will be removed in 3.5',
239 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000240 return "0" <= char <= "9"
241
242def isname(name):
Georg Brandl1d472b72013-04-14 11:40:00 +0200243 import warnings
244 warnings.warn('sre_parse.isname() will be removed in 3.5',
245 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000246 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000247 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000248 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000249 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000250 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000251 return False
252 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000253
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000254def _class_escape(source, escape):
255 # handle escape code inside character class
256 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000257 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000258 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000259 code = CATEGORIES.get(escape)
Ezio Melottife8e6e72013-01-11 08:32:01 +0200260 if code and code[0] == IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000261 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000262 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000263 c = escape[1:2]
264 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000265 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200266 escape += source.getwhile(2, HEXDIGITS)
267 if len(escape) != 4:
268 raise ValueError
269 return LITERAL, int(escape[2:], 16) & 0xff
270 elif c == "u" and source.istext:
271 # unicode escape (exactly four digits)
272 escape += source.getwhile(4, HEXDIGITS)
273 if len(escape) != 6:
274 raise ValueError
275 return LITERAL, int(escape[2:], 16)
276 elif c == "U" and source.istext:
277 # unicode escape (exactly eight digits)
278 escape += source.getwhile(8, HEXDIGITS)
279 if len(escape) != 10:
280 raise ValueError
281 c = int(escape[2:], 16)
282 chr(c) # raise ValueError for invalid code
283 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000284 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000285 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200286 escape += source.getwhile(2, OCTDIGITS)
287 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000288 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200289 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000290 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000291 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000292 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000293 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000294 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000295
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000296def _escape(source, escape, state):
297 # handle escape code in expression
298 code = CATEGORIES.get(escape)
299 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000300 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000301 code = ESCAPES.get(escape)
302 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000303 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000304 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000305 c = escape[1:2]
306 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000307 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200308 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000309 if len(escape) != 4:
310 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000311 return LITERAL, int(escape[2:], 16) & 0xff
Antoine Pitrou463badf2012-06-23 13:29:19 +0200312 elif c == "u" and source.istext:
313 # unicode escape (exactly four digits)
314 escape += source.getwhile(4, HEXDIGITS)
315 if len(escape) != 6:
316 raise ValueError
317 return LITERAL, int(escape[2:], 16)
318 elif c == "U" and source.istext:
319 # unicode escape (exactly eight digits)
320 escape += source.getwhile(8, HEXDIGITS)
321 if len(escape) != 10:
322 raise ValueError
323 c = int(escape[2:], 16)
324 chr(c) # raise ValueError for invalid code
325 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000326 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000327 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200328 escape += source.getwhile(2, OCTDIGITS)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000329 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000330 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000331 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000332 if source.next in DIGITS:
333 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000334 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
335 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000336 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000337 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000338 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000339 # not an octal escape, so this is a group reference
340 group = int(escape[1:])
341 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000342 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000343 raise error("cannot refer to open group")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000344 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000345 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000346 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000347 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000348 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000349 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000350 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000351
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000352def _parse_sub(source, state, nested=1):
353 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000354
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000355 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000356 itemsappend = items.append
357 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000358 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000359 itemsappend(_parse(source, state))
360 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000361 continue
362 if not nested:
363 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000364 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000365 break
366 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000367 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000368
369 if len(items) == 1:
370 return items[0]
371
372 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000373 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000374
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000375 # check if all items share a common prefix
376 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000377 prefix = None
378 for item in items:
379 if not item:
380 break
381 if prefix is None:
382 prefix = item[0]
383 elif item[0] != prefix:
384 break
385 else:
386 # all subitems start with a common "prefix".
387 # move it out of the branch
388 for item in items:
389 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000390 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000391 continue # check next one
392 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000393
394 # check if the branch can be replaced by a character set
395 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000396 if len(item) != 1 or item[0][0] != LITERAL:
397 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000398 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000399 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000400 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000401 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000402 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000403 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000404 setappend(item[0])
405 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000406 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000407
408 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000409 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000410
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000411def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000412 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000413 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000414 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000415 if source.match("|"):
Collin Winterce36ad82007-08-30 01:19:48 +0000416 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000417 else:
418 item_no = None
419 if source.next and not source.match(")", 0):
Collin Winterce36ad82007-08-30 01:19:48 +0000420 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000421 subpattern = SubPattern(state)
422 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
423 return subpattern
424
Raymond Hettinger049ade22005-02-28 19:27:52 +0000425_PATTERNENDERS = set("|)")
426_ASSERTCHARS = set("=!<")
427_LOOKBEHINDASSERTCHARS = set("=!")
428_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
429
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000430def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000431 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000432 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000433
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000434 # precompute constants into local variables
435 subpatternappend = subpattern.append
436 sourceget = source.get
437 sourcematch = source.match
438 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000439 PATTERNENDERS = _PATTERNENDERS
440 ASSERTCHARS = _ASSERTCHARS
441 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
442 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000443
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000444 while 1:
445
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000446 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000447 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000448 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000449 if this is None:
450 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000451
Fredrik Lundh90a07912000-06-30 07:50:59 +0000452 if state.flags & SRE_FLAG_VERBOSE:
453 # skip whitespace and comments
454 if this in WHITESPACE:
455 continue
456 if this == "#":
457 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000458 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000459 if this in (None, "\n"):
460 break
461 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000462
Fredrik Lundh90a07912000-06-30 07:50:59 +0000463 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000464 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000465
Fredrik Lundh90a07912000-06-30 07:50:59 +0000466 elif this == "[":
467 # character set
468 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000469 setappend = set.append
470## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000471## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000472 if sourcematch("^"):
473 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000474 # check remaining characters
475 start = set[:]
476 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000477 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000478 if this == "]" and set != start:
479 break
480 elif this and this[0] == "\\":
481 code1 = _class_escape(source, this)
482 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000483 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000484 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000485 raise error("unexpected end of regular expression")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000486 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000487 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000488 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000489 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000490 if code1[0] is IN:
491 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000492 setappend(code1)
493 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000494 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000495 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000496 if this[0] == "\\":
497 code2 = _class_escape(source, this)
498 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000499 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000500 if code1[0] != LITERAL or code2[0] != LITERAL:
Collin Winterce36ad82007-08-30 01:19:48 +0000501 raise error("bad character range")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000502 lo = code1[1]
503 hi = code2[1]
504 if hi < lo:
Collin Winterce36ad82007-08-30 01:19:48 +0000505 raise error("bad character range")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000506 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000507 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000508 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000509 else:
510 if code1[0] is IN:
511 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000512 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000513
Fredrik Lundh770617b2001-01-14 15:06:11 +0000514 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000515 if _len(set)==1 and set[0][0] is LITERAL:
516 subpatternappend(set[0]) # optimization
517 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
518 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000519 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000520 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000521 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000522
Fredrik Lundh90a07912000-06-30 07:50:59 +0000523 elif this and this[0] in REPEAT_CHARS:
524 # repeat previous item
525 if this == "?":
526 min, max = 0, 1
527 elif this == "*":
528 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000529
Fredrik Lundh90a07912000-06-30 07:50:59 +0000530 elif this == "+":
531 min, max = 1, MAXREPEAT
532 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000533 if source.next == "}":
534 subpatternappend((LITERAL, ord(this)))
535 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000536 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000537 min, max = 0, MAXREPEAT
538 lo = hi = ""
539 while source.next in DIGITS:
540 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000541 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000542 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000543 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000544 else:
545 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000546 if not sourcematch("}"):
547 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000548 source.seek(here)
549 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000550 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000551 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200552 if min >= MAXREPEAT:
553 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000554 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000555 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200556 if max >= MAXREPEAT:
557 raise OverflowError("the repetition number is too large")
558 if max < min:
559 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000560 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000561 raise error("not supported")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000562 # figure out which item to repeat
563 if subpattern:
564 item = subpattern[-1:]
565 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000566 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000567 if not item or (_len(item) == 1 and item[0][0] == AT):
Collin Winterce36ad82007-08-30 01:19:48 +0000568 raise error("nothing to repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000569 if item[0][0] in REPEATCODES:
Collin Winterce36ad82007-08-30 01:19:48 +0000570 raise error("multiple repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000571 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000572 subpattern[-1] = (MIN_REPEAT, (min, max, item))
573 else:
574 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000575
Fredrik Lundh90a07912000-06-30 07:50:59 +0000576 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000577 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000578
Fredrik Lundh90a07912000-06-30 07:50:59 +0000579 elif this == "(":
580 group = 1
581 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000582 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000583 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000584 group = 0
585 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000586 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000587 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000588 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000589 # named group: skip forward to end of name
590 name = ""
591 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000592 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000593 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000594 raise error("unterminated name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000595 if char == ">":
596 break
597 name = name + char
598 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200599 if not name:
600 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200601 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400602 raise error("bad character in group name %r" % name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000603 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000604 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000605 name = ""
606 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000607 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000608 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000609 raise error("unterminated name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000610 if char == ")":
611 break
612 name = name + char
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200613 if not name:
614 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200615 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400616 raise error("bad character in backref group name "
617 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000618 gid = state.groupdict.get(name)
619 if gid is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000620 raise error("unknown group name")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000621 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000622 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000623 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000624 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000625 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000626 raise error("unexpected end of pattern")
627 raise error("unknown specifier: ?P%s" % char)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000628 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000629 # non-capturing group
630 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000631 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000632 # comment
633 while 1:
634 if source.next is None or source.next == ")":
635 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000636 sourceget()
637 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000638 raise error("unbalanced parenthesis")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000639 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000640 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000641 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000642 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000643 dir = 1
644 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000645 if source.next not in LOOKBEHINDASSERTCHARS:
Collin Winterce36ad82007-08-30 01:19:48 +0000646 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000647 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000648 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000649 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000650 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000651 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000652 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000653 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000654 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000655 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000656 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000657 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000658 # conditional backreference group
659 condname = ""
660 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000661 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000662 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000663 raise error("unterminated name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000664 if char == ")":
665 break
666 condname = condname + char
667 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200668 if not condname:
669 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200670 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000671 condgroup = state.groupdict.get(condname)
672 if condgroup is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000673 raise error("unknown group name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000674 else:
675 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000676 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000677 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000678 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000679 else:
680 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000681 if not source.next in FLAGS:
Collin Winterce36ad82007-08-30 01:19:48 +0000682 raise error("unexpected end of pattern")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000683 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000684 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000685 if group:
686 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000687 if group == 2:
688 # anonymous group
689 group = None
690 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000691 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000692 if condgroup:
693 p = _parse_sub_cond(source, state, condgroup)
694 else:
695 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000696 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000697 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000698 if group is not None:
699 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000700 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000701 else:
702 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000703 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000704 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000705 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000706 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000707 break
Collin Winterce36ad82007-08-30 01:19:48 +0000708 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000709
Fredrik Lundh90a07912000-06-30 07:50:59 +0000710 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000711 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000712
Fredrik Lundh90a07912000-06-30 07:50:59 +0000713 elif this == "$":
714 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000715
Fredrik Lundh90a07912000-06-30 07:50:59 +0000716 elif this and this[0] == "\\":
717 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000718 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000719
Fredrik Lundh90a07912000-06-30 07:50:59 +0000720 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000721 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000722
723 return subpattern
724
Antoine Pitroufd036452008-08-19 17:56:33 +0000725def fix_flags(src, flags):
726 # Check and fix flags according to the type of pattern (str or bytes)
727 if isinstance(src, str):
728 if not flags & SRE_FLAG_ASCII:
729 flags |= SRE_FLAG_UNICODE
730 elif flags & SRE_FLAG_UNICODE:
731 raise ValueError("ASCII and UNICODE flags are incompatible")
732 else:
733 if flags & SRE_FLAG_UNICODE:
734 raise ValueError("can't use UNICODE flag with a bytes pattern")
735 return flags
736
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000737def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000738 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000739
740 source = Tokenizer(str)
741
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000742 if pattern is None:
743 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000744 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000745 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000746
747 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000748 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000749
750 tail = source.get()
751 if tail == ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000752 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000753 elif tail:
Collin Winterce36ad82007-08-30 01:19:48 +0000754 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000755
Fredrik Lundh770617b2001-01-14 15:06:11 +0000756 if flags & SRE_FLAG_DEBUG:
757 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000758
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000759 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
760 # the VERBOSE flag was switched on inside the pattern. to be
761 # on the safe side, we'll parse the whole thing again...
762 return parse(str, p.pattern.flags)
763
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000764 return p
765
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000766def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000767 # parse 're' replacement string into list of literals and
768 # group references
769 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000770 sget = s.get
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000771 p = []
772 a = p.append
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000773 def literal(literal, p=p, pappend=a):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000774 if p and p[-1][0] is LITERAL:
775 p[-1] = LITERAL, p[-1][1] + literal
776 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000777 pappend((LITERAL, literal))
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000778 sep = source[:0]
Guido van Rossum13257902007-06-07 23:15:56 +0000779 if isinstance(sep, str):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000780 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000781 else:
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000782 makechar = chr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000783 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000784 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000785 if this is None:
786 break # end of replacement string
787 if this and this[0] == "\\":
788 # group
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000789 c = this[1:2]
790 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000791 name = ""
792 if s.match("<"):
793 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000794 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000795 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000796 raise error("unterminated group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000797 if char == ">":
798 break
799 name = name + char
800 if not name:
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200801 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000802 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000803 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000804 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000805 raise error("negative group number")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000806 except ValueError:
Georg Brandl1d472b72013-04-14 11:40:00 +0200807 if not name.isidentifier():
Collin Winterce36ad82007-08-30 01:19:48 +0000808 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000809 try:
810 index = pattern.groupindex[name]
811 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +0000812 raise IndexError("unknown group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000813 a((MARK, index))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000814 elif c == "0":
815 if s.next in OCTDIGITS:
816 this = this + sget()
817 if s.next in OCTDIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000818 this = this + sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000819 literal(makechar(int(this[1:], 8) & 0xff))
820 elif c in DIGITS:
821 isoctal = False
822 if s.next in DIGITS:
823 this = this + sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000824 if (c in OCTDIGITS and this[2] in OCTDIGITS and
825 s.next in OCTDIGITS):
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000826 this = this + sget()
827 isoctal = True
828 literal(makechar(int(this[1:], 8) & 0xff))
829 if not isoctal:
830 a((MARK, int(this[1:])))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000831 else:
832 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000833 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000834 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000835 pass
836 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000837 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000838 literal(this)
839 # convert template to groups and literals lists
840 i = 0
841 groups = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000842 groupsappend = groups.append
843 literals = [None] * len(p)
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000844 if isinstance(source, str):
845 encode = lambda x: x
846 else:
847 # The tokenizer implicitly decodes bytes objects as latin-1, we must
848 # therefore re-encode the final representation.
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000849 encode = lambda x: x.encode('latin-1')
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000850 for c, s in p:
851 if c is MARK:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000852 groupsappend((i, s))
853 # literal[i] is already None
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000854 else:
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000855 literals[i] = encode(s)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000856 i = i + 1
857 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000858
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000859def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000860 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000861 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000862 groups, literals = template
863 literals = literals[:]
864 try:
865 for index, group in groups:
866 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000867 if s is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000868 raise error("unmatched group")
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000869 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000870 raise error("invalid group reference")
Barry Warsaw8bee7612004-08-25 02:22:30 +0000871 return sep.join(literals)