blob: 7c36d4f2dcb2bb673d34d333c1b03407c8954efb [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
15SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000016REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000017
Tim Peters17289422000-09-02 07:44:32 +000018DIGITS = tuple("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000019
Fredrik Lundh75f2d672000-06-29 11:34:28 +000020OCTDIGITS = tuple("01234567")
21HEXDIGITS = tuple("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000022
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000023WHITESPACE = tuple(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000024
Guido van Rossum7627c0d2000-03-31 14:58:54 +000025ESCAPES = {
Fredrik Lundh0640e112000-06-30 13:55:15 +000026 r"\a": (LITERAL, 7),
27 r"\b": (LITERAL, 8),
28 r"\f": (LITERAL, 12),
29 r"\n": (LITERAL, 10),
30 r"\r": (LITERAL, 13),
31 r"\t": (LITERAL, 9),
32 r"\v": (LITERAL, 11),
33 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000034}
35
36CATEGORIES = {
Fredrik Lundh01016fe2000-06-30 00:27:46 +000037 r"\A": (AT, AT_BEGINNING), # start of string
38 r"\b": (AT, AT_BOUNDARY),
39 r"\B": (AT, AT_NON_BOUNDARY),
40 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
41 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
42 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
43 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
44 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
45 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
46 r"\Z": (AT, AT_END), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000047}
48
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000049FLAGS = {
Fredrik Lundh436c3d52000-06-29 08:58:44 +000050 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000051 "i": SRE_FLAG_IGNORECASE,
52 "L": SRE_FLAG_LOCALE,
53 "m": SRE_FLAG_MULTILINE,
54 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000055 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d52000-06-29 08:58:44 +000056 # extensions
57 "t": SRE_FLAG_TEMPLATE,
58 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000059}
60
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000061class Pattern:
62 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000063 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000064 self.flags = 0
65 self.groups = 1
66 self.groupdict = {}
Guido van Rossum7627c0d2000-03-31 14:58:54 +000067 def getgroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000068 gid = self.groups
69 self.groups = gid + 1
70 if name:
71 self.groupdict[name] = gid
72 return gid
Guido van Rossum7627c0d2000-03-31 14:58:54 +000073
74class SubPattern:
75 # a subpattern, in intermediate form
76 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000077 self.pattern = pattern
78 if not data:
79 data = []
80 self.data = data
81 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000082 def dump(self, level=0):
83 nl = 1
84 for op, av in self.data:
85 print level*" " + op,; nl = 0
86 if op == "in":
87 # member sublanguage
88 print; nl = 1
89 for op, a in av:
90 print (level+1)*" " + op, a
91 elif op == "branch":
92 print; nl = 1
93 i = 0
94 for a in av[1]:
95 if i > 0:
96 print level*" " + "or"
97 a.dump(level+1); nl = 1
98 i = i + 1
99 elif type(av) in (type(()), type([])):
100 for a in av:
101 if isinstance(a, SubPattern):
102 if not nl: print
103 a.dump(level+1); nl = 1
104 else:
105 print a, ; nl = 0
106 else:
107 print av, ; nl = 0
108 if not nl: print
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000109 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000110 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000111 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000112 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000113 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000114 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000115 def __getitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000116 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000117 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000118 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000119 def __getslice__(self, start, stop):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000120 return SubPattern(self.pattern, self.data[start:stop])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000121 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000122 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000123 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000124 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000125 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000126 # determine the width (min, max) for this subpattern
127 if self.width:
128 return self.width
129 lo = hi = 0L
130 for op, av in self.data:
131 if op is BRANCH:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000132 i = sys.maxint
133 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000134 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000135 l, h = av.getwidth()
136 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000137 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000138 lo = lo + i
139 hi = hi + j
140 elif op is CALL:
141 i, j = av.getwidth()
142 lo = lo + i
143 hi = hi + j
144 elif op is SUBPATTERN:
145 i, j = av[1].getwidth()
146 lo = lo + i
147 hi = hi + j
148 elif op in (MIN_REPEAT, MAX_REPEAT):
149 i, j = av[2].getwidth()
150 lo = lo + long(i) * av[0]
151 hi = hi + long(j) * av[1]
152 elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY):
153 lo = lo + 1
154 hi = hi + 1
155 elif op == SUCCESS:
156 break
157 self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint))
158 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000159
160class Tokenizer:
161 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000162 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000163 self.index = 0
164 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000165 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000166 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000167 self.next = None
168 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000169 char = self.string[self.index]
170 if char[0] == "\\":
171 try:
172 c = self.string[self.index + 1]
173 except IndexError:
174 raise error, "bogus escape"
175 char = char + c
176 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000177 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000178 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000179 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000180 if skip:
181 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000182 return 1
183 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000184 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000185 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000186 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000187 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000188 def tell(self):
189 return self.index, self.next
190 def seek(self, index):
191 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000192
Fredrik Lundh4781b072000-06-29 12:38:45 +0000193def isident(char):
194 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
195
196def isdigit(char):
197 return "0" <= char <= "9"
198
199def isname(name):
200 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000201 if not isident(name[0]):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000202 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000203 for char in name:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000204 if not isident(char) and not isdigit(char):
205 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000206 return 1
207
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000208def _group(escape, groups):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000209 # check if the escape string represents a valid group
210 try:
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000211 gid = int(escape[1:])
212 if gid and gid < groups:
213 return gid
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000214 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000215 pass
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000216 return None # not a valid group
217
218def _class_escape(source, escape):
219 # handle escape code inside character class
220 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000221 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000222 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000223 code = CATEGORIES.get(escape)
224 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000225 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000226 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000227 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000228 # hexadecimal escape (exactly two digits)
229 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000230 escape = escape + source.get()
231 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000232 if len(escape) != 2:
233 raise error, "bogus escape: %s" % repr("\\" + escape)
234 return LITERAL, int(escape, 16) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000235 elif str(escape[1:2]) in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000236 # octal escape (up to three digits)
237 while source.next in OCTDIGITS and len(escape) < 5:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000238 escape = escape + source.get()
239 escape = escape[1:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000240 return LITERAL, int(escape, 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000241 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000242 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000243 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000244 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000245 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000246
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000247def _escape(source, escape, state):
248 # handle escape code in expression
249 code = CATEGORIES.get(escape)
250 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000251 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000252 code = ESCAPES.get(escape)
253 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000254 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000255 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000256 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000257 # hexadecimal escape
258 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000259 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000260 if len(escape) != 4:
261 raise ValueError
262 return LITERAL, int(escape[2:], 16) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000263 elif escape[1:2] == "0":
264 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000265 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000266 escape = escape + source.get()
267 return LITERAL, int(escape[1:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000268 elif escape[1:2] in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000269 # octal escape *or* decimal group reference (sigh)
270 here = source.tell()
271 if source.next in DIGITS:
272 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000273 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
274 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000275 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000276 escape = escape + source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000277 return LITERAL, int(escape[1:], 8) & 0xff
278 # got at least one decimal digit; this is a group reference
279 group = _group(escape, state.groups)
280 if group:
281 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000282 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000283 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000284 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000285 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000286 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000287 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000288
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000289def _parse_sub(source, state, nested=1):
290 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000291
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000292 items = []
293 while 1:
294 items.append(_parse(source, state))
295 if source.match("|"):
296 continue
297 if not nested:
298 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000299 if not source.next or source.match(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000300 break
301 else:
302 raise error, "pattern not properly closed"
303
304 if len(items) == 1:
305 return items[0]
306
307 subpattern = SubPattern(state)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000308
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000309 # check if all items share a common prefix
310 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000311 prefix = None
312 for item in items:
313 if not item:
314 break
315 if prefix is None:
316 prefix = item[0]
317 elif item[0] != prefix:
318 break
319 else:
320 # all subitems start with a common "prefix".
321 # move it out of the branch
322 for item in items:
323 del item[0]
324 subpattern.append(prefix)
325 continue # check next one
326 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000327
328 # check if the branch can be replaced by a character set
329 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000330 if len(item) != 1 or item[0][0] != LITERAL:
331 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000332 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000333 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000334 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000335 set = []
336 for item in items:
337 set.append(item[0])
338 subpattern.append((IN, set))
339 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000340
341 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000342 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000343
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000344def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000345 # parse a simple pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000346
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000347 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000348
349 while 1:
350
Fredrik Lundh90a07912000-06-30 07:50:59 +0000351 if source.next in ("|", ")"):
352 break # end of subpattern
353 this = source.get()
354 if this is None:
355 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000356
Fredrik Lundh90a07912000-06-30 07:50:59 +0000357 if state.flags & SRE_FLAG_VERBOSE:
358 # skip whitespace and comments
359 if this in WHITESPACE:
360 continue
361 if this == "#":
362 while 1:
363 this = source.get()
364 if this in (None, "\n"):
365 break
366 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000367
Fredrik Lundh90a07912000-06-30 07:50:59 +0000368 if this and this[0] not in SPECIAL_CHARS:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000369 subpattern.append((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000370
Fredrik Lundh90a07912000-06-30 07:50:59 +0000371 elif this == "[":
372 # character set
373 set = []
374## if source.match(":"):
375## pass # handle character classes
376 if source.match("^"):
377 set.append((NEGATE, None))
378 # check remaining characters
379 start = set[:]
380 while 1:
381 this = source.get()
382 if this == "]" and set != start:
383 break
384 elif this and this[0] == "\\":
385 code1 = _class_escape(source, this)
386 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000387 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000388 else:
389 raise error, "unexpected end of regular expression"
390 if source.match("-"):
391 # potential range
392 this = source.get()
393 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000394 if code1[0] is IN:
395 code1 = code1[1][0]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000396 set.append(code1)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000397 set.append((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000398 break
399 else:
400 if this[0] == "\\":
401 code2 = _class_escape(source, this)
402 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000403 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000404 if code1[0] != LITERAL or code2[0] != LITERAL:
405 raise error, "illegal range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000406 lo = code1[1]
407 hi = code2[1]
408 if hi < lo:
409 raise error, "illegal range"
410 set.append((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000411 else:
412 if code1[0] is IN:
413 code1 = code1[1][0]
414 set.append(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000415
Fredrik Lundh90a07912000-06-30 07:50:59 +0000416 # FIXME: <fl> move set optimization to compiler!
417 if len(set)==1 and set[0][0] is LITERAL:
418 subpattern.append(set[0]) # optimization
419 elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
420 subpattern.append((NOT_LITERAL, set[1][1])) # optimization
421 else:
422 # FIXME: <fl> add charmap optimization
423 subpattern.append((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000424
Fredrik Lundh90a07912000-06-30 07:50:59 +0000425 elif this and this[0] in REPEAT_CHARS:
426 # repeat previous item
427 if this == "?":
428 min, max = 0, 1
429 elif this == "*":
430 min, max = 0, MAXREPEAT
431 elif this == "+":
432 min, max = 1, MAXREPEAT
433 elif this == "{":
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000434 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000435 min, max = 0, MAXREPEAT
436 lo = hi = ""
437 while source.next in DIGITS:
438 lo = lo + source.get()
439 if source.match(","):
440 while source.next in DIGITS:
441 hi = hi + source.get()
442 else:
443 hi = lo
444 if not source.match("}"):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000445 subpattern.append((LITERAL, ord(this)))
446 source.seek(here)
447 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000448 if lo:
449 min = int(lo)
450 if hi:
451 max = int(hi)
452 # FIXME: <fl> check that hi >= lo!
453 else:
454 raise error, "not supported"
455 # figure out which item to repeat
456 if subpattern:
457 item = subpattern[-1:]
458 else:
459 raise error, "nothing to repeat"
460 if source.match("?"):
461 subpattern[-1] = (MIN_REPEAT, (min, max, item))
462 else:
463 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000464
Fredrik Lundh90a07912000-06-30 07:50:59 +0000465 elif this == ".":
466 subpattern.append((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000467
Fredrik Lundh90a07912000-06-30 07:50:59 +0000468 elif this == "(":
469 group = 1
470 name = None
471 if source.match("?"):
472 group = 0
473 # options
474 if source.match("P"):
475 # python extensions
476 if source.match("<"):
477 # named group: skip forward to end of name
478 name = ""
479 while 1:
480 char = source.get()
481 if char is None:
482 raise error, "unterminated name"
483 if char == ">":
484 break
485 name = name + char
486 group = 1
487 if not isname(name):
488 raise error, "illegal character in group name"
489 elif source.match("="):
490 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000491 name = ""
492 while 1:
493 char = source.get()
494 if char is None:
495 raise error, "unterminated name"
496 if char == ")":
497 break
498 name = name + char
499 if not isname(name):
500 raise error, "illegal character in group name"
501 gid = state.groupdict.get(name)
502 if gid is None:
503 raise error, "unknown group name"
Fredrik Lundh72b82ba2000-07-03 21:31:48 +0000504 subpattern.append((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000505 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000506 else:
507 char = source.get()
508 if char is None:
509 raise error, "unexpected end of pattern"
510 raise error, "unknown specifier: ?P%s" % char
511 elif source.match(":"):
512 # non-capturing group
513 group = 2
514 elif source.match("#"):
515 # comment
516 while 1:
517 if source.next is None or source.next == ")":
518 break
519 source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000520 if not source.match(")"):
521 raise error, "unbalanced parenthesis"
522 continue
Fredrik Lundh6f013982000-07-03 18:44:21 +0000523 elif source.next in ("=", "!", "<"):
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000524 # lookahead assertions
525 char = source.get()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000526 dir = 1
527 if char == "<":
528 if source.next not in ("=", "!"):
529 raise error, "syntax error"
530 dir = -1 # lookbehind
531 char = source.get()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000532 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000533 if not source.match(")"):
534 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000535 if char == "=":
536 subpattern.append((ASSERT, (dir, p)))
537 else:
538 subpattern.append((ASSERT_NOT, (dir, p)))
539 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000540 else:
541 # flags
542 while FLAGS.has_key(source.next):
543 state.flags = state.flags | FLAGS[source.get()]
544 if group:
545 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000546 if group == 2:
547 # anonymous group
548 group = None
549 else:
550 group = state.getgroup(name)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000551 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000552 if not source.match(")"):
553 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000554 subpattern.append((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000555 else:
556 while 1:
557 char = source.get()
558 if char is None or char == ")":
559 break
560 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000561
Fredrik Lundh90a07912000-06-30 07:50:59 +0000562 elif this == "^":
563 subpattern.append((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000564
Fredrik Lundh90a07912000-06-30 07:50:59 +0000565 elif this == "$":
566 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000567
Fredrik Lundh90a07912000-06-30 07:50:59 +0000568 elif this and this[0] == "\\":
569 code = _escape(source, this, state)
570 subpattern.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000571
Fredrik Lundh90a07912000-06-30 07:50:59 +0000572 else:
573 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000574
575 return subpattern
576
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000577def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000578 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000579
580 source = Tokenizer(str)
581
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000582 if pattern is None:
583 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000584 pattern.flags = flags
585
586 p = _parse_sub(source, pattern, 0)
587
588 tail = source.get()
589 if tail == ")":
590 raise error, "unbalanced parenthesis"
591 elif tail:
592 raise error, "bogus characters at end of regular expression"
593
594 # p.dump()
595
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000596 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
597 # the VERBOSE flag was switched on inside the pattern. to be
598 # on the safe side, we'll parse the whole thing again...
599 return parse(str, p.pattern.flags)
600
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000601 return p
602
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000603def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000604 # parse 're' replacement string into list of literals and
605 # group references
606 s = Tokenizer(source)
607 p = []
608 a = p.append
609 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000610 this = s.get()
611 if this is None:
612 break # end of replacement string
613 if this and this[0] == "\\":
614 # group
615 if this == "\\g":
616 name = ""
617 if s.match("<"):
618 while 1:
619 char = s.get()
620 if char is None:
621 raise error, "unterminated group name"
622 if char == ">":
623 break
624 name = name + char
625 if not name:
626 raise error, "bad group name"
627 try:
628 index = int(name)
629 except ValueError:
630 if not isname(name):
631 raise error, "illegal character in group name"
632 try:
633 index = pattern.groupindex[name]
634 except KeyError:
635 raise IndexError, "unknown group name"
636 a((MARK, index))
637 elif len(this) > 1 and this[1] in DIGITS:
638 code = None
639 while 1:
640 group = _group(this, pattern.groups+1)
641 if group:
Fredrik Lundh19f977b2000-09-24 14:46:23 +0000642 if (s.next not in DIGITS or
Fredrik Lundh90a07912000-06-30 07:50:59 +0000643 not _group(this + s.next, pattern.groups+1)):
644 code = MARK, int(group)
645 break
646 elif s.next in OCTDIGITS:
647 this = this + s.get()
648 else:
649 break
650 if not code:
651 this = this[1:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000652 code = LITERAL, int(this[-6:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000653 a(code)
654 else:
655 try:
656 a(ESCAPES[this])
657 except KeyError:
658 for c in this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000659 a((LITERAL, ord(c)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000660 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000661 a((LITERAL, ord(this)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000662 return p
663
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000664def expand_template(template, match):
665 # FIXME: <fl> this is sooooo slow. drop in the slicelist
666 # code instead
667 p = []
668 a = p.append
Fredrik Lundh0640e112000-06-30 13:55:15 +0000669 sep = match.string[:0]
670 if type(sep) is type(""):
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000671 char = chr
Fredrik Lundh0640e112000-06-30 13:55:15 +0000672 else:
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000673 char = unichr
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000674 for c, s in template:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000675 if c is LITERAL:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000676 a(char(s))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000677 elif c is MARK:
678 s = match.group(s)
679 if s is None:
680 raise error, "empty group"
681 a(s)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000682 return string.join(p, sep)