blob: 9cbbc0254e8647db64699ade1a3b0513e93f5bda [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#
6# Copyright (c) 1998-2000 by Secret Labs AB. All rights reserved.
7#
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
Guido van Rossum7627c0d2000-03-31 14:58:54 +000011import string, sys
12
13from sre_constants import *
14
Fredrik Lundh3562f112000-07-02 12:00:07 +000015MAXREPEAT = 65535
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000016
Guido van Rossum7627c0d2000-03-31 14:58:54 +000017SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000018REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000019
Tim Peters17289422000-09-02 07:44:32 +000020DIGITS = tuple("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000021
Fredrik Lundh75f2d672000-06-29 11:34:28 +000022OCTDIGITS = tuple("01234567")
23HEXDIGITS = tuple("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000024
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000025WHITESPACE = tuple(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000026
Guido van Rossum7627c0d2000-03-31 14:58:54 +000027ESCAPES = {
Fredrik Lundh0640e112000-06-30 13:55:15 +000028 r"\a": (LITERAL, 7),
29 r"\b": (LITERAL, 8),
30 r"\f": (LITERAL, 12),
31 r"\n": (LITERAL, 10),
32 r"\r": (LITERAL, 13),
33 r"\t": (LITERAL, 9),
34 r"\v": (LITERAL, 11),
35 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000036}
37
38CATEGORIES = {
Fredrik Lundh01016fe2000-06-30 00:27:46 +000039 r"\A": (AT, AT_BEGINNING), # start of string
40 r"\b": (AT, AT_BOUNDARY),
41 r"\B": (AT, AT_NON_BOUNDARY),
42 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
43 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
44 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
45 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
46 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
47 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
48 r"\Z": (AT, AT_END), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000049}
50
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000051FLAGS = {
Fredrik Lundh436c3d582000-06-29 08:58:44 +000052 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000053 "i": SRE_FLAG_IGNORECASE,
54 "L": SRE_FLAG_LOCALE,
55 "m": SRE_FLAG_MULTILINE,
56 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000057 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000058 # extensions
59 "t": SRE_FLAG_TEMPLATE,
60 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000061}
62
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000063class Pattern:
64 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000065 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000066 self.flags = 0
67 self.groups = 1
68 self.groupdict = {}
Guido van Rossum7627c0d2000-03-31 14:58:54 +000069 def getgroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000070 gid = self.groups
71 self.groups = gid + 1
72 if name:
73 self.groupdict[name] = gid
74 return gid
Guido van Rossum7627c0d2000-03-31 14:58:54 +000075
76class SubPattern:
77 # a subpattern, in intermediate form
78 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000079 self.pattern = pattern
80 if not data:
81 data = []
82 self.data = data
83 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000084 def dump(self, level=0):
85 nl = 1
86 for op, av in self.data:
87 print level*" " + op,; nl = 0
88 if op == "in":
89 # member sublanguage
90 print; nl = 1
91 for op, a in av:
92 print (level+1)*" " + op, a
93 elif op == "branch":
94 print; nl = 1
95 i = 0
96 for a in av[1]:
97 if i > 0:
98 print level*" " + "or"
99 a.dump(level+1); nl = 1
100 i = i + 1
101 elif type(av) in (type(()), type([])):
102 for a in av:
103 if isinstance(a, SubPattern):
104 if not nl: print
105 a.dump(level+1); nl = 1
106 else:
107 print a, ; nl = 0
108 else:
109 print av, ; nl = 0
110 if not nl: print
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000111 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000112 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000113 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000114 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000115 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000116 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000117 def __getitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000118 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000119 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000120 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000121 def __getslice__(self, start, stop):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000122 return SubPattern(self.pattern, self.data[start:stop])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000123 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000124 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000125 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000126 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000127 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000128 # determine the width (min, max) for this subpattern
129 if self.width:
130 return self.width
131 lo = hi = 0L
132 for op, av in self.data:
133 if op is BRANCH:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000134 i = sys.maxint
135 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000136 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000137 l, h = av.getwidth()
138 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000139 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000140 lo = lo + i
141 hi = hi + j
142 elif op is CALL:
143 i, j = av.getwidth()
144 lo = lo + i
145 hi = hi + j
146 elif op is SUBPATTERN:
147 i, j = av[1].getwidth()
148 lo = lo + i
149 hi = hi + j
150 elif op in (MIN_REPEAT, MAX_REPEAT):
151 i, j = av[2].getwidth()
152 lo = lo + long(i) * av[0]
153 hi = hi + long(j) * av[1]
154 elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY):
155 lo = lo + 1
156 hi = hi + 1
157 elif op == SUCCESS:
158 break
159 self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint))
160 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000161
162class Tokenizer:
163 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000164 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000165 self.index = 0
166 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000167 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000168 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000169 self.next = None
170 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000171 char = self.string[self.index]
172 if char[0] == "\\":
173 try:
174 c = self.string[self.index + 1]
175 except IndexError:
176 raise error, "bogus escape"
177 char = char + c
178 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000179 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000180 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000181 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000182 if skip:
183 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000184 return 1
185 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000186 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000187 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000188 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000189 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000190 def tell(self):
191 return self.index, self.next
192 def seek(self, index):
193 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000194
Fredrik Lundh4781b072000-06-29 12:38:45 +0000195def isident(char):
196 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
197
198def isdigit(char):
199 return "0" <= char <= "9"
200
201def isname(name):
202 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000203 if not isident(name[0]):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000204 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000205 for char in name:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000206 if not isident(char) and not isdigit(char):
207 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000208 return 1
209
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000210def _group(escape, groups):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000211 # check if the escape string represents a valid group
212 try:
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000213 gid = int(escape[1:])
214 if gid and gid < groups:
215 return gid
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000216 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000217 pass
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000218 return None # not a valid group
219
220def _class_escape(source, escape):
221 # handle escape code inside character class
222 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000223 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000224 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000225 code = CATEGORIES.get(escape)
226 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000227 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000228 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000229 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000230 # hexadecimal escape (exactly two digits)
231 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000232 escape = escape + source.get()
233 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000234 if len(escape) != 2:
235 raise error, "bogus escape: %s" % repr("\\" + escape)
236 return LITERAL, int(escape, 16) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000237 elif str(escape[1:2]) in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000238 # octal escape (up to three digits)
239 while source.next in OCTDIGITS and len(escape) < 5:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000240 escape = escape + source.get()
241 escape = escape[1:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000242 return LITERAL, int(escape, 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000243 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000244 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000245 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000246 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000247 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000248
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000249def _escape(source, escape, state):
250 # handle escape code in expression
251 code = CATEGORIES.get(escape)
252 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000253 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000254 code = ESCAPES.get(escape)
255 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000256 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000257 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000258 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000259 # hexadecimal escape
260 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000261 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000262 if len(escape) != 4:
263 raise ValueError
264 return LITERAL, int(escape[2:], 16) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000265 elif escape[1:2] == "0":
266 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000267 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000268 escape = escape + source.get()
269 return LITERAL, int(escape[1:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000270 elif escape[1:2] in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000271 # octal escape *or* decimal group reference (sigh)
272 here = source.tell()
273 if source.next in DIGITS:
274 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000275 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
276 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000277 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000278 escape = escape + source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000279 return LITERAL, int(escape[1:], 8) & 0xff
280 # got at least one decimal digit; this is a group reference
281 group = _group(escape, state.groups)
282 if group:
283 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000284 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000285 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000286 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000287 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000288 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000289 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000290
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000291def _parse_sub(source, state, nested=1):
292 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000293
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000294 items = []
295 while 1:
296 items.append(_parse(source, state))
297 if source.match("|"):
298 continue
299 if not nested:
300 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000301 if not source.next or source.match(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000302 break
303 else:
304 raise error, "pattern not properly closed"
305
306 if len(items) == 1:
307 return items[0]
308
309 subpattern = SubPattern(state)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000310
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000311 # check if all items share a common prefix
312 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000313 prefix = None
314 for item in items:
315 if not item:
316 break
317 if prefix is None:
318 prefix = item[0]
319 elif item[0] != prefix:
320 break
321 else:
322 # all subitems start with a common "prefix".
323 # move it out of the branch
324 for item in items:
325 del item[0]
326 subpattern.append(prefix)
327 continue # check next one
328 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000329
330 # check if the branch can be replaced by a character set
331 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000332 if len(item) != 1 or item[0][0] != LITERAL:
333 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000334 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000335 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000336 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000337 set = []
338 for item in items:
339 set.append(item[0])
340 subpattern.append((IN, set))
341 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000342
343 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000344 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000345
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000346def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000347 # parse a simple pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000348
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000349 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000350
351 while 1:
352
Fredrik Lundh90a07912000-06-30 07:50:59 +0000353 if source.next in ("|", ")"):
354 break # end of subpattern
355 this = source.get()
356 if this is None:
357 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000358
Fredrik Lundh90a07912000-06-30 07:50:59 +0000359 if state.flags & SRE_FLAG_VERBOSE:
360 # skip whitespace and comments
361 if this in WHITESPACE:
362 continue
363 if this == "#":
364 while 1:
365 this = source.get()
366 if this in (None, "\n"):
367 break
368 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000369
Fredrik Lundh90a07912000-06-30 07:50:59 +0000370 if this and this[0] not in SPECIAL_CHARS:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000371 subpattern.append((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000372
Fredrik Lundh90a07912000-06-30 07:50:59 +0000373 elif this == "[":
374 # character set
375 set = []
376## if source.match(":"):
377## pass # handle character classes
378 if source.match("^"):
379 set.append((NEGATE, None))
380 # check remaining characters
381 start = set[:]
382 while 1:
383 this = source.get()
384 if this == "]" and set != start:
385 break
386 elif this and this[0] == "\\":
387 code1 = _class_escape(source, this)
388 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000389 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000390 else:
391 raise error, "unexpected end of regular expression"
392 if source.match("-"):
393 # potential range
394 this = source.get()
395 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000396 if code1[0] is IN:
397 code1 = code1[1][0]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000398 set.append(code1)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000399 set.append((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000400 break
401 else:
402 if this[0] == "\\":
403 code2 = _class_escape(source, this)
404 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000405 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000406 if code1[0] != LITERAL or code2[0] != LITERAL:
407 raise error, "illegal range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000408 lo = code1[1]
409 hi = code2[1]
410 if hi < lo:
411 raise error, "illegal range"
412 set.append((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000413 else:
414 if code1[0] is IN:
415 code1 = code1[1][0]
416 set.append(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000417
Fredrik Lundh90a07912000-06-30 07:50:59 +0000418 # FIXME: <fl> move set optimization to compiler!
419 if len(set)==1 and set[0][0] is LITERAL:
420 subpattern.append(set[0]) # optimization
421 elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
422 subpattern.append((NOT_LITERAL, set[1][1])) # optimization
423 else:
424 # FIXME: <fl> add charmap optimization
425 subpattern.append((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000426
Fredrik Lundh90a07912000-06-30 07:50:59 +0000427 elif this and this[0] in REPEAT_CHARS:
428 # repeat previous item
429 if this == "?":
430 min, max = 0, 1
431 elif this == "*":
432 min, max = 0, MAXREPEAT
433 elif this == "+":
434 min, max = 1, MAXREPEAT
435 elif this == "{":
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000436 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000437 min, max = 0, MAXREPEAT
438 lo = hi = ""
439 while source.next in DIGITS:
440 lo = lo + source.get()
441 if source.match(","):
442 while source.next in DIGITS:
443 hi = hi + source.get()
444 else:
445 hi = lo
446 if not source.match("}"):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000447 subpattern.append((LITERAL, ord(this)))
448 source.seek(here)
449 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000450 if lo:
451 min = int(lo)
452 if hi:
453 max = int(hi)
454 # FIXME: <fl> check that hi >= lo!
455 else:
456 raise error, "not supported"
457 # figure out which item to repeat
458 if subpattern:
459 item = subpattern[-1:]
460 else:
461 raise error, "nothing to repeat"
462 if source.match("?"):
463 subpattern[-1] = (MIN_REPEAT, (min, max, item))
464 else:
465 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000466
Fredrik Lundh90a07912000-06-30 07:50:59 +0000467 elif this == ".":
468 subpattern.append((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000469
Fredrik Lundh90a07912000-06-30 07:50:59 +0000470 elif this == "(":
471 group = 1
472 name = None
473 if source.match("?"):
474 group = 0
475 # options
476 if source.match("P"):
477 # python extensions
478 if source.match("<"):
479 # named group: skip forward to end of name
480 name = ""
481 while 1:
482 char = source.get()
483 if char is None:
484 raise error, "unterminated name"
485 if char == ">":
486 break
487 name = name + char
488 group = 1
489 if not isname(name):
490 raise error, "illegal character in group name"
491 elif source.match("="):
492 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000493 name = ""
494 while 1:
495 char = source.get()
496 if char is None:
497 raise error, "unterminated name"
498 if char == ")":
499 break
500 name = name + char
501 if not isname(name):
502 raise error, "illegal character in group name"
503 gid = state.groupdict.get(name)
504 if gid is None:
505 raise error, "unknown group name"
Fredrik Lundh72b82ba2000-07-03 21:31:48 +0000506 subpattern.append((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000507 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000508 else:
509 char = source.get()
510 if char is None:
511 raise error, "unexpected end of pattern"
512 raise error, "unknown specifier: ?P%s" % char
513 elif source.match(":"):
514 # non-capturing group
515 group = 2
516 elif source.match("#"):
517 # comment
518 while 1:
519 if source.next is None or source.next == ")":
520 break
521 source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000522 if not source.match(")"):
523 raise error, "unbalanced parenthesis"
524 continue
Fredrik Lundh6f013982000-07-03 18:44:21 +0000525 elif source.next in ("=", "!", "<"):
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000526 # lookahead assertions
527 char = source.get()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000528 dir = 1
529 if char == "<":
530 if source.next not in ("=", "!"):
531 raise error, "syntax error"
532 dir = -1 # lookbehind
533 char = source.get()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000534 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000535 if not source.match(")"):
536 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000537 if char == "=":
538 subpattern.append((ASSERT, (dir, p)))
539 else:
540 subpattern.append((ASSERT_NOT, (dir, p)))
541 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000542 else:
543 # flags
544 while FLAGS.has_key(source.next):
545 state.flags = state.flags | FLAGS[source.get()]
546 if group:
547 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000548 if group == 2:
549 # anonymous group
550 group = None
551 else:
552 group = state.getgroup(name)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000553 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000554 if not source.match(")"):
555 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000556 subpattern.append((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000557 else:
558 while 1:
559 char = source.get()
560 if char is None or char == ")":
561 break
562 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000563
Fredrik Lundh90a07912000-06-30 07:50:59 +0000564 elif this == "^":
565 subpattern.append((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000566
Fredrik Lundh90a07912000-06-30 07:50:59 +0000567 elif this == "$":
568 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000569
Fredrik Lundh90a07912000-06-30 07:50:59 +0000570 elif this and this[0] == "\\":
571 code = _escape(source, this, state)
572 subpattern.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000573
Fredrik Lundh90a07912000-06-30 07:50:59 +0000574 else:
575 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000576
577 return subpattern
578
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000579def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000580 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000581
582 source = Tokenizer(str)
583
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000584 if pattern is None:
585 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000586 pattern.flags = flags
587
588 p = _parse_sub(source, pattern, 0)
589
590 tail = source.get()
591 if tail == ")":
592 raise error, "unbalanced parenthesis"
593 elif tail:
594 raise error, "bogus characters at end of regular expression"
595
596 # p.dump()
597
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000598 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
599 # the VERBOSE flag was switched on inside the pattern. to be
600 # on the safe side, we'll parse the whole thing again...
601 return parse(str, p.pattern.flags)
602
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000603 return p
604
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000605def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000606 # parse 're' replacement string into list of literals and
607 # group references
608 s = Tokenizer(source)
609 p = []
610 a = p.append
611 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000612 this = s.get()
613 if this is None:
614 break # end of replacement string
615 if this and this[0] == "\\":
616 # group
617 if this == "\\g":
618 name = ""
619 if s.match("<"):
620 while 1:
621 char = s.get()
622 if char is None:
623 raise error, "unterminated group name"
624 if char == ">":
625 break
626 name = name + char
627 if not name:
628 raise error, "bad group name"
629 try:
630 index = int(name)
631 except ValueError:
632 if not isname(name):
633 raise error, "illegal character in group name"
634 try:
635 index = pattern.groupindex[name]
636 except KeyError:
637 raise IndexError, "unknown group name"
638 a((MARK, index))
639 elif len(this) > 1 and this[1] in DIGITS:
640 code = None
641 while 1:
642 group = _group(this, pattern.groups+1)
643 if group:
Fredrik Lundh19f977b2000-09-24 14:46:23 +0000644 if (s.next not in DIGITS or
Fredrik Lundh90a07912000-06-30 07:50:59 +0000645 not _group(this + s.next, pattern.groups+1)):
646 code = MARK, int(group)
647 break
648 elif s.next in OCTDIGITS:
649 this = this + s.get()
650 else:
651 break
652 if not code:
653 this = this[1:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000654 code = LITERAL, int(this[-6:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000655 a(code)
656 else:
657 try:
658 a(ESCAPES[this])
659 except KeyError:
660 for c in this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000661 a((LITERAL, ord(c)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000662 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000663 a((LITERAL, ord(this)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000664 return p
665
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000666def expand_template(template, match):
667 # FIXME: <fl> this is sooooo slow. drop in the slicelist
668 # code instead
669 p = []
670 a = p.append
Fredrik Lundh0640e112000-06-30 13:55:15 +0000671 sep = match.string[:0]
672 if type(sep) is type(""):
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000673 char = chr
Fredrik Lundh0640e112000-06-30 13:55:15 +0000674 else:
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000675 char = unichr
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000676 for c, s in template:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000677 if c is LITERAL:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000678 a(char(s))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000679 elif c is MARK:
680 s = match.group(s)
681 if s is None:
682 raise error, "empty group"
683 a(s)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000684 return string.join(p, sep)