blob: b195fd01dc9bda21b655d3a1e8f0611df98e0a06 [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 *
Serhiy Storchaka70ca0212013-02-16 16:47:47 +020018from _sre import MAXREPEAT
Guido van Rossum7627c0d2000-03-31 14:58:54 +000019
20SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000021REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000022
Raymond Hettinger049ade22005-02-28 19:27:52 +000023DIGITS = set("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000024
Raymond Hettinger049ade22005-02-28 19:27:52 +000025OCTDIGITS = set("01234567")
26HEXDIGITS = set("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000027
Raymond Hettinger049ade22005-02-28 19:27:52 +000028WHITESPACE = set(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000029
Guido van Rossum7627c0d2000-03-31 14:58:54 +000030ESCAPES = {
Fredrik Lundhf2989b22001-02-18 12:05:16 +000031 r"\a": (LITERAL, ord("\a")),
32 r"\b": (LITERAL, ord("\b")),
33 r"\f": (LITERAL, ord("\f")),
34 r"\n": (LITERAL, ord("\n")),
35 r"\r": (LITERAL, ord("\r")),
36 r"\t": (LITERAL, ord("\t")),
37 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000038 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000039}
40
41CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000042 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000043 r"\b": (AT, AT_BOUNDARY),
44 r"\B": (AT, AT_NON_BOUNDARY),
45 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
46 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
47 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
48 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
49 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
50 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000051 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000052}
53
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000054FLAGS = {
Fredrik Lundh436c3d582000-06-29 08:58:44 +000055 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000056 "i": SRE_FLAG_IGNORECASE,
57 "L": SRE_FLAG_LOCALE,
58 "m": SRE_FLAG_MULTILINE,
59 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000060 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000061 # extensions
Antoine Pitroufd036452008-08-19 17:56:33 +000062 "a": SRE_FLAG_ASCII,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000063 "t": SRE_FLAG_TEMPLATE,
64 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000065}
66
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000067class Pattern:
68 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000069 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000070 self.flags = 0
Fredrik Lundhebc37b22000-10-28 19:30:41 +000071 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000072 self.groups = 1
73 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000074 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000075 gid = self.groups
76 self.groups = gid + 1
Raymond Hettingerf13eb552002-06-02 00:40:05 +000077 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000078 ogid = self.groupdict.get(name, None)
79 if ogid is not None:
Collin Winterce36ad82007-08-30 01:19:48 +000080 raise error("redefinition of group name %s as group %d; "
81 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000082 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000083 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000084 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000085 def closegroup(self, gid):
86 self.open.remove(gid)
87 def checkgroup(self, gid):
88 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000089
90class SubPattern:
91 # a subpattern, in intermediate form
92 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000093 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000094 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000095 data = []
96 self.data = data
97 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000098 def dump(self, level=0):
99 nl = 1
Guido van Rossum13257902007-06-07 23:15:56 +0000100 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000101 for op, av in self.data:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000102 print(level*" " + op, end=' '); nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000103 if op == "in":
104 # member sublanguage
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000105 print(); nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000106 for op, a in av:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000107 print((level+1)*" " + op, a)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000108 elif op == "branch":
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000109 print(); nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000110 i = 0
111 for a in av[1]:
112 if i > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000113 print(level*" " + "or")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000114 a.dump(level+1); nl = 1
115 i = i + 1
Guido van Rossum13257902007-06-07 23:15:56 +0000116 elif isinstance(av, seqtypes):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000117 for a in av:
118 if isinstance(a, SubPattern):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000119 if not nl: print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000120 a.dump(level+1); nl = 1
121 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000122 print(a, end=' ') ; nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000123 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000124 print(av, end=' ') ; nl = 0
125 if not nl: print()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000126 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000127 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000128 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000129 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000130 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000131 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000132 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000133 if isinstance(index, slice):
134 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000135 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000136 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000137 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000138 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000139 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000140 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000141 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000142 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000143 # determine the width (min, max) for this subpattern
144 if self.width:
145 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000146 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000147 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
148 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000149 for op, av in self.data:
150 if op is BRANCH:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000151 i = sys.maxsize
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000152 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000153 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000154 l, h = av.getwidth()
155 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000156 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000157 lo = lo + i
158 hi = hi + j
159 elif op is CALL:
160 i, j = av.getwidth()
161 lo = lo + i
162 hi = hi + j
163 elif op is SUBPATTERN:
164 i, j = av[1].getwidth()
165 lo = lo + i
166 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000167 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000168 i, j = av[2].getwidth()
Guido van Rossume2a383d2007-01-15 16:59:06 +0000169 lo = lo + int(i) * av[0]
170 hi = hi + int(j) * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000171 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000172 lo = lo + 1
173 hi = hi + 1
174 elif op == SUCCESS:
175 break
Christian Heimesa37d4c62007-12-04 23:02:19 +0000176 self.width = int(min(lo, sys.maxsize)), int(min(hi, sys.maxsize))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000177 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000178
179class Tokenizer:
180 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200181 self.istext = isinstance(string, str)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000182 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000183 self.index = 0
184 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000185 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000186 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000187 self.next = None
188 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000189 char = self.string[self.index:self.index+1]
190 # Special case for the str8, since indexing returns a integer
191 # XXX This is only needed for test_bug_926075 in test_re.py
Antoine Pitrou463badf2012-06-23 13:29:19 +0200192 if char and not self.istext:
Thomas Wouters40a088d2008-03-18 20:19:54 +0000193 char = chr(char[0])
Guido van Rossum75a902d2007-10-19 22:06:24 +0000194 if char == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000195 try:
196 c = self.string[self.index + 1]
197 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000198 raise error("bogus escape (end of line)")
Antoine Pitrou463badf2012-06-23 13:29:19 +0200199 if not self.istext:
Antoine Pitrou22628c42008-07-22 17:53:22 +0000200 c = chr(c)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000201 char = char + c
202 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000203 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000204 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000205 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000206 if skip:
207 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000208 return 1
209 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000210 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000211 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000212 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000213 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200214 def getwhile(self, n, charset):
215 result = ''
216 for _ in range(n):
217 c = self.next
218 if c not in charset:
219 break
220 result += c
221 self.__next()
222 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000223 def tell(self):
224 return self.index, self.next
225 def seek(self, index):
226 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000227
Fredrik Lundh4781b072000-06-29 12:38:45 +0000228def isident(char):
229 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
230
231def isdigit(char):
232 return "0" <= char <= "9"
233
234def isname(name):
235 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000236 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000237 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000238 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000239 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000240 return False
241 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000242
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000243def _class_escape(source, escape):
244 # handle escape code inside character class
245 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000246 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000247 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000248 code = CATEGORIES.get(escape)
Ezio Melottife8e6e72013-01-11 08:32:01 +0200249 if code and code[0] == IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000250 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000251 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000252 c = escape[1:2]
253 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000254 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200255 escape += source.getwhile(2, HEXDIGITS)
256 if len(escape) != 4:
257 raise ValueError
258 return LITERAL, int(escape[2:], 16) & 0xff
259 elif c == "u" and source.istext:
260 # unicode escape (exactly four digits)
261 escape += source.getwhile(4, HEXDIGITS)
262 if len(escape) != 6:
263 raise ValueError
264 return LITERAL, int(escape[2:], 16)
265 elif c == "U" and source.istext:
266 # unicode escape (exactly eight digits)
267 escape += source.getwhile(8, HEXDIGITS)
268 if len(escape) != 10:
269 raise ValueError
270 c = int(escape[2:], 16)
271 chr(c) # raise ValueError for invalid code
272 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000273 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000274 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200275 escape += source.getwhile(2, OCTDIGITS)
276 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000277 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200278 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000279 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000280 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000281 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000282 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000283 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000284
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000285def _escape(source, escape, state):
286 # handle escape code in expression
287 code = CATEGORIES.get(escape)
288 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000289 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000290 code = ESCAPES.get(escape)
291 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000292 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000293 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000294 c = escape[1:2]
295 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000296 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200297 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000298 if len(escape) != 4:
299 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000300 return LITERAL, int(escape[2:], 16) & 0xff
Antoine Pitrou463badf2012-06-23 13:29:19 +0200301 elif c == "u" and source.istext:
302 # unicode escape (exactly four digits)
303 escape += source.getwhile(4, HEXDIGITS)
304 if len(escape) != 6:
305 raise ValueError
306 return LITERAL, int(escape[2:], 16)
307 elif c == "U" and source.istext:
308 # unicode escape (exactly eight digits)
309 escape += source.getwhile(8, HEXDIGITS)
310 if len(escape) != 10:
311 raise ValueError
312 c = int(escape[2:], 16)
313 chr(c) # raise ValueError for invalid code
314 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000315 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000316 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200317 escape += source.getwhile(2, OCTDIGITS)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000318 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000319 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000320 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000321 if source.next in DIGITS:
322 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000323 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
324 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000325 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000326 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000327 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000328 # not an octal escape, so this is a group reference
329 group = int(escape[1:])
330 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000331 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000332 raise error("cannot refer to open group")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000333 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000334 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000335 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000336 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000337 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000338 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000339 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000340
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000341def _parse_sub(source, state, nested=1):
342 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000343
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000344 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000345 itemsappend = items.append
346 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000347 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000348 itemsappend(_parse(source, state))
349 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000350 continue
351 if not nested:
352 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000353 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000354 break
355 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000356 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000357
358 if len(items) == 1:
359 return items[0]
360
361 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000362 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000363
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000364 # check if all items share a common prefix
365 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000366 prefix = None
367 for item in items:
368 if not item:
369 break
370 if prefix is None:
371 prefix = item[0]
372 elif item[0] != prefix:
373 break
374 else:
375 # all subitems start with a common "prefix".
376 # move it out of the branch
377 for item in items:
378 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000379 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000380 continue # check next one
381 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000382
383 # check if the branch can be replaced by a character set
384 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000385 if len(item) != 1 or item[0][0] != LITERAL:
386 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000387 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000388 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000389 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000390 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000391 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000392 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000393 setappend(item[0])
394 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000395 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000396
397 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000398 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000399
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000400def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000401 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000402 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000403 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000404 if source.match("|"):
Collin Winterce36ad82007-08-30 01:19:48 +0000405 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000406 else:
407 item_no = None
408 if source.next and not source.match(")", 0):
Collin Winterce36ad82007-08-30 01:19:48 +0000409 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000410 subpattern = SubPattern(state)
411 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
412 return subpattern
413
Raymond Hettinger049ade22005-02-28 19:27:52 +0000414_PATTERNENDERS = set("|)")
415_ASSERTCHARS = set("=!<")
416_LOOKBEHINDASSERTCHARS = set("=!")
417_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
418
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000419def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000420 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000421 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000422
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000423 # precompute constants into local variables
424 subpatternappend = subpattern.append
425 sourceget = source.get
426 sourcematch = source.match
427 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000428 PATTERNENDERS = _PATTERNENDERS
429 ASSERTCHARS = _ASSERTCHARS
430 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
431 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000432
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000433 while 1:
434
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000435 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000436 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000437 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000438 if this is None:
439 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000440
Fredrik Lundh90a07912000-06-30 07:50:59 +0000441 if state.flags & SRE_FLAG_VERBOSE:
442 # skip whitespace and comments
443 if this in WHITESPACE:
444 continue
445 if this == "#":
446 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000447 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000448 if this in (None, "\n"):
449 break
450 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000451
Fredrik Lundh90a07912000-06-30 07:50:59 +0000452 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000453 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000454
Fredrik Lundh90a07912000-06-30 07:50:59 +0000455 elif this == "[":
456 # character set
457 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000458 setappend = set.append
459## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000460## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000461 if sourcematch("^"):
462 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000463 # check remaining characters
464 start = set[:]
465 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000466 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000467 if this == "]" and set != start:
468 break
469 elif this and this[0] == "\\":
470 code1 = _class_escape(source, this)
471 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000472 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000473 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000474 raise error("unexpected end of regular expression")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000475 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000476 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000477 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000478 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000479 if code1[0] is IN:
480 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000481 setappend(code1)
482 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000483 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000484 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000485 if this[0] == "\\":
486 code2 = _class_escape(source, this)
487 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000488 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000489 if code1[0] != LITERAL or code2[0] != LITERAL:
Collin Winterce36ad82007-08-30 01:19:48 +0000490 raise error("bad character range")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000491 lo = code1[1]
492 hi = code2[1]
493 if hi < lo:
Collin Winterce36ad82007-08-30 01:19:48 +0000494 raise error("bad character range")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000495 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000496 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000497 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000498 else:
499 if code1[0] is IN:
500 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000501 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000502
Fredrik Lundh770617b2001-01-14 15:06:11 +0000503 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000504 if _len(set)==1 and set[0][0] is LITERAL:
505 subpatternappend(set[0]) # optimization
506 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
507 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000508 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000509 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000510 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000511
Fredrik Lundh90a07912000-06-30 07:50:59 +0000512 elif this and this[0] in REPEAT_CHARS:
513 # repeat previous item
514 if this == "?":
515 min, max = 0, 1
516 elif this == "*":
517 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000518
Fredrik Lundh90a07912000-06-30 07:50:59 +0000519 elif this == "+":
520 min, max = 1, MAXREPEAT
521 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000522 if source.next == "}":
523 subpatternappend((LITERAL, ord(this)))
524 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000525 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000526 min, max = 0, MAXREPEAT
527 lo = hi = ""
528 while source.next in DIGITS:
529 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000530 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000531 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000532 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000533 else:
534 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000535 if not sourcematch("}"):
536 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000537 source.seek(here)
538 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000539 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000540 min = int(lo)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200541 if min >= MAXREPEAT:
542 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000543 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000544 max = int(hi)
Serhiy Storchaka70ca0212013-02-16 16:47:47 +0200545 if max >= MAXREPEAT:
546 raise OverflowError("the repetition number is too large")
547 if max < min:
548 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000549 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000550 raise error("not supported")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000551 # figure out which item to repeat
552 if subpattern:
553 item = subpattern[-1:]
554 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000555 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000556 if not item or (_len(item) == 1 and item[0][0] == AT):
Collin Winterce36ad82007-08-30 01:19:48 +0000557 raise error("nothing to repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000558 if item[0][0] in REPEATCODES:
Collin Winterce36ad82007-08-30 01:19:48 +0000559 raise error("multiple repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000560 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000561 subpattern[-1] = (MIN_REPEAT, (min, max, item))
562 else:
563 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000564
Fredrik Lundh90a07912000-06-30 07:50:59 +0000565 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000566 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000567
Fredrik Lundh90a07912000-06-30 07:50:59 +0000568 elif this == "(":
569 group = 1
570 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000571 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000572 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000573 group = 0
574 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000575 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000576 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000577 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000578 # named group: skip forward to end of name
579 name = ""
580 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000581 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000582 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000583 raise error("unterminated name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000584 if char == ">":
585 break
586 name = name + char
587 group = 1
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200588 if not name:
589 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000590 if not isname(name):
Collin Winterce36ad82007-08-30 01:19:48 +0000591 raise error("bad character in group name")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000592 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000593 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000594 name = ""
595 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000596 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000597 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000598 raise error("unterminated name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000599 if char == ")":
600 break
601 name = name + char
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200602 if not name:
603 raise error("missing group name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000604 if not isname(name):
Collin Winterce36ad82007-08-30 01:19:48 +0000605 raise error("bad character in group name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000606 gid = state.groupdict.get(name)
607 if gid is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000608 raise error("unknown group name")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000609 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000610 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000611 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000612 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000613 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000614 raise error("unexpected end of pattern")
615 raise error("unknown specifier: ?P%s" % char)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000616 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000617 # non-capturing group
618 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000619 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000620 # comment
621 while 1:
622 if source.next is None or source.next == ")":
623 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000624 sourceget()
625 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000626 raise error("unbalanced parenthesis")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000627 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000628 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000629 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000630 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000631 dir = 1
632 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000633 if source.next not in LOOKBEHINDASSERTCHARS:
Collin Winterce36ad82007-08-30 01:19:48 +0000634 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000635 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000636 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000637 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000638 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000639 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000640 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000641 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000642 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000643 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000644 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000645 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000646 # conditional backreference group
647 condname = ""
648 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000649 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000650 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000651 raise error("unterminated name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000652 if char == ")":
653 break
654 condname = condname + char
655 group = 2
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200656 if not condname:
657 raise error("missing group name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000658 if isname(condname):
659 condgroup = state.groupdict.get(condname)
660 if condgroup is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000661 raise error("unknown group name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000662 else:
663 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000664 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000665 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000666 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000667 else:
668 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000669 if not source.next in FLAGS:
Collin Winterce36ad82007-08-30 01:19:48 +0000670 raise error("unexpected end of pattern")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000671 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000672 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000673 if group:
674 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000675 if group == 2:
676 # anonymous group
677 group = None
678 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000679 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000680 if condgroup:
681 p = _parse_sub_cond(source, state, condgroup)
682 else:
683 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000684 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000685 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000686 if group is not None:
687 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000688 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000689 else:
690 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000691 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000692 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000693 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000694 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000695 break
Collin Winterce36ad82007-08-30 01:19:48 +0000696 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000697
Fredrik Lundh90a07912000-06-30 07:50:59 +0000698 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000699 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000700
Fredrik Lundh90a07912000-06-30 07:50:59 +0000701 elif this == "$":
702 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000703
Fredrik Lundh90a07912000-06-30 07:50:59 +0000704 elif this and this[0] == "\\":
705 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000706 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000707
Fredrik Lundh90a07912000-06-30 07:50:59 +0000708 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000709 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000710
711 return subpattern
712
Antoine Pitroufd036452008-08-19 17:56:33 +0000713def fix_flags(src, flags):
714 # Check and fix flags according to the type of pattern (str or bytes)
715 if isinstance(src, str):
716 if not flags & SRE_FLAG_ASCII:
717 flags |= SRE_FLAG_UNICODE
718 elif flags & SRE_FLAG_UNICODE:
719 raise ValueError("ASCII and UNICODE flags are incompatible")
720 else:
721 if flags & SRE_FLAG_UNICODE:
722 raise ValueError("can't use UNICODE flag with a bytes pattern")
723 return flags
724
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000725def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000726 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000727
728 source = Tokenizer(str)
729
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000730 if pattern is None:
731 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000732 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000733 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000734
735 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000736 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000737
738 tail = source.get()
739 if tail == ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000740 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000741 elif tail:
Collin Winterce36ad82007-08-30 01:19:48 +0000742 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000743
Fredrik Lundh770617b2001-01-14 15:06:11 +0000744 if flags & SRE_FLAG_DEBUG:
745 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000746
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000747 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
748 # the VERBOSE flag was switched on inside the pattern. to be
749 # on the safe side, we'll parse the whole thing again...
750 return parse(str, p.pattern.flags)
751
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000752 return p
753
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000754def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000755 # parse 're' replacement string into list of literals and
756 # group references
757 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000758 sget = s.get
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000759 p = []
760 a = p.append
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000761 def literal(literal, p=p, pappend=a):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000762 if p and p[-1][0] is LITERAL:
763 p[-1] = LITERAL, p[-1][1] + literal
764 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000765 pappend((LITERAL, literal))
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000766 sep = source[:0]
Guido van Rossum13257902007-06-07 23:15:56 +0000767 if isinstance(sep, str):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000768 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000769 else:
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000770 makechar = chr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000771 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000772 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000773 if this is None:
774 break # end of replacement string
775 if this and this[0] == "\\":
776 # group
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000777 c = this[1:2]
778 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000779 name = ""
780 if s.match("<"):
781 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000782 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000783 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000784 raise error("unterminated group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000785 if char == ">":
786 break
787 name = name + char
788 if not name:
Ezio Melotti0941d9f2012-11-03 20:33:08 +0200789 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000790 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000791 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000792 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000793 raise error("negative group number")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000794 except ValueError:
795 if not isname(name):
Collin Winterce36ad82007-08-30 01:19:48 +0000796 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000797 try:
798 index = pattern.groupindex[name]
799 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +0000800 raise IndexError("unknown group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000801 a((MARK, index))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000802 elif c == "0":
803 if s.next in OCTDIGITS:
804 this = this + sget()
805 if s.next in OCTDIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000806 this = this + sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000807 literal(makechar(int(this[1:], 8) & 0xff))
808 elif c in DIGITS:
809 isoctal = False
810 if s.next in DIGITS:
811 this = this + sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000812 if (c in OCTDIGITS and this[2] in OCTDIGITS and
813 s.next in OCTDIGITS):
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000814 this = this + sget()
815 isoctal = True
816 literal(makechar(int(this[1:], 8) & 0xff))
817 if not isoctal:
818 a((MARK, int(this[1:])))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000819 else:
820 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000821 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000822 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000823 pass
824 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000825 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000826 literal(this)
827 # convert template to groups and literals lists
828 i = 0
829 groups = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000830 groupsappend = groups.append
831 literals = [None] * len(p)
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000832 if isinstance(source, str):
833 encode = lambda x: x
834 else:
835 # The tokenizer implicitly decodes bytes objects as latin-1, we must
836 # therefore re-encode the final representation.
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000837 encode = lambda x: x.encode('latin-1')
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000838 for c, s in p:
839 if c is MARK:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000840 groupsappend((i, s))
841 # literal[i] is already None
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000842 else:
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000843 literals[i] = encode(s)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000844 i = i + 1
845 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000846
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000847def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000848 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000849 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000850 groups, literals = template
851 literals = literals[:]
852 try:
853 for index, group in groups:
854 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000855 if s is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000856 raise error("unmatched group")
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000857 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000858 raise error("invalid group reference")
Barry Warsaw8bee7612004-08-25 02:22:30 +0000859 return sep.join(literals)