blob: 635605de676146b18bae9d8e488793ff9216bd8d [file] [log] [blame]
Guido van Rossum7627c0d2000-03-31 14:58:54 +00001#
2# Secret Labs' Regular Expression Engine
Guido van Rossum7627c0d2000-03-31 14:58:54 +00003#
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +00004# convert re-style regular expression to sre pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +00005#
Fredrik Lundh770617b2001-01-14 15:06:11 +00006# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
Guido van Rossum7627c0d2000-03-31 14:58:54 +00007#
Fredrik Lundh29c4ba92000-08-01 18:20:07 +00008# See the sre.py file for information on usage and redistribution.
Guido van Rossum7627c0d2000-03-31 14:58:54 +00009#
10
Fredrik Lundh470ea5a2001-01-14 21:00:44 +000011# XXX: show string offset and offending character for all errors
12
Eric S. Raymondfc170b12001-02-09 11:51:27 +000013import sys
Guido van Rossum7627c0d2000-03-31 14:58:54 +000014
15from sre_constants import *
16
17SPECIAL_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 Lundh770617b2001-01-14 15:06:11 +000039 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000040 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)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000048 r"\Z": (AT, AT_END_STRING), # 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
Fredrik Lundhebc37b22000-10-28 19:30:41 +000067 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000068 self.groups = 1
69 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000070 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000071 gid = self.groups
72 self.groups = gid + 1
73 if name:
74 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000075 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000076 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000077 def closegroup(self, gid):
78 self.open.remove(gid)
79 def checkgroup(self, gid):
80 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000081
82class SubPattern:
83 # a subpattern, in intermediate form
84 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000085 self.pattern = pattern
86 if not data:
87 data = []
88 self.data = data
89 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000090 def dump(self, level=0):
91 nl = 1
92 for op, av in self.data:
93 print level*" " + op,; nl = 0
94 if op == "in":
95 # member sublanguage
96 print; nl = 1
97 for op, a in av:
98 print (level+1)*" " + op, a
99 elif op == "branch":
100 print; nl = 1
101 i = 0
102 for a in av[1]:
103 if i > 0:
104 print level*" " + "or"
105 a.dump(level+1); nl = 1
106 i = i + 1
107 elif type(av) in (type(()), type([])):
108 for a in av:
109 if isinstance(a, SubPattern):
110 if not nl: print
111 a.dump(level+1); nl = 1
112 else:
113 print a, ; nl = 0
114 else:
115 print av, ; nl = 0
116 if not nl: print
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000117 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000118 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000119 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000120 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000121 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000122 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000123 def __getitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000124 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000125 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000126 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000127 def __getslice__(self, start, stop):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000128 return SubPattern(self.pattern, self.data[start:stop])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000129 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000130 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000131 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000132 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000133 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000134 # determine the width (min, max) for this subpattern
135 if self.width:
136 return self.width
137 lo = hi = 0L
138 for op, av in self.data:
139 if op is BRANCH:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000140 i = sys.maxint
141 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000142 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000143 l, h = av.getwidth()
144 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000145 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000146 lo = lo + i
147 hi = hi + j
148 elif op is CALL:
149 i, j = av.getwidth()
150 lo = lo + i
151 hi = hi + j
152 elif op is SUBPATTERN:
153 i, j = av[1].getwidth()
154 lo = lo + i
155 hi = hi + j
156 elif op in (MIN_REPEAT, MAX_REPEAT):
157 i, j = av[2].getwidth()
158 lo = lo + long(i) * av[0]
159 hi = hi + long(j) * av[1]
160 elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY):
161 lo = lo + 1
162 hi = hi + 1
163 elif op == SUCCESS:
164 break
165 self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint))
166 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000167
168class Tokenizer:
169 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000170 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000171 self.index = 0
172 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000173 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000174 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000175 self.next = None
176 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000177 char = self.string[self.index]
178 if char[0] == "\\":
179 try:
180 c = self.string[self.index + 1]
181 except IndexError:
182 raise error, "bogus escape"
183 char = char + c
184 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000185 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000186 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000187 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000188 if skip:
189 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000190 return 1
191 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000192 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000193 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000194 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000195 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000196 def tell(self):
197 return self.index, self.next
198 def seek(self, index):
199 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000200
Fredrik Lundh4781b072000-06-29 12:38:45 +0000201def isident(char):
202 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
203
204def isdigit(char):
205 return "0" <= char <= "9"
206
207def isname(name):
208 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000209 if not isident(name[0]):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000210 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000211 for char in name:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000212 if not isident(char) and not isdigit(char):
213 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000214 return 1
215
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000216def _group(escape, groups):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000217 # check if the escape string represents a valid group
218 try:
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000219 gid = int(escape[1:])
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000220 if gid and gid < groups:
221 return gid
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000222 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000223 pass
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000224 return None # not a valid group
225
226def _class_escape(source, escape):
227 # handle escape code inside character class
228 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000229 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000230 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000231 code = CATEGORIES.get(escape)
232 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000233 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000234 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000235 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000236 # hexadecimal escape (exactly two digits)
237 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000238 escape = escape + source.get()
239 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000240 if len(escape) != 2:
241 raise error, "bogus escape: %s" % repr("\\" + escape)
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000242 return LITERAL, int(escape, 16) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000243 elif str(escape[1:2]) in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000244 # octal escape (up to three digits)
245 while source.next in OCTDIGITS and len(escape) < 5:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000246 escape = escape + source.get()
247 escape = escape[1:]
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000248 return LITERAL, int(escape, 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000249 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000250 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000251 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000252 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000253 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000254
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000255def _escape(source, escape, state):
256 # handle escape code in expression
257 code = CATEGORIES.get(escape)
258 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000259 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000260 code = ESCAPES.get(escape)
261 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000262 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000263 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000264 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000265 # hexadecimal escape
266 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000267 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000268 if len(escape) != 4:
269 raise ValueError
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000270 return LITERAL, int(escape[2:], 16) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000271 elif escape[1:2] == "0":
272 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000273 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000274 escape = escape + source.get()
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000275 return LITERAL, int(escape[1:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000276 elif escape[1:2] in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000277 # octal escape *or* decimal group reference (sigh)
278 here = source.tell()
279 if source.next in DIGITS:
280 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000281 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
282 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000283 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000284 escape = escape + source.get()
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000285 return LITERAL, int(escape[1:], 8) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000286 # got at least one decimal digit; this is a group reference
287 group = _group(escape, state.groups)
288 if group:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000289 if not state.checkgroup(group):
290 raise error, "cannot refer to open group"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000291 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000292 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000293 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000294 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000295 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000296 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000297 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000298
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000299def _parse_sub(source, state, nested=1):
300 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000301
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000302 items = []
303 while 1:
304 items.append(_parse(source, state))
305 if source.match("|"):
306 continue
307 if not nested:
308 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000309 if not source.next or source.match(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000310 break
311 else:
312 raise error, "pattern not properly closed"
313
314 if len(items) == 1:
315 return items[0]
316
317 subpattern = SubPattern(state)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000318
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000319 # check if all items share a common prefix
320 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000321 prefix = None
322 for item in items:
323 if not item:
324 break
325 if prefix is None:
326 prefix = item[0]
327 elif item[0] != prefix:
328 break
329 else:
330 # all subitems start with a common "prefix".
331 # move it out of the branch
332 for item in items:
333 del item[0]
334 subpattern.append(prefix)
335 continue # check next one
336 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000337
338 # check if the branch can be replaced by a character set
339 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000340 if len(item) != 1 or item[0][0] != LITERAL:
341 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000342 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000343 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000344 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000345 set = []
346 for item in items:
347 set.append(item[0])
348 subpattern.append((IN, set))
349 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000350
351 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000352 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000353
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000354def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000355 # parse a simple pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000356
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000357 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000358
359 while 1:
360
Fredrik Lundh90a07912000-06-30 07:50:59 +0000361 if source.next in ("|", ")"):
362 break # end of subpattern
363 this = source.get()
364 if this is None:
365 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000366
Fredrik Lundh90a07912000-06-30 07:50:59 +0000367 if state.flags & SRE_FLAG_VERBOSE:
368 # skip whitespace and comments
369 if this in WHITESPACE:
370 continue
371 if this == "#":
372 while 1:
373 this = source.get()
374 if this in (None, "\n"):
375 break
376 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000377
Fredrik Lundh90a07912000-06-30 07:50:59 +0000378 if this and this[0] not in SPECIAL_CHARS:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000379 subpattern.append((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000380
Fredrik Lundh90a07912000-06-30 07:50:59 +0000381 elif this == "[":
382 # character set
383 set = []
384## if source.match(":"):
385## pass # handle character classes
386 if source.match("^"):
387 set.append((NEGATE, None))
388 # check remaining characters
389 start = set[:]
390 while 1:
391 this = source.get()
392 if this == "]" and set != start:
393 break
394 elif this and this[0] == "\\":
395 code1 = _class_escape(source, this)
396 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000397 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000398 else:
399 raise error, "unexpected end of regular expression"
400 if source.match("-"):
401 # potential range
402 this = source.get()
403 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000404 if code1[0] is IN:
405 code1 = code1[1][0]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000406 set.append(code1)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000407 set.append((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000408 break
409 else:
410 if this[0] == "\\":
411 code2 = _class_escape(source, this)
412 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000413 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000414 if code1[0] != LITERAL or code2[0] != LITERAL:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000415 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000416 lo = code1[1]
417 hi = code2[1]
418 if hi < lo:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000419 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000420 set.append((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000421 else:
422 if code1[0] is IN:
423 code1 = code1[1][0]
424 set.append(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000425
Fredrik Lundh770617b2001-01-14 15:06:11 +0000426 # XXX: <fl> should move set optimization to compiler!
Fredrik Lundh90a07912000-06-30 07:50:59 +0000427 if len(set)==1 and set[0][0] is LITERAL:
428 subpattern.append(set[0]) # optimization
429 elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
430 subpattern.append((NOT_LITERAL, set[1][1])) # optimization
431 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000432 # XXX: <fl> should add charmap optimization here
Fredrik Lundh90a07912000-06-30 07:50:59 +0000433 subpattern.append((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000434
Fredrik Lundh90a07912000-06-30 07:50:59 +0000435 elif this and this[0] in REPEAT_CHARS:
436 # repeat previous item
437 if this == "?":
438 min, max = 0, 1
439 elif this == "*":
440 min, max = 0, MAXREPEAT
441 elif this == "+":
442 min, max = 1, MAXREPEAT
443 elif this == "{":
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000444 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000445 min, max = 0, MAXREPEAT
446 lo = hi = ""
447 while source.next in DIGITS:
448 lo = lo + source.get()
449 if source.match(","):
450 while source.next in DIGITS:
451 hi = hi + source.get()
452 else:
453 hi = lo
454 if not source.match("}"):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000455 subpattern.append((LITERAL, ord(this)))
456 source.seek(here)
457 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000458 if lo:
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000459 min = int(lo)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000460 if hi:
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000461 max = int(hi)
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000462 if max < min:
463 raise error, "bad repeat interval"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000464 else:
465 raise error, "not supported"
466 # figure out which item to repeat
467 if subpattern:
468 item = subpattern[-1:]
469 else:
470 raise error, "nothing to repeat"
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000471 if item[0][0] in (MIN_REPEAT, MAX_REPEAT):
472 raise error, "multiple repeat"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000473 if source.match("?"):
474 subpattern[-1] = (MIN_REPEAT, (min, max, item))
475 else:
476 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000477
Fredrik Lundh90a07912000-06-30 07:50:59 +0000478 elif this == ".":
479 subpattern.append((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000480
Fredrik Lundh90a07912000-06-30 07:50:59 +0000481 elif this == "(":
482 group = 1
483 name = None
484 if source.match("?"):
485 group = 0
486 # options
487 if source.match("P"):
488 # python extensions
489 if source.match("<"):
490 # named group: skip forward to end of name
491 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 group = 1
500 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000501 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000502 elif source.match("="):
503 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000504 name = ""
505 while 1:
506 char = source.get()
507 if char is None:
508 raise error, "unterminated name"
509 if char == ")":
510 break
511 name = name + char
512 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000513 raise error, "bad character in group name"
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000514 gid = state.groupdict.get(name)
515 if gid is None:
516 raise error, "unknown group name"
Fredrik Lundh72b82ba2000-07-03 21:31:48 +0000517 subpattern.append((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000518 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000519 else:
520 char = source.get()
521 if char is None:
522 raise error, "unexpected end of pattern"
523 raise error, "unknown specifier: ?P%s" % char
524 elif source.match(":"):
525 # non-capturing group
526 group = 2
527 elif source.match("#"):
528 # comment
529 while 1:
530 if source.next is None or source.next == ")":
531 break
532 source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000533 if not source.match(")"):
534 raise error, "unbalanced parenthesis"
535 continue
Fredrik Lundh6f013982000-07-03 18:44:21 +0000536 elif source.next in ("=", "!", "<"):
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000537 # lookahead assertions
538 char = source.get()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000539 dir = 1
540 if char == "<":
541 if source.next not in ("=", "!"):
542 raise error, "syntax error"
543 dir = -1 # lookbehind
544 char = source.get()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000545 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000546 if not source.match(")"):
547 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000548 if char == "=":
549 subpattern.append((ASSERT, (dir, p)))
550 else:
551 subpattern.append((ASSERT_NOT, (dir, p)))
552 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000553 else:
554 # flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000555 if not FLAGS.has_key(source.next):
556 raise error, "unexpected end of pattern"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000557 while FLAGS.has_key(source.next):
558 state.flags = state.flags | FLAGS[source.get()]
559 if group:
560 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000561 if group == 2:
562 # anonymous group
563 group = None
564 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000565 group = state.opengroup(name)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000566 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000567 if not source.match(")"):
568 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000569 if group is not None:
570 state.closegroup(group)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000571 subpattern.append((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000572 else:
573 while 1:
574 char = source.get()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000575 if char is None:
576 raise error, "unexpected end of pattern"
577 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000578 break
579 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000580
Fredrik Lundh90a07912000-06-30 07:50:59 +0000581 elif this == "^":
582 subpattern.append((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000583
Fredrik Lundh90a07912000-06-30 07:50:59 +0000584 elif this == "$":
585 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000586
Fredrik Lundh90a07912000-06-30 07:50:59 +0000587 elif this and this[0] == "\\":
588 code = _escape(source, this, state)
589 subpattern.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000590
Fredrik Lundh90a07912000-06-30 07:50:59 +0000591 else:
592 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000593
594 return subpattern
595
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000596def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000597 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000598
599 source = Tokenizer(str)
600
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000601 if pattern is None:
602 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000603 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000604 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000605
606 p = _parse_sub(source, pattern, 0)
607
608 tail = source.get()
609 if tail == ")":
610 raise error, "unbalanced parenthesis"
611 elif tail:
612 raise error, "bogus characters at end of regular expression"
613
Fredrik Lundh770617b2001-01-14 15:06:11 +0000614 if flags & SRE_FLAG_DEBUG:
615 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000616
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000617 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
618 # the VERBOSE flag was switched on inside the pattern. to be
619 # on the safe side, we'll parse the whole thing again...
620 return parse(str, p.pattern.flags)
621
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000622 return p
623
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000624def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000625 # parse 're' replacement string into list of literals and
626 # group references
627 s = Tokenizer(source)
628 p = []
629 a = p.append
630 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000631 this = s.get()
632 if this is None:
633 break # end of replacement string
634 if this and this[0] == "\\":
635 # group
636 if this == "\\g":
637 name = ""
638 if s.match("<"):
639 while 1:
640 char = s.get()
641 if char is None:
642 raise error, "unterminated group name"
643 if char == ">":
644 break
645 name = name + char
646 if not name:
647 raise error, "bad group name"
648 try:
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000649 index = int(name)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000650 except ValueError:
651 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000652 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000653 try:
654 index = pattern.groupindex[name]
655 except KeyError:
656 raise IndexError, "unknown group name"
657 a((MARK, index))
658 elif len(this) > 1 and this[1] in DIGITS:
659 code = None
660 while 1:
661 group = _group(this, pattern.groups+1)
662 if group:
Fredrik Lundh19f977b2000-09-24 14:46:23 +0000663 if (s.next not in DIGITS or
Fredrik Lundh90a07912000-06-30 07:50:59 +0000664 not _group(this + s.next, pattern.groups+1)):
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000665 code = MARK, group
Fredrik Lundh90a07912000-06-30 07:50:59 +0000666 break
667 elif s.next in OCTDIGITS:
668 this = this + s.get()
669 else:
670 break
671 if not code:
672 this = this[1:]
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000673 code = LITERAL, int(this[-6:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000674 a(code)
675 else:
676 try:
677 a(ESCAPES[this])
678 except KeyError:
679 for c in this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000680 a((LITERAL, ord(c)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000681 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000682 a((LITERAL, ord(this)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000683 return p
684
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000685def expand_template(template, match):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000686 # XXX: <fl> this is sooooo slow. drop in the slicelist code instead
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000687 p = []
688 a = p.append
Fredrik Lundh0640e112000-06-30 13:55:15 +0000689 sep = match.string[:0]
690 if type(sep) is type(""):
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000691 char = chr
Fredrik Lundh0640e112000-06-30 13:55:15 +0000692 else:
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000693 char = unichr
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000694 for c, s in template:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000695 if c is LITERAL:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000696 a(char(s))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000697 elif c is MARK:
698 s = match.group(s)
699 if s is None:
700 raise error, "empty group"
701 a(s)
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000702 return sep.join(p)