blob: d358646a39aed6ddcdaaea599e12f31a2e9f6286 [file] [log] [blame]
Guido van Rossum7627c0d2000-03-31 14:58:54 +00001#
2# Secret Labs' Regular Expression Engine
Guido van Rossum7627c0d2000-03-31 14:58:54 +00003#
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +00004# convert re-style regular expression to sre pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +00005#
Fredrik Lundh770617b2001-01-14 15:06:11 +00006# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
Guido van Rossum7627c0d2000-03-31 14:58:54 +00007#
Fredrik Lundh29c4ba92000-08-01 18:20:07 +00008# See the sre.py file for information on usage and redistribution.
Guido van Rossum7627c0d2000-03-31 14:58:54 +00009#
10
Fred Drakeb8f22742001-09-04 19:10:20 +000011"""Internal support module for sre"""
12
Fredrik Lundh470ea5a2001-01-14 21:00:44 +000013# XXX: show string offset and offending character for all errors
14
Barry Warsaw8bee7612004-08-25 02:22:30 +000015import sys
Guido van Rossum7627c0d2000-03-31 14:58:54 +000016
17from sre_constants import *
18
19SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000020REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000021
Raymond Hettinger049ade22005-02-28 19:27:52 +000022DIGITS = set("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000023
Raymond Hettinger049ade22005-02-28 19:27:52 +000024OCTDIGITS = set("01234567")
25HEXDIGITS = set("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000026
Raymond Hettinger049ade22005-02-28 19:27:52 +000027WHITESPACE = set(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000028
Guido van Rossum7627c0d2000-03-31 14:58:54 +000029ESCAPES = {
Fredrik Lundhf2989b22001-02-18 12:05:16 +000030 r"\a": (LITERAL, ord("\a")),
31 r"\b": (LITERAL, ord("\b")),
32 r"\f": (LITERAL, ord("\f")),
33 r"\n": (LITERAL, ord("\n")),
34 r"\r": (LITERAL, ord("\r")),
35 r"\t": (LITERAL, ord("\t")),
36 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000037 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000038}
39
40CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000041 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000042 r"\b": (AT, AT_BOUNDARY),
43 r"\B": (AT, AT_NON_BOUNDARY),
44 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
45 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
46 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
47 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
48 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
49 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000050 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000051}
52
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000053FLAGS = {
Fredrik Lundh436c3d582000-06-29 08:58:44 +000054 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000055 "i": SRE_FLAG_IGNORECASE,
56 "L": SRE_FLAG_LOCALE,
57 "m": SRE_FLAG_MULTILINE,
58 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000059 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000060 # extensions
Antoine Pitroufd036452008-08-19 17:56:33 +000061 "a": SRE_FLAG_ASCII,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000062 "t": SRE_FLAG_TEMPLATE,
63 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000064}
65
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000066class Pattern:
67 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000068 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000069 self.flags = 0
Fredrik Lundhebc37b22000-10-28 19:30:41 +000070 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000071 self.groups = 1
72 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000073 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000074 gid = self.groups
75 self.groups = gid + 1
Raymond Hettingerf13eb552002-06-02 00:40:05 +000076 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000077 ogid = self.groupdict.get(name, None)
78 if ogid is not None:
Collin Winterce36ad82007-08-30 01:19:48 +000079 raise error("redefinition of group name %s as group %d; "
80 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000081 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000082 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000083 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000084 def closegroup(self, gid):
85 self.open.remove(gid)
86 def checkgroup(self, gid):
87 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000088
89class SubPattern:
90 # a subpattern, in intermediate form
91 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000092 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000093 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000094 data = []
95 self.data = data
96 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000097 def dump(self, level=0):
98 nl = 1
Guido van Rossum13257902007-06-07 23:15:56 +000099 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000100 for op, av in self.data:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000101 print(level*" " + op, end=' '); nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000102 if op == "in":
103 # member sublanguage
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000104 print(); nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000105 for op, a in av:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000106 print((level+1)*" " + op, a)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000107 elif op == "branch":
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000108 print(); nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000109 i = 0
110 for a in av[1]:
111 if i > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000112 print(level*" " + "or")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000113 a.dump(level+1); nl = 1
114 i = i + 1
Guido van Rossum13257902007-06-07 23:15:56 +0000115 elif isinstance(av, seqtypes):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000116 for a in av:
117 if isinstance(a, SubPattern):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000118 if not nl: print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000119 a.dump(level+1); nl = 1
120 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000121 print(a, end=' ') ; nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000122 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000123 print(av, end=' ') ; nl = 0
124 if not nl: print()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000125 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000126 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000127 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000128 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000129 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000130 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000131 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000132 if isinstance(index, slice):
133 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000134 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000135 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000136 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000137 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000138 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000139 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000140 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000141 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000142 # determine the width (min, max) for this subpattern
143 if self.width:
144 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000145 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000146 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
147 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000148 for op, av in self.data:
149 if op is BRANCH:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000150 i = sys.maxsize
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000151 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000152 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000153 l, h = av.getwidth()
154 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000155 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000156 lo = lo + i
157 hi = hi + j
158 elif op is CALL:
159 i, j = av.getwidth()
160 lo = lo + i
161 hi = hi + j
162 elif op is SUBPATTERN:
163 i, j = av[1].getwidth()
164 lo = lo + i
165 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000166 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000167 i, j = av[2].getwidth()
Guido van Rossume2a383d2007-01-15 16:59:06 +0000168 lo = lo + int(i) * av[0]
169 hi = hi + int(j) * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000170 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000171 lo = lo + 1
172 hi = hi + 1
173 elif op == SUCCESS:
174 break
Christian Heimesa37d4c62007-12-04 23:02:19 +0000175 self.width = int(min(lo, sys.maxsize)), int(min(hi, sys.maxsize))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000176 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000177
178class Tokenizer:
179 def __init__(self, string):
Antoine Pitrou463badf2012-06-23 13:29:19 +0200180 self.istext = isinstance(string, str)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000181 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000182 self.index = 0
183 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000184 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000185 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000186 self.next = None
187 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000188 char = self.string[self.index:self.index+1]
189 # Special case for the str8, since indexing returns a integer
190 # XXX This is only needed for test_bug_926075 in test_re.py
Antoine Pitrou463badf2012-06-23 13:29:19 +0200191 if char and not self.istext:
Thomas Wouters40a088d2008-03-18 20:19:54 +0000192 char = chr(char[0])
Guido van Rossum75a902d2007-10-19 22:06:24 +0000193 if char == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000194 try:
195 c = self.string[self.index + 1]
196 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000197 raise error("bogus escape (end of line)")
Antoine Pitrou463badf2012-06-23 13:29:19 +0200198 if not self.istext:
Antoine Pitrou22628c42008-07-22 17:53:22 +0000199 c = chr(c)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000200 char = char + c
201 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000202 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000203 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000204 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000205 if skip:
206 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000207 return 1
208 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000209 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000210 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000211 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000212 return this
Antoine Pitrou463badf2012-06-23 13:29:19 +0200213 def getwhile(self, n, charset):
214 result = ''
215 for _ in range(n):
216 c = self.next
217 if c not in charset:
218 break
219 result += c
220 self.__next()
221 return result
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000222 def tell(self):
223 return self.index, self.next
224 def seek(self, index):
225 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000226
Fredrik Lundh4781b072000-06-29 12:38:45 +0000227def isident(char):
228 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
229
230def isdigit(char):
231 return "0" <= char <= "9"
232
233def isname(name):
234 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000235 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000236 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000237 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000238 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000239 return False
240 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000241
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000242def _class_escape(source, escape):
243 # handle escape code inside character class
244 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000245 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000246 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000247 code = CATEGORIES.get(escape)
248 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000249 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000250 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000251 c = escape[1:2]
252 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000253 # hexadecimal escape (exactly two digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200254 escape += source.getwhile(2, HEXDIGITS)
255 if len(escape) != 4:
256 raise ValueError
257 return LITERAL, int(escape[2:], 16) & 0xff
258 elif c == "u" and source.istext:
259 # unicode escape (exactly four digits)
260 escape += source.getwhile(4, HEXDIGITS)
261 if len(escape) != 6:
262 raise ValueError
263 return LITERAL, int(escape[2:], 16)
264 elif c == "U" and source.istext:
265 # unicode escape (exactly eight digits)
266 escape += source.getwhile(8, HEXDIGITS)
267 if len(escape) != 10:
268 raise ValueError
269 c = int(escape[2:], 16)
270 chr(c) # raise ValueError for invalid code
271 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000272 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000273 # octal escape (up to three digits)
Antoine Pitrou463badf2012-06-23 13:29:19 +0200274 escape += source.getwhile(2, OCTDIGITS)
275 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000276 elif c in DIGITS:
Antoine Pitrou463badf2012-06-23 13:29:19 +0200277 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000278 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000279 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000280 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000281 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000282 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000283
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000284def _escape(source, escape, state):
285 # handle escape code in expression
286 code = CATEGORIES.get(escape)
287 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000288 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000289 code = ESCAPES.get(escape)
290 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000291 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000292 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000293 c = escape[1:2]
294 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000295 # hexadecimal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200296 escape += source.getwhile(2, HEXDIGITS)
Fredrik Lundh143328b2000-09-02 11:03:34 +0000297 if len(escape) != 4:
298 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000299 return LITERAL, int(escape[2:], 16) & 0xff
Antoine Pitrou463badf2012-06-23 13:29:19 +0200300 elif c == "u" and source.istext:
301 # unicode escape (exactly four digits)
302 escape += source.getwhile(4, HEXDIGITS)
303 if len(escape) != 6:
304 raise ValueError
305 return LITERAL, int(escape[2:], 16)
306 elif c == "U" and source.istext:
307 # unicode escape (exactly eight digits)
308 escape += source.getwhile(8, HEXDIGITS)
309 if len(escape) != 10:
310 raise ValueError
311 c = int(escape[2:], 16)
312 chr(c) # raise ValueError for invalid code
313 return LITERAL, c
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000314 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000315 # octal escape
Antoine Pitrou463badf2012-06-23 13:29:19 +0200316 escape += source.getwhile(2, OCTDIGITS)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000317 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000318 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000319 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000320 if source.next in DIGITS:
321 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000322 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
323 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000324 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000325 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000326 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000327 # not an octal escape, so this is a group reference
328 group = int(escape[1:])
329 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000330 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000331 raise error("cannot refer to open group")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000332 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000333 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000334 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000335 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000336 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000337 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000338 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000339
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000340def _parse_sub(source, state, nested=1):
341 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000342
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000343 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000344 itemsappend = items.append
345 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000346 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000347 itemsappend(_parse(source, state))
348 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000349 continue
350 if not nested:
351 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000352 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000353 break
354 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000355 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000356
357 if len(items) == 1:
358 return items[0]
359
360 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000361 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000362
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000363 # check if all items share a common prefix
364 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000365 prefix = None
366 for item in items:
367 if not item:
368 break
369 if prefix is None:
370 prefix = item[0]
371 elif item[0] != prefix:
372 break
373 else:
374 # all subitems start with a common "prefix".
375 # move it out of the branch
376 for item in items:
377 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000378 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000379 continue # check next one
380 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000381
382 # check if the branch can be replaced by a character set
383 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000384 if len(item) != 1 or item[0][0] != LITERAL:
385 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000386 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000387 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000388 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000389 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000390 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000391 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000392 setappend(item[0])
393 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000394 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000395
396 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000397 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000398
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000399def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000400 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000401 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000402 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000403 if source.match("|"):
Collin Winterce36ad82007-08-30 01:19:48 +0000404 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000405 else:
406 item_no = None
407 if source.next and not source.match(")", 0):
Collin Winterce36ad82007-08-30 01:19:48 +0000408 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000409 subpattern = SubPattern(state)
410 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
411 return subpattern
412
Raymond Hettinger049ade22005-02-28 19:27:52 +0000413_PATTERNENDERS = set("|)")
414_ASSERTCHARS = set("=!<")
415_LOOKBEHINDASSERTCHARS = set("=!")
416_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
417
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000418def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000419 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000420 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000421
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000422 # precompute constants into local variables
423 subpatternappend = subpattern.append
424 sourceget = source.get
425 sourcematch = source.match
426 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000427 PATTERNENDERS = _PATTERNENDERS
428 ASSERTCHARS = _ASSERTCHARS
429 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
430 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000431
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000432 while 1:
433
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000434 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000435 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000436 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000437 if this is None:
438 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000439
Fredrik Lundh90a07912000-06-30 07:50:59 +0000440 if state.flags & SRE_FLAG_VERBOSE:
441 # skip whitespace and comments
442 if this in WHITESPACE:
443 continue
444 if this == "#":
445 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000446 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000447 if this in (None, "\n"):
448 break
449 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000450
Fredrik Lundh90a07912000-06-30 07:50:59 +0000451 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000452 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000453
Fredrik Lundh90a07912000-06-30 07:50:59 +0000454 elif this == "[":
455 # character set
456 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000457 setappend = set.append
458## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000459## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000460 if sourcematch("^"):
461 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000462 # check remaining characters
463 start = set[:]
464 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000465 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000466 if this == "]" and set != start:
467 break
468 elif this and this[0] == "\\":
469 code1 = _class_escape(source, this)
470 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000471 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000472 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000473 raise error("unexpected end of regular expression")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000474 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000475 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000476 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000477 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000478 if code1[0] is IN:
479 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000480 setappend(code1)
481 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000482 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000483 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000484 if this[0] == "\\":
485 code2 = _class_escape(source, this)
486 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000487 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000488 if code1[0] != LITERAL or code2[0] != LITERAL:
Collin Winterce36ad82007-08-30 01:19:48 +0000489 raise error("bad character range")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000490 lo = code1[1]
491 hi = code2[1]
492 if hi < lo:
Collin Winterce36ad82007-08-30 01:19:48 +0000493 raise error("bad character range")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000494 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000495 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000496 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000497 else:
498 if code1[0] is IN:
499 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000500 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000501
Fredrik Lundh770617b2001-01-14 15:06:11 +0000502 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000503 if _len(set)==1 and set[0][0] is LITERAL:
504 subpatternappend(set[0]) # optimization
505 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
506 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000507 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000508 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000509 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000510
Fredrik Lundh90a07912000-06-30 07:50:59 +0000511 elif this and this[0] in REPEAT_CHARS:
512 # repeat previous item
513 if this == "?":
514 min, max = 0, 1
515 elif this == "*":
516 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000517
Fredrik Lundh90a07912000-06-30 07:50:59 +0000518 elif this == "+":
519 min, max = 1, MAXREPEAT
520 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000521 if source.next == "}":
522 subpatternappend((LITERAL, ord(this)))
523 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000524 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000525 min, max = 0, MAXREPEAT
526 lo = hi = ""
527 while source.next in DIGITS:
528 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000529 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000530 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000531 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000532 else:
533 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000534 if not sourcematch("}"):
535 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000536 source.seek(here)
537 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000538 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000539 min = int(lo)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000540 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000541 max = int(hi)
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000542 if max < min:
Collin Winterce36ad82007-08-30 01:19:48 +0000543 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000544 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000545 raise error("not supported")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000546 # figure out which item to repeat
547 if subpattern:
548 item = subpattern[-1:]
549 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000550 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000551 if not item or (_len(item) == 1 and item[0][0] == AT):
Collin Winterce36ad82007-08-30 01:19:48 +0000552 raise error("nothing to repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000553 if item[0][0] in REPEATCODES:
Collin Winterce36ad82007-08-30 01:19:48 +0000554 raise error("multiple repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000555 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000556 subpattern[-1] = (MIN_REPEAT, (min, max, item))
557 else:
558 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000559
Fredrik Lundh90a07912000-06-30 07:50:59 +0000560 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000561 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000562
Fredrik Lundh90a07912000-06-30 07:50:59 +0000563 elif this == "(":
564 group = 1
565 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000566 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000567 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000568 group = 0
569 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000570 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000571 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000572 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000573 # named group: skip forward to end of name
574 name = ""
575 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000576 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000577 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000578 raise error("unterminated name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000579 if char == ">":
580 break
581 name = name + char
582 group = 1
583 if not isname(name):
Collin Winterce36ad82007-08-30 01:19:48 +0000584 raise error("bad character in group name")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000585 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000586 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000587 name = ""
588 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000589 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000590 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000591 raise error("unterminated name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000592 if char == ")":
593 break
594 name = name + char
595 if not isname(name):
Collin Winterce36ad82007-08-30 01:19:48 +0000596 raise error("bad character in group name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000597 gid = state.groupdict.get(name)
598 if gid is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000599 raise error("unknown group name")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000600 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000601 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000602 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000603 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000604 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000605 raise error("unexpected end of pattern")
606 raise error("unknown specifier: ?P%s" % char)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000607 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000608 # non-capturing group
609 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000610 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000611 # comment
612 while 1:
613 if source.next is None or source.next == ")":
614 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000615 sourceget()
616 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000617 raise error("unbalanced parenthesis")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000618 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000619 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000620 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000621 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000622 dir = 1
623 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000624 if source.next not in LOOKBEHINDASSERTCHARS:
Collin Winterce36ad82007-08-30 01:19:48 +0000625 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000626 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000627 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000628 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000629 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000630 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000631 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000632 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000633 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000634 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000635 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000636 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000637 # conditional backreference group
638 condname = ""
639 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000640 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000641 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000642 raise error("unterminated name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000643 if char == ")":
644 break
645 condname = condname + char
646 group = 2
647 if isname(condname):
648 condgroup = state.groupdict.get(condname)
649 if condgroup is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000650 raise error("unknown group name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000651 else:
652 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000653 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000654 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000655 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000656 else:
657 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000658 if not source.next in FLAGS:
Collin Winterce36ad82007-08-30 01:19:48 +0000659 raise error("unexpected end of pattern")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000660 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000661 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000662 if group:
663 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000664 if group == 2:
665 # anonymous group
666 group = None
667 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000668 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000669 if condgroup:
670 p = _parse_sub_cond(source, state, condgroup)
671 else:
672 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000673 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000674 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000675 if group is not None:
676 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000677 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000678 else:
679 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000680 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000681 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000682 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000683 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000684 break
Collin Winterce36ad82007-08-30 01:19:48 +0000685 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000686
Fredrik Lundh90a07912000-06-30 07:50:59 +0000687 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000688 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000689
Fredrik Lundh90a07912000-06-30 07:50:59 +0000690 elif this == "$":
691 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000692
Fredrik Lundh90a07912000-06-30 07:50:59 +0000693 elif this and this[0] == "\\":
694 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000695 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000696
Fredrik Lundh90a07912000-06-30 07:50:59 +0000697 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000698 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000699
700 return subpattern
701
Antoine Pitroufd036452008-08-19 17:56:33 +0000702def fix_flags(src, flags):
703 # Check and fix flags according to the type of pattern (str or bytes)
704 if isinstance(src, str):
705 if not flags & SRE_FLAG_ASCII:
706 flags |= SRE_FLAG_UNICODE
707 elif flags & SRE_FLAG_UNICODE:
708 raise ValueError("ASCII and UNICODE flags are incompatible")
709 else:
710 if flags & SRE_FLAG_UNICODE:
711 raise ValueError("can't use UNICODE flag with a bytes pattern")
712 return flags
713
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000714def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000715 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000716
717 source = Tokenizer(str)
718
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000719 if pattern is None:
720 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000721 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000722 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000723
724 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000725 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000726
727 tail = source.get()
728 if tail == ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000729 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000730 elif tail:
Collin Winterce36ad82007-08-30 01:19:48 +0000731 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000732
Fredrik Lundh770617b2001-01-14 15:06:11 +0000733 if flags & SRE_FLAG_DEBUG:
734 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000735
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000736 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
737 # the VERBOSE flag was switched on inside the pattern. to be
738 # on the safe side, we'll parse the whole thing again...
739 return parse(str, p.pattern.flags)
740
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000741 return p
742
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000743def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000744 # parse 're' replacement string into list of literals and
745 # group references
746 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000747 sget = s.get
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000748 p = []
749 a = p.append
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000750 def literal(literal, p=p, pappend=a):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000751 if p and p[-1][0] is LITERAL:
752 p[-1] = LITERAL, p[-1][1] + literal
753 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000754 pappend((LITERAL, literal))
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000755 sep = source[:0]
Guido van Rossum13257902007-06-07 23:15:56 +0000756 if isinstance(sep, str):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000757 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000758 else:
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000759 makechar = chr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000760 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000761 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000762 if this is None:
763 break # end of replacement string
764 if this and this[0] == "\\":
765 # group
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000766 c = this[1:2]
767 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000768 name = ""
769 if s.match("<"):
770 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000771 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000772 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000773 raise error("unterminated group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000774 if char == ">":
775 break
776 name = name + char
777 if not name:
Collin Winterce36ad82007-08-30 01:19:48 +0000778 raise error("bad group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000779 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000780 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000781 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000782 raise error("negative group number")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000783 except ValueError:
784 if not isname(name):
Collin Winterce36ad82007-08-30 01:19:48 +0000785 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000786 try:
787 index = pattern.groupindex[name]
788 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +0000789 raise IndexError("unknown group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000790 a((MARK, index))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000791 elif c == "0":
792 if s.next in OCTDIGITS:
793 this = this + sget()
794 if s.next in OCTDIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000795 this = this + sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000796 literal(makechar(int(this[1:], 8) & 0xff))
797 elif c in DIGITS:
798 isoctal = False
799 if s.next in DIGITS:
800 this = this + sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000801 if (c in OCTDIGITS and this[2] in OCTDIGITS and
802 s.next in OCTDIGITS):
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000803 this = this + sget()
804 isoctal = True
805 literal(makechar(int(this[1:], 8) & 0xff))
806 if not isoctal:
807 a((MARK, int(this[1:])))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000808 else:
809 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000810 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000811 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000812 pass
813 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000814 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000815 literal(this)
816 # convert template to groups and literals lists
817 i = 0
818 groups = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000819 groupsappend = groups.append
820 literals = [None] * len(p)
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000821 if isinstance(source, str):
822 encode = lambda x: x
823 else:
824 # The tokenizer implicitly decodes bytes objects as latin-1, we must
825 # therefore re-encode the final representation.
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000826 encode = lambda x: x.encode('latin-1')
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000827 for c, s in p:
828 if c is MARK:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000829 groupsappend((i, s))
830 # literal[i] is already None
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000831 else:
Ezio Melottib92ed7c2010-03-06 15:24:08 +0000832 literals[i] = encode(s)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000833 i = i + 1
834 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000835
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000836def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000837 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000838 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000839 groups, literals = template
840 literals = literals[:]
841 try:
842 for index, group in groups:
843 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000844 if s is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000845 raise error("unmatched group")
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000846 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000847 raise error("invalid group reference")
Barry Warsaw8bee7612004-08-25 02:22:30 +0000848 return sep.join(literals)