blob: fad80148aa27fefe7c6ee5ffc5c58594dc020902 [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 Lundh90a07912000-06-30 07:50:59 +000069 self.groupdict = {}
Serhiy Storchaka84df7fe2014-11-07 21:43:57 +020070 self.subpatterns = [None] # group 0
71 @property
72 def groups(self):
73 return len(self.subpatterns)
Fredrik Lundhebc37b22000-10-28 19:30:41 +000074 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000075 gid = self.groups
Serhiy Storchaka84df7fe2014-11-07 21:43:57 +020076 self.subpatterns.append(None)
Raymond Hettingerf13eb552002-06-02 00:40:05 +000077 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000078 ogid = self.groupdict.get(name, None)
79 if ogid is not None:
Collin Winterce36ad82007-08-30 01:19:48 +000080 raise error("redefinition of group name %s as group %d; "
81 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000082 self.groupdict[name] = gid
83 return gid
Serhiy Storchaka84df7fe2014-11-07 21:43:57 +020084 def closegroup(self, gid, p):
85 self.subpatterns[gid] = p
Fredrik Lundhebc37b22000-10-28 19:30:41 +000086 def checkgroup(self, gid):
Serhiy Storchaka84df7fe2014-11-07 21:43:57 +020087 return gid < self.groups and self.subpatterns[gid] is not None
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):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +030098 nl = True
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:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300101 print(level*" " + op, end='')
102 if op == IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000103 # member sublanguage
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300104 print()
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)
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300107 elif op == BRANCH:
108 print()
109 for i, a in enumerate(av[1]):
110 if i:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000111 print(level*" " + "or")
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300112 a.dump(level+1)
113 elif op == GROUPREF_EXISTS:
114 condgroup, item_yes, item_no = av
115 print('', condgroup)
116 item_yes.dump(level+1)
117 if item_no:
118 print(level*" " + "else")
119 item_no.dump(level+1)
Guido van Rossum13257902007-06-07 23:15:56 +0000120 elif isinstance(av, seqtypes):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300121 nl = False
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000122 for a in av:
123 if isinstance(a, SubPattern):
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300124 if not nl:
125 print()
126 a.dump(level+1)
127 nl = True
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000128 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300129 if not nl:
130 print(' ', end='')
131 print(a, end='')
132 nl = False
133 if not nl:
134 print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000135 else:
Serhiy Storchaka44dae8b2014-09-21 22:47:55 +0300136 print('', av)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000137 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000138 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000139 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000140 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000141 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000142 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000143 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000144 if isinstance(index, slice):
145 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000146 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000147 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000148 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000149 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000150 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000151 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000152 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000153 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000154 # determine the width (min, max) for this subpattern
155 if self.width:
156 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000157 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000158 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
159 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000160 for op, av in self.data:
161 if op is BRANCH:
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300162 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000163 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000164 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000165 l, h = av.getwidth()
166 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000167 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000168 lo = lo + i
169 hi = hi + j
170 elif op is CALL:
171 i, j = av.getwidth()
172 lo = lo + i
173 hi = hi + j
174 elif op is SUBPATTERN:
175 i, j = av[1].getwidth()
176 lo = lo + i
177 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000178 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000179 i, j = av[2].getwidth()
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300180 lo = lo + i * av[0]
181 hi = hi + j * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000182 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000183 lo = lo + 1
184 hi = hi + 1
Serhiy Storchaka84df7fe2014-11-07 21:43:57 +0200185 elif op is GROUPREF:
186 i, j = self.pattern.subpatterns[av].getwidth()
187 lo = lo + i
188 hi = hi + j
189 elif op is GROUPREF_EXISTS:
190 i, j = av[1].getwidth()
191 if av[2] is not None:
192 l, h = av[2].getwidth()
193 i = min(i, l)
194 j = max(j, h)
195 else:
196 i = 0
197 lo = lo + i
198 hi = hi + j
199 elif op is SUCCESS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000200 break
Serhiy Storchaka9d965422013-08-19 22:50:54 +0300201 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000202 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000203
204class Tokenizer:
205 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200206 self.istext = isinstance(string, str)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000207 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000208 self.index = 0
209 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000210 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000211 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000212 self.next = None
213 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000214 char = self.string[self.index:self.index+1]
215 # Special case for the str8, since indexing returns a integer
216 # XXX This is only needed for test_bug_926075 in test_re.py
Antoine Pitrou463badf2012-06-23 13:29:19 +0200217 if char and not self.istext:
Thomas Wouters40a088d2008-03-18 20:19:54 +0000218 char = chr(char[0])
Guido van Rossum75a902d2007-10-19 22:06:24 +0000219 if char == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000220 try:
221 c = self.string[self.index + 1]
222 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000223 raise error("bogus escape (end of line)")
Antoine Pitrou463badf2012-06-23 13:29:19 +0200224 if not self.istext:
Antoine Pitrou22628c42008-07-22 17:53:22 +0000225 c = chr(c)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000226 char = char + c
227 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000228 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000229 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000230 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000231 if skip:
232 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000233 return 1
234 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000235 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000236 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000237 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000238 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200239 def getwhile(self, n, charset):
240 result = ''
241 for _ in range(n):
242 c = self.next
243 if c not in charset:
244 break
245 result += c
246 self.__next()
247 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000248 def tell(self):
249 return self.index, self.next
250 def seek(self, index):
251 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000252
Georg Brandl1d472b72013-04-14 11:40:00 +0200253# The following three functions are not used in this module anymore, but we keep
254# them here (with DeprecationWarnings) for backwards compatibility.
255
Fredrik Lundh4781b072000-06-29 12:38:45 +0000256def isident(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200257 import warnings
258 warnings.warn('sre_parse.isident() will be removed in 3.5',
259 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000260 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
261
262def isdigit(char):
Georg Brandl1d472b72013-04-14 11:40:00 +0200263 import warnings
264 warnings.warn('sre_parse.isdigit() will be removed in 3.5',
265 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000266 return "0" <= char <= "9"
267
268def isname(name):
Georg Brandl1d472b72013-04-14 11:40:00 +0200269 import warnings
270 warnings.warn('sre_parse.isname() will be removed in 3.5',
271 DeprecationWarning, stacklevel=2)
Fredrik Lundh4781b072000-06-29 12:38:45 +0000272 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000273 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000274 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000275 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000276 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000277 return False
278 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000279
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000280def _class_escape(source, escape):
281 # handle escape code inside character class
282 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000283 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000284 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000285 code = CATEGORIES.get(escape)
Ezio Melottife8e6e72013-01-11 08:32:01 +0200286 if code and code[0] == IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000287 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000288 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000289 c = escape[1:2]
290 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000291 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200292 escape += source.getwhile(2, HEXDIGITS)
293 if len(escape) != 4:
294 raise ValueError
295 return LITERAL, int(escape[2:], 16) & 0xff
296 elif c == "u" and source.istext:
297 # unicode escape (exactly four digits)
298 escape += source.getwhile(4, HEXDIGITS)
299 if len(escape) != 6:
300 raise ValueError
301 return LITERAL, int(escape[2:], 16)
302 elif c == "U" and source.istext:
303 # unicode escape (exactly eight digits)
304 escape += source.getwhile(8, HEXDIGITS)
305 if len(escape) != 10:
306 raise ValueError
307 c = int(escape[2:], 16)
308 chr(c) # raise ValueError for invalid code
309 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000310 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000311 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200312 escape += source.getwhile(2, OCTDIGITS)
313 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000314 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200315 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000316 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000317 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000318 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000319 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000320 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000321
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000322def _escape(source, escape, state):
323 # handle escape code in expression
324 code = CATEGORIES.get(escape)
325 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000326 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000327 code = ESCAPES.get(escape)
328 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000329 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000330 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000331 c = escape[1:2]
332 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000333 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200334 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000335 if len(escape) != 4:
336 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000337 return LITERAL, int(escape[2:], 16) & 0xff
Antoine Pitrou463badf2012-06-23 13:29:19 +0200338 elif c == "u" and source.istext:
339 # unicode escape (exactly four digits)
340 escape += source.getwhile(4, HEXDIGITS)
341 if len(escape) != 6:
342 raise ValueError
343 return LITERAL, int(escape[2:], 16)
344 elif c == "U" and source.istext:
345 # unicode escape (exactly eight digits)
346 escape += source.getwhile(8, HEXDIGITS)
347 if len(escape) != 10:
348 raise ValueError
349 c = int(escape[2:], 16)
350 chr(c) # raise ValueError for invalid code
351 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000352 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000353 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200354 escape += source.getwhile(2, OCTDIGITS)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000355 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000356 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000357 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000358 if source.next in DIGITS:
359 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000360 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
361 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000362 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000363 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000364 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000365 # not an octal escape, so this is a group reference
366 group = int(escape[1:])
367 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000368 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000369 raise error("cannot refer to open group")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000370 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000371 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000372 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000373 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000374 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000375 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000376 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000377
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000378def _parse_sub(source, state, nested=1):
379 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000380
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000381 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000382 itemsappend = items.append
383 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000384 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000385 itemsappend(_parse(source, state))
386 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000387 continue
388 if not nested:
389 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000390 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000391 break
392 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000393 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000394
395 if len(items) == 1:
396 return items[0]
397
398 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000399 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000400
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000401 # check if all items share a common prefix
402 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000403 prefix = None
404 for item in items:
405 if not item:
406 break
407 if prefix is None:
408 prefix = item[0]
409 elif item[0] != prefix:
410 break
411 else:
412 # all subitems start with a common "prefix".
413 # move it out of the branch
414 for item in items:
415 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000416 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000417 continue # check next one
418 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000419
420 # check if the branch can be replaced by a character set
421 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000422 if len(item) != 1 or item[0][0] != LITERAL:
423 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000424 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000425 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000426 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000427 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000428 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000429 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000430 setappend(item[0])
431 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000432 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000433
434 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000435 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000436
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000437def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000438 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000439 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000440 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000441 if source.match("|"):
Collin Winterce36ad82007-08-30 01:19:48 +0000442 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000443 else:
444 item_no = None
445 if source.next and not source.match(")", 0):
Collin Winterce36ad82007-08-30 01:19:48 +0000446 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000447 subpattern = SubPattern(state)
448 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
449 return subpattern
450
Raymond Hettinger049ade22005-02-28 19:27:52 +0000451_PATTERNENDERS = set("|)")
452_ASSERTCHARS = set("=!<")
453_LOOKBEHINDASSERTCHARS = set("=!")
454_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
455
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000456def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000457 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000458 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000459
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000460 # precompute constants into local variables
461 subpatternappend = subpattern.append
462 sourceget = source.get
463 sourcematch = source.match
464 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000465 PATTERNENDERS = _PATTERNENDERS
466 ASSERTCHARS = _ASSERTCHARS
467 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
468 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000469
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000470 while 1:
471
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000472 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000473 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000474 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000475 if this is None:
476 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000477
Fredrik Lundh90a07912000-06-30 07:50:59 +0000478 if state.flags & SRE_FLAG_VERBOSE:
479 # skip whitespace and comments
480 if this in WHITESPACE:
481 continue
482 if this == "#":
483 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000484 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000485 if this in (None, "\n"):
486 break
487 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000488
Fredrik Lundh90a07912000-06-30 07:50:59 +0000489 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000490 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000491
Fredrik Lundh90a07912000-06-30 07:50:59 +0000492 elif this == "[":
493 # character set
494 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000495 setappend = set.append
496## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000497## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000498 if sourcematch("^"):
499 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000500 # check remaining characters
501 start = set[:]
502 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000503 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000504 if this == "]" and set != start:
505 break
506 elif this and this[0] == "\\":
507 code1 = _class_escape(source, this)
508 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000509 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000510 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000511 raise error("unexpected end of regular expression")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000512 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000513 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000514 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000515 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000516 if code1[0] is IN:
517 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000518 setappend(code1)
519 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000520 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000521 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000522 if this[0] == "\\":
523 code2 = _class_escape(source, this)
524 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000525 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000526 if code1[0] != LITERAL or code2[0] != LITERAL:
Collin Winterce36ad82007-08-30 01:19:48 +0000527 raise error("bad character range")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000528 lo = code1[1]
529 hi = code2[1]
530 if hi < lo:
Collin Winterce36ad82007-08-30 01:19:48 +0000531 raise error("bad character range")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000532 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000533 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000534 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000535 else:
536 if code1[0] is IN:
537 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000538 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000539
Fredrik Lundh770617b2001-01-14 15:06:11 +0000540 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000541 if _len(set)==1 and set[0][0] is LITERAL:
542 subpatternappend(set[0]) # optimization
543 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
544 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000545 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000546 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000547 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000548
Fredrik Lundh90a07912000-06-30 07:50:59 +0000549 elif this and this[0] in REPEAT_CHARS:
550 # repeat previous item
551 if this == "?":
552 min, max = 0, 1
553 elif this == "*":
554 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000555
Fredrik Lundh90a07912000-06-30 07:50:59 +0000556 elif this == "+":
557 min, max = 1, MAXREPEAT
558 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000559 if source.next == "}":
560 subpatternappend((LITERAL, ord(this)))
561 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000562 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000563 min, max = 0, MAXREPEAT
564 lo = hi = ""
565 while source.next in DIGITS:
566 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000567 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000568 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000569 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000570 else:
571 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000572 if not sourcematch("}"):
573 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000574 source.seek(here)
575 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000576 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000577 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200578 if min >= MAXREPEAT:
579 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000580 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000581 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200582 if max >= MAXREPEAT:
583 raise OverflowError("the repetition number is too large")
584 if max < min:
585 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000586 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000587 raise error("not supported")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000588 # figure out which item to repeat
589 if subpattern:
590 item = subpattern[-1:]
591 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000592 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000593 if not item or (_len(item) == 1 and item[0][0] == AT):
Collin Winterce36ad82007-08-30 01:19:48 +0000594 raise error("nothing to repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000595 if item[0][0] in REPEATCODES:
Collin Winterce36ad82007-08-30 01:19:48 +0000596 raise error("multiple repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000597 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000598 subpattern[-1] = (MIN_REPEAT, (min, max, item))
599 else:
600 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000601
Fredrik Lundh90a07912000-06-30 07:50:59 +0000602 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000603 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000604
Fredrik Lundh90a07912000-06-30 07:50:59 +0000605 elif this == "(":
606 group = 1
607 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000608 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000609 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000610 group = 0
611 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000612 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000613 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000614 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000615 # named group: skip forward to end of name
616 name = ""
617 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000618 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000619 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000620 raise error("unterminated name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000621 if char == ">":
622 break
623 name = name + char
624 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200625 if not name:
626 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200627 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400628 raise error("bad character in group name %r" % name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000629 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000630 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000631 name = ""
632 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000633 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000634 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000635 raise error("unterminated name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000636 if char == ")":
637 break
638 name = name + char
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200639 if not name:
640 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200641 if not name.isidentifier():
R David Murray26dfaac92013-04-14 13:00:54 -0400642 raise error("bad character in backref group name "
643 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000644 gid = state.groupdict.get(name)
645 if gid is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700646 msg = "unknown group name: {0!r}".format(name)
647 raise error(msg)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000648 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000649 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000650 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000651 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000652 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000653 raise error("unexpected end of pattern")
654 raise error("unknown specifier: ?P%s" % char)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000655 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000656 # non-capturing group
657 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000658 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000659 # comment
660 while 1:
661 if source.next is None or source.next == ")":
662 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000663 sourceget()
664 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000665 raise error("unbalanced parenthesis")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000666 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000667 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000668 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000669 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000670 dir = 1
671 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000672 if source.next not in LOOKBEHINDASSERTCHARS:
Collin Winterce36ad82007-08-30 01:19:48 +0000673 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000674 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000675 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000676 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000677 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000678 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000679 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000680 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000681 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000682 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000683 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000684 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000685 # conditional backreference group
686 condname = ""
687 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000688 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000689 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000690 raise error("unterminated name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000691 if char == ")":
692 break
693 condname = condname + char
694 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200695 if not condname:
696 raise error("missing group name")
Georg Brandl1d472b72013-04-14 11:40:00 +0200697 if condname.isidentifier():
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000698 condgroup = state.groupdict.get(condname)
699 if condgroup is None:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700700 msg = "unknown group name: {0!r}".format(condname)
701 raise error(msg)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000702 else:
703 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000704 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000705 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000706 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000707 else:
708 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000709 if not source.next in FLAGS:
Collin Winterce36ad82007-08-30 01:19:48 +0000710 raise error("unexpected end of pattern")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000711 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000712 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000713 if group:
714 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000715 if group == 2:
716 # anonymous group
717 group = None
718 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000719 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000720 if condgroup:
721 p = _parse_sub_cond(source, state, condgroup)
722 else:
723 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000724 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000725 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000726 if group is not None:
Serhiy Storchaka84df7fe2014-11-07 21:43:57 +0200727 state.closegroup(group, p)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000728 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000729 else:
730 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000731 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000732 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000733 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000734 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000735 break
Collin Winterce36ad82007-08-30 01:19:48 +0000736 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000737
Fredrik Lundh90a07912000-06-30 07:50:59 +0000738 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000739 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000740
Fredrik Lundh90a07912000-06-30 07:50:59 +0000741 elif this == "$":
742 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000743
Fredrik Lundh90a07912000-06-30 07:50:59 +0000744 elif this and this[0] == "\\":
745 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000746 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000747
Fredrik Lundh90a07912000-06-30 07:50:59 +0000748 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000749 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000750
751 return subpattern
752
Antoine Pitroufd036452008-08-19 17:56:33 +0000753def fix_flags(src, flags):
754 # Check and fix flags according to the type of pattern (str or bytes)
755 if isinstance(src, str):
756 if not flags & SRE_FLAG_ASCII:
757 flags |= SRE_FLAG_UNICODE
758 elif flags & SRE_FLAG_UNICODE:
759 raise ValueError("ASCII and UNICODE flags are incompatible")
760 else:
761 if flags & SRE_FLAG_UNICODE:
762 raise ValueError("can't use UNICODE flag with a bytes pattern")
763 return flags
764
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000765def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000766 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000767
768 source = Tokenizer(str)
769
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000770 if pattern is None:
771 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000772 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000773 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000774
775 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000776 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000777
778 tail = source.get()
779 if tail == ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000780 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000781 elif tail:
Collin Winterce36ad82007-08-30 01:19:48 +0000782 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000783
Fredrik Lundh770617b2001-01-14 15:06:11 +0000784 if flags & SRE_FLAG_DEBUG:
785 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000786
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000787 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
788 # the VERBOSE flag was switched on inside the pattern. to be
789 # on the safe side, we'll parse the whole thing again...
790 return parse(str, p.pattern.flags)
791
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000792 return p
793
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000794def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000795 # parse 're' replacement string into list of literals and
796 # group references
797 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000798 sget = s.get
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300799 groups = []
800 literals = []
801 literal = []
802 lappend = literal.append
803 def addgroup(index):
804 if literal:
805 literals.append(''.join(literal))
806 del literal[:]
807 groups.append((len(literals), index))
808 literals.append(None)
809 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000810 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000811 if this is None:
812 break # end of replacement string
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300813 if this[0] == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000814 # group
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300815 c = this[1]
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000816 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000817 name = ""
818 if s.match("<"):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300819 while True:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000820 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000821 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000822 raise error("unterminated group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000823 if char == ">":
824 break
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300825 name += char
Fredrik Lundh90a07912000-06-30 07:50:59 +0000826 if not name:
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200827 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000828 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000829 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000830 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000831 raise error("negative group number")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000832 except ValueError:
Georg Brandl1d472b72013-04-14 11:40:00 +0200833 if not name.isidentifier():
Collin Winterce36ad82007-08-30 01:19:48 +0000834 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000835 try:
836 index = pattern.groupindex[name]
837 except KeyError:
Raymond Hettinger1c99bc82014-06-22 19:47:22 -0700838 msg = "unknown group name: {0!r}".format(name)
839 raise IndexError(msg)
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300840 addgroup(index)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000841 elif c == "0":
842 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300843 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000844 if s.next in OCTDIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300845 this += sget()
846 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000847 elif c in DIGITS:
848 isoctal = False
849 if s.next in DIGITS:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300850 this += sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000851 if (c in OCTDIGITS and this[2] in OCTDIGITS and
852 s.next in OCTDIGITS):
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300853 this += sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000854 isoctal = True
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300855 lappend(chr(int(this[1:], 8) & 0xff))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000856 if not isoctal:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300857 addgroup(int(this[1:]))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000858 else:
859 try:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300860 this = chr(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000861 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000862 pass
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300863 lappend(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000864 else:
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300865 lappend(this)
866 if literal:
867 literals.append(''.join(literal))
868 if not isinstance(source, str):
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000869 # The tokenizer implicitly decodes bytes objects as latin-1, we must
870 # therefore re-encode the final representation.
Serhiy Storchaka9c15ec12013-10-23 22:27:52 +0300871 literals = [None if s is None else s.encode('latin-1') for s in literals]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000872 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000873
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000874def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000875 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000876 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000877 groups, literals = template
878 literals = literals[:]
879 try:
880 for index, group in groups:
881 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000882 if s is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000883 raise error("unmatched group")
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000884 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000885 raise error("invalid group reference")
Barry Warsaw8bee7612004-08-25 02:22:30 +0000886 return sep.join(literals)