blob: 5334e0661aa676667eb34406b222f46ca308e4bc [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 Lundh436c3d582000-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 Lundh436c3d582000-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
Fredrik Lundhebc37b22000-10-28 19:30:41 +000065 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000066 self.groups = 1
67 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000068 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000069 gid = self.groups
70 self.groups = gid + 1
71 if name:
72 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000073 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000074 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000075 def closegroup(self, gid):
76 self.open.remove(gid)
77 def checkgroup(self, gid):
78 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000079
80class SubPattern:
81 # a subpattern, in intermediate form
82 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000083 self.pattern = pattern
84 if not data:
85 data = []
86 self.data = data
87 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000088 def dump(self, level=0):
89 nl = 1
90 for op, av in self.data:
91 print level*" " + op,; nl = 0
92 if op == "in":
93 # member sublanguage
94 print; nl = 1
95 for op, a in av:
96 print (level+1)*" " + op, a
97 elif op == "branch":
98 print; nl = 1
99 i = 0
100 for a in av[1]:
101 if i > 0:
102 print level*" " + "or"
103 a.dump(level+1); nl = 1
104 i = i + 1
105 elif type(av) in (type(()), type([])):
106 for a in av:
107 if isinstance(a, SubPattern):
108 if not nl: print
109 a.dump(level+1); nl = 1
110 else:
111 print a, ; nl = 0
112 else:
113 print av, ; nl = 0
114 if not nl: print
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000115 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000116 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000117 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000118 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000119 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000120 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000121 def __getitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000122 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000123 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000124 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000125 def __getslice__(self, start, stop):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000126 return SubPattern(self.pattern, self.data[start:stop])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000127 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000128 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000129 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000130 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000131 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000132 # determine the width (min, max) for this subpattern
133 if self.width:
134 return self.width
135 lo = hi = 0L
136 for op, av in self.data:
137 if op is BRANCH:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000138 i = sys.maxint
139 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000140 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000141 l, h = av.getwidth()
142 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000143 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000144 lo = lo + i
145 hi = hi + j
146 elif op is CALL:
147 i, j = av.getwidth()
148 lo = lo + i
149 hi = hi + j
150 elif op is SUBPATTERN:
151 i, j = av[1].getwidth()
152 lo = lo + i
153 hi = hi + j
154 elif op in (MIN_REPEAT, MAX_REPEAT):
155 i, j = av[2].getwidth()
156 lo = lo + long(i) * av[0]
157 hi = hi + long(j) * av[1]
158 elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY):
159 lo = lo + 1
160 hi = hi + 1
161 elif op == SUCCESS:
162 break
163 self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint))
164 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000165
166class Tokenizer:
167 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000168 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000169 self.index = 0
170 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000171 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000172 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000173 self.next = None
174 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000175 char = self.string[self.index]
176 if char[0] == "\\":
177 try:
178 c = self.string[self.index + 1]
179 except IndexError:
180 raise error, "bogus escape"
181 char = char + c
182 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000183 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000184 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000185 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000186 if skip:
187 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000188 return 1
189 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000190 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000191 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000192 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000193 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000194 def tell(self):
195 return self.index, self.next
196 def seek(self, index):
197 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000198
Fredrik Lundh4781b072000-06-29 12:38:45 +0000199def isident(char):
200 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
201
202def isdigit(char):
203 return "0" <= char <= "9"
204
205def isname(name):
206 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000207 if not isident(name[0]):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000208 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000209 for char in name:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000210 if not isident(char) and not isdigit(char):
211 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000212 return 1
213
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000214def _group(escape, groups):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000215 # check if the escape string represents a valid group
216 try:
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000217 gid = int(escape[1:])
218 if gid and gid < groups:
219 return gid
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000220 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000221 pass
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000222 return None # not a valid group
223
224def _class_escape(source, escape):
225 # handle escape code inside character class
226 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000227 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000228 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000229 code = CATEGORIES.get(escape)
230 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000231 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000232 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000233 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000234 # hexadecimal escape (exactly two digits)
235 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000236 escape = escape + source.get()
237 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000238 if len(escape) != 2:
239 raise error, "bogus escape: %s" % repr("\\" + escape)
240 return LITERAL, int(escape, 16) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000241 elif str(escape[1:2]) in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000242 # octal escape (up to three digits)
243 while source.next in OCTDIGITS and len(escape) < 5:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000244 escape = escape + source.get()
245 escape = escape[1:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000246 return LITERAL, int(escape, 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000247 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000248 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000249 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000250 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000251 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000252
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000253def _escape(source, escape, state):
254 # handle escape code in expression
255 code = CATEGORIES.get(escape)
256 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000257 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000258 code = ESCAPES.get(escape)
259 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000260 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000261 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000262 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000263 # hexadecimal escape
264 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000265 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000266 if len(escape) != 4:
267 raise ValueError
268 return LITERAL, int(escape[2:], 16) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000269 elif escape[1:2] == "0":
270 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000271 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000272 escape = escape + source.get()
273 return LITERAL, int(escape[1:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000274 elif escape[1:2] in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000275 # octal escape *or* decimal group reference (sigh)
276 here = source.tell()
277 if source.next in DIGITS:
278 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000279 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
280 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000281 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000282 escape = escape + source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000283 return LITERAL, int(escape[1:], 8) & 0xff
284 # got at least one decimal digit; this is a group reference
285 group = _group(escape, state.groups)
286 if group:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000287 if not state.checkgroup(group):
288 raise error, "cannot refer to open group"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000289 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000290 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000291 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000292 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000293 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000294 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000295 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000296
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000297def _parse_sub(source, state, nested=1):
298 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000299
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000300 items = []
301 while 1:
302 items.append(_parse(source, state))
303 if source.match("|"):
304 continue
305 if not nested:
306 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000307 if not source.next or source.match(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000308 break
309 else:
310 raise error, "pattern not properly closed"
311
312 if len(items) == 1:
313 return items[0]
314
315 subpattern = SubPattern(state)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000316
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000317 # check if all items share a common prefix
318 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000319 prefix = None
320 for item in items:
321 if not item:
322 break
323 if prefix is None:
324 prefix = item[0]
325 elif item[0] != prefix:
326 break
327 else:
328 # all subitems start with a common "prefix".
329 # move it out of the branch
330 for item in items:
331 del item[0]
332 subpattern.append(prefix)
333 continue # check next one
334 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000335
336 # check if the branch can be replaced by a character set
337 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000338 if len(item) != 1 or item[0][0] != LITERAL:
339 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000340 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000341 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000342 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000343 set = []
344 for item in items:
345 set.append(item[0])
346 subpattern.append((IN, set))
347 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000348
349 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000350 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000351
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000352def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000353 # parse a simple pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000354
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000355 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000356
357 while 1:
358
Fredrik Lundh90a07912000-06-30 07:50:59 +0000359 if source.next in ("|", ")"):
360 break # end of subpattern
361 this = source.get()
362 if this is None:
363 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000364
Fredrik Lundh90a07912000-06-30 07:50:59 +0000365 if state.flags & SRE_FLAG_VERBOSE:
366 # skip whitespace and comments
367 if this in WHITESPACE:
368 continue
369 if this == "#":
370 while 1:
371 this = source.get()
372 if this in (None, "\n"):
373 break
374 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000375
Fredrik Lundh90a07912000-06-30 07:50:59 +0000376 if this and this[0] not in SPECIAL_CHARS:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000377 subpattern.append((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000378
Fredrik Lundh90a07912000-06-30 07:50:59 +0000379 elif this == "[":
380 # character set
381 set = []
382## if source.match(":"):
383## pass # handle character classes
384 if source.match("^"):
385 set.append((NEGATE, None))
386 # check remaining characters
387 start = set[:]
388 while 1:
389 this = source.get()
390 if this == "]" and set != start:
391 break
392 elif this and this[0] == "\\":
393 code1 = _class_escape(source, this)
394 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000395 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000396 else:
397 raise error, "unexpected end of regular expression"
398 if source.match("-"):
399 # potential range
400 this = source.get()
401 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000402 if code1[0] is IN:
403 code1 = code1[1][0]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000404 set.append(code1)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000405 set.append((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000406 break
407 else:
408 if this[0] == "\\":
409 code2 = _class_escape(source, this)
410 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000411 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000412 if code1[0] != LITERAL or code2[0] != LITERAL:
413 raise error, "illegal range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000414 lo = code1[1]
415 hi = code2[1]
416 if hi < lo:
417 raise error, "illegal range"
418 set.append((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000419 else:
420 if code1[0] is IN:
421 code1 = code1[1][0]
422 set.append(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000423
Fredrik Lundh90a07912000-06-30 07:50:59 +0000424 # FIXME: <fl> move set optimization to compiler!
425 if len(set)==1 and set[0][0] is LITERAL:
426 subpattern.append(set[0]) # optimization
427 elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
428 subpattern.append((NOT_LITERAL, set[1][1])) # optimization
429 else:
430 # FIXME: <fl> add charmap optimization
431 subpattern.append((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000432
Fredrik Lundh90a07912000-06-30 07:50:59 +0000433 elif this and this[0] in REPEAT_CHARS:
434 # repeat previous item
435 if this == "?":
436 min, max = 0, 1
437 elif this == "*":
438 min, max = 0, MAXREPEAT
439 elif this == "+":
440 min, max = 1, MAXREPEAT
441 elif this == "{":
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000442 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000443 min, max = 0, MAXREPEAT
444 lo = hi = ""
445 while source.next in DIGITS:
446 lo = lo + source.get()
447 if source.match(","):
448 while source.next in DIGITS:
449 hi = hi + source.get()
450 else:
451 hi = lo
452 if not source.match("}"):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000453 subpattern.append((LITERAL, ord(this)))
454 source.seek(here)
455 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000456 if lo:
457 min = int(lo)
458 if hi:
459 max = int(hi)
460 # FIXME: <fl> check that hi >= lo!
461 else:
462 raise error, "not supported"
463 # figure out which item to repeat
464 if subpattern:
465 item = subpattern[-1:]
466 else:
467 raise error, "nothing to repeat"
468 if source.match("?"):
469 subpattern[-1] = (MIN_REPEAT, (min, max, item))
470 else:
471 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000472
Fredrik Lundh90a07912000-06-30 07:50:59 +0000473 elif this == ".":
474 subpattern.append((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000475
Fredrik Lundh90a07912000-06-30 07:50:59 +0000476 elif this == "(":
477 group = 1
478 name = None
479 if source.match("?"):
480 group = 0
481 # options
482 if source.match("P"):
483 # python extensions
484 if source.match("<"):
485 # named group: skip forward to end of name
486 name = ""
487 while 1:
488 char = source.get()
489 if char is None:
490 raise error, "unterminated name"
491 if char == ">":
492 break
493 name = name + char
494 group = 1
495 if not isname(name):
496 raise error, "illegal character in group name"
497 elif source.match("="):
498 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000499 name = ""
500 while 1:
501 char = source.get()
502 if char is None:
503 raise error, "unterminated name"
504 if char == ")":
505 break
506 name = name + char
507 if not isname(name):
508 raise error, "illegal character in group name"
509 gid = state.groupdict.get(name)
510 if gid is None:
511 raise error, "unknown group name"
Fredrik Lundh72b82ba2000-07-03 21:31:48 +0000512 subpattern.append((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000513 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000514 else:
515 char = source.get()
516 if char is None:
517 raise error, "unexpected end of pattern"
518 raise error, "unknown specifier: ?P%s" % char
519 elif source.match(":"):
520 # non-capturing group
521 group = 2
522 elif source.match("#"):
523 # comment
524 while 1:
525 if source.next is None or source.next == ")":
526 break
527 source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000528 if not source.match(")"):
529 raise error, "unbalanced parenthesis"
530 continue
Fredrik Lundh6f013982000-07-03 18:44:21 +0000531 elif source.next in ("=", "!", "<"):
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000532 # lookahead assertions
533 char = source.get()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000534 dir = 1
535 if char == "<":
536 if source.next not in ("=", "!"):
537 raise error, "syntax error"
538 dir = -1 # lookbehind
539 char = source.get()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000540 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000541 if not source.match(")"):
542 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000543 if char == "=":
544 subpattern.append((ASSERT, (dir, p)))
545 else:
546 subpattern.append((ASSERT_NOT, (dir, p)))
547 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000548 else:
549 # flags
550 while FLAGS.has_key(source.next):
551 state.flags = state.flags | FLAGS[source.get()]
552 if group:
553 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000554 if group == 2:
555 # anonymous group
556 group = None
557 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000558 group = state.opengroup(name)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000559 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000560 if not source.match(")"):
561 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000562 if group is not None:
563 state.closegroup(group)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000564 subpattern.append((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000565 else:
566 while 1:
567 char = source.get()
568 if char is None or char == ")":
569 break
570 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000571
Fredrik Lundh90a07912000-06-30 07:50:59 +0000572 elif this == "^":
573 subpattern.append((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000574
Fredrik Lundh90a07912000-06-30 07:50:59 +0000575 elif this == "$":
576 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000577
Fredrik Lundh90a07912000-06-30 07:50:59 +0000578 elif this and this[0] == "\\":
579 code = _escape(source, this, state)
580 subpattern.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000581
Fredrik Lundh90a07912000-06-30 07:50:59 +0000582 else:
583 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000584
585 return subpattern
586
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000587def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000588 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000589
590 source = Tokenizer(str)
591
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000592 if pattern is None:
593 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000594 pattern.flags = flags
595
596 p = _parse_sub(source, pattern, 0)
597
598 tail = source.get()
599 if tail == ")":
600 raise error, "unbalanced parenthesis"
601 elif tail:
602 raise error, "bogus characters at end of regular expression"
603
604 # p.dump()
605
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000606 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
607 # the VERBOSE flag was switched on inside the pattern. to be
608 # on the safe side, we'll parse the whole thing again...
609 return parse(str, p.pattern.flags)
610
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000611 return p
612
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000613def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000614 # parse 're' replacement string into list of literals and
615 # group references
616 s = Tokenizer(source)
617 p = []
618 a = p.append
619 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000620 this = s.get()
621 if this is None:
622 break # end of replacement string
623 if this and this[0] == "\\":
624 # group
625 if this == "\\g":
626 name = ""
627 if s.match("<"):
628 while 1:
629 char = s.get()
630 if char is None:
631 raise error, "unterminated group name"
632 if char == ">":
633 break
634 name = name + char
635 if not name:
636 raise error, "bad group name"
637 try:
638 index = int(name)
639 except ValueError:
640 if not isname(name):
641 raise error, "illegal character in group name"
642 try:
643 index = pattern.groupindex[name]
644 except KeyError:
645 raise IndexError, "unknown group name"
646 a((MARK, index))
647 elif len(this) > 1 and this[1] in DIGITS:
648 code = None
649 while 1:
650 group = _group(this, pattern.groups+1)
651 if group:
Fredrik Lundh19f977b2000-09-24 14:46:23 +0000652 if (s.next not in DIGITS or
Fredrik Lundh90a07912000-06-30 07:50:59 +0000653 not _group(this + s.next, pattern.groups+1)):
654 code = MARK, int(group)
655 break
656 elif s.next in OCTDIGITS:
657 this = this + s.get()
658 else:
659 break
660 if not code:
661 this = this[1:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000662 code = LITERAL, int(this[-6:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000663 a(code)
664 else:
665 try:
666 a(ESCAPES[this])
667 except KeyError:
668 for c in this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000669 a((LITERAL, ord(c)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000670 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000671 a((LITERAL, ord(this)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000672 return p
673
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000674def expand_template(template, match):
675 # FIXME: <fl> this is sooooo slow. drop in the slicelist
676 # code instead
677 p = []
678 a = p.append
Fredrik Lundh0640e112000-06-30 13:55:15 +0000679 sep = match.string[:0]
680 if type(sep) is type(""):
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000681 char = chr
Fredrik Lundh0640e112000-06-30 13:55:15 +0000682 else:
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000683 char = unichr
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000684 for c, s in template:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000685 if c is LITERAL:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000686 a(char(s))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000687 elif c is MARK:
688 s = match.group(s)
689 if s is None:
690 raise error, "empty group"
691 a(s)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000692 return string.join(p, sep)