blob: a50191ec9b093ea163124dd6610c495d050f6758 [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 = ".\\[{()*+?^$|"
18REPEAT_CHARS = "*+?{"
19
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000020DIGITS = tuple("012345689")
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()
262 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000263 if len(escape) != 2:
264 raise error, "bogus escape: %s" % repr("\\" + escape)
265 return LITERAL, int(escape, 16) & 0xff
266 elif escape[1:2] == "0":
267 # octal escape
268 while source.next in OCTDIGITS and len(escape) < 5:
269 escape = escape + source.get()
270 return LITERAL, int(escape[1:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000271 elif escape[1:2] in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000272 # octal escape *or* decimal group reference (sigh)
273 here = source.tell()
274 if source.next in DIGITS:
275 escape = escape + source.get()
276 if escape[2] in OCTDIGITS and source.next in OCTDIGITS:
277 # 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
284 raise error, "bogus escape: %s" % repr(escape)
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 == "]":
396 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
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000596 return p
597
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000598def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000599 # parse 're' replacement string into list of literals and
600 # group references
601 s = Tokenizer(source)
602 p = []
603 a = p.append
604 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000605 this = s.get()
606 if this is None:
607 break # end of replacement string
608 if this and this[0] == "\\":
609 # group
610 if this == "\\g":
611 name = ""
612 if s.match("<"):
613 while 1:
614 char = s.get()
615 if char is None:
616 raise error, "unterminated group name"
617 if char == ">":
618 break
619 name = name + char
620 if not name:
621 raise error, "bad group name"
622 try:
623 index = int(name)
624 except ValueError:
625 if not isname(name):
626 raise error, "illegal character in group name"
627 try:
628 index = pattern.groupindex[name]
629 except KeyError:
630 raise IndexError, "unknown group name"
631 a((MARK, index))
632 elif len(this) > 1 and this[1] in DIGITS:
633 code = None
634 while 1:
635 group = _group(this, pattern.groups+1)
636 if group:
637 if (not s.next or
638 not _group(this + s.next, pattern.groups+1)):
639 code = MARK, int(group)
640 break
641 elif s.next in OCTDIGITS:
642 this = this + s.get()
643 else:
644 break
645 if not code:
646 this = this[1:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000647 code = LITERAL, int(this[-6:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000648 a(code)
649 else:
650 try:
651 a(ESCAPES[this])
652 except KeyError:
653 for c in this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000654 a((LITERAL, ord(c)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000655 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000656 a((LITERAL, ord(this)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000657 return p
658
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000659def expand_template(template, match):
660 # FIXME: <fl> this is sooooo slow. drop in the slicelist
661 # code instead
662 p = []
663 a = p.append
Fredrik Lundh0640e112000-06-30 13:55:15 +0000664 sep = match.string[:0]
665 if type(sep) is type(""):
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000666 char = chr
Fredrik Lundh0640e112000-06-30 13:55:15 +0000667 else:
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000668 char = unichr
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000669 for c, s in template:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000670 if c is LITERAL:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000671 a(char(s))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000672 elif c is MARK:
673 s = match.group(s)
674 if s is None:
675 raise error, "empty group"
676 a(s)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000677 return string.join(p, sep)