blob: 7c6eb9f7647de67b8e89dd7eed8fe83651f5bbd4 [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
Guido van Rossum7627c0d2000-03-31 14:58:54 +000013import string, sys
14
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 Lundh436c3d52000-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 Lundh436c3d52000-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 Lundh1c5aa692001-01-16 07:37:30 +000063try:
64 int("10", 8)
65 atoi = int
66except TypeError:
67 atoi = string.atoi
68
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000069class Pattern:
70 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000071 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000072 self.flags = 0
Fredrik Lundhebc37b22000-10-28 19:30:41 +000073 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000074 self.groups = 1
75 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000076 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000077 gid = self.groups
78 self.groups = gid + 1
79 if name:
80 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000081 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000082 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000083 def closegroup(self, gid):
84 self.open.remove(gid)
85 def checkgroup(self, gid):
86 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000087
88class SubPattern:
89 # a subpattern, in intermediate form
90 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000091 self.pattern = pattern
92 if not data:
93 data = []
94 self.data = data
95 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000096 def dump(self, level=0):
97 nl = 1
98 for op, av in self.data:
99 print level*" " + op,; nl = 0
100 if op == "in":
101 # member sublanguage
102 print; nl = 1
103 for op, a in av:
104 print (level+1)*" " + op, a
105 elif op == "branch":
106 print; nl = 1
107 i = 0
108 for a in av[1]:
109 if i > 0:
110 print level*" " + "or"
111 a.dump(level+1); nl = 1
112 i = i + 1
113 elif type(av) in (type(()), type([])):
114 for a in av:
115 if isinstance(a, SubPattern):
116 if not nl: print
117 a.dump(level+1); nl = 1
118 else:
119 print a, ; nl = 0
120 else:
121 print av, ; nl = 0
122 if not nl: print
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000123 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000124 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000125 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000126 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000127 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000128 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000129 def __getitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000130 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000131 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000132 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000133 def __getslice__(self, start, stop):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000134 return SubPattern(self.pattern, self.data[start:stop])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000135 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000136 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000137 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000138 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000139 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000140 # determine the width (min, max) for this subpattern
141 if self.width:
142 return self.width
143 lo = hi = 0L
144 for op, av in self.data:
145 if op is BRANCH:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000146 i = sys.maxint
147 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000148 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000149 l, h = av.getwidth()
150 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000151 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000152 lo = lo + i
153 hi = hi + j
154 elif op is CALL:
155 i, j = av.getwidth()
156 lo = lo + i
157 hi = hi + j
158 elif op is SUBPATTERN:
159 i, j = av[1].getwidth()
160 lo = lo + i
161 hi = hi + j
162 elif op in (MIN_REPEAT, MAX_REPEAT):
163 i, j = av[2].getwidth()
164 lo = lo + long(i) * av[0]
165 hi = hi + long(j) * av[1]
166 elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY):
167 lo = lo + 1
168 hi = hi + 1
169 elif op == SUCCESS:
170 break
171 self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint))
172 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000173
174class Tokenizer:
175 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000176 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000177 self.index = 0
178 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000179 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000180 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000181 self.next = None
182 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000183 char = self.string[self.index]
184 if char[0] == "\\":
185 try:
186 c = self.string[self.index + 1]
187 except IndexError:
188 raise error, "bogus escape"
189 char = char + c
190 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000191 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000192 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000193 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000194 if skip:
195 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000196 return 1
197 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000198 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000199 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000200 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000201 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000202 def tell(self):
203 return self.index, self.next
204 def seek(self, index):
205 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000206
Fredrik Lundh4781b072000-06-29 12:38:45 +0000207def isident(char):
208 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
209
210def isdigit(char):
211 return "0" <= char <= "9"
212
213def isname(name):
214 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000215 if not isident(name[0]):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000216 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000217 for char in name:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000218 if not isident(char) and not isdigit(char):
219 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000220 return 1
221
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000222def _group(escape, groups):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000223 # check if the escape string represents a valid group
224 try:
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000225 gid = atoi(escape[1:])
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000226 if gid and gid < groups:
227 return gid
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000228 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000229 pass
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000230 return None # not a valid group
231
232def _class_escape(source, escape):
233 # handle escape code inside character class
234 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000235 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000236 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000237 code = CATEGORIES.get(escape)
238 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000239 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000240 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000241 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000242 # hexadecimal escape (exactly two digits)
243 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000244 escape = escape + source.get()
245 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000246 if len(escape) != 2:
247 raise error, "bogus escape: %s" % repr("\\" + escape)
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000248 return LITERAL, atoi(escape, 16) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000249 elif str(escape[1:2]) in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000250 # octal escape (up to three digits)
251 while source.next in OCTDIGITS and len(escape) < 5:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000252 escape = escape + source.get()
253 escape = escape[1:]
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000254 return LITERAL, atoi(escape, 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000255 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000256 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000257 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000258 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000259 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000260
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000261def _escape(source, escape, state):
262 # handle escape code in expression
263 code = CATEGORIES.get(escape)
264 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000265 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000266 code = ESCAPES.get(escape)
267 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000268 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000269 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000270 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000271 # hexadecimal escape
272 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000273 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000274 if len(escape) != 4:
275 raise ValueError
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000276 return LITERAL, atoi(escape[2:], 16) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000277 elif escape[1:2] == "0":
278 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000279 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000280 escape = escape + source.get()
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000281 return LITERAL, atoi(escape[1:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000282 elif escape[1:2] in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000283 # octal escape *or* decimal group reference (sigh)
284 here = source.tell()
285 if source.next in DIGITS:
286 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000287 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
288 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000289 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000290 escape = escape + source.get()
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000291 return LITERAL, atoi(escape[1:], 8) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000292 # got at least one decimal digit; this is a group reference
293 group = _group(escape, state.groups)
294 if group:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000295 if not state.checkgroup(group):
296 raise error, "cannot refer to open group"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000297 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000298 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000299 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000300 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000301 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000302 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000303 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000304
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000305def _parse_sub(source, state, nested=1):
306 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000307
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000308 items = []
309 while 1:
310 items.append(_parse(source, state))
311 if source.match("|"):
312 continue
313 if not nested:
314 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000315 if not source.next or source.match(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000316 break
317 else:
318 raise error, "pattern not properly closed"
319
320 if len(items) == 1:
321 return items[0]
322
323 subpattern = SubPattern(state)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000324
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000325 # check if all items share a common prefix
326 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000327 prefix = None
328 for item in items:
329 if not item:
330 break
331 if prefix is None:
332 prefix = item[0]
333 elif item[0] != prefix:
334 break
335 else:
336 # all subitems start with a common "prefix".
337 # move it out of the branch
338 for item in items:
339 del item[0]
340 subpattern.append(prefix)
341 continue # check next one
342 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000343
344 # check if the branch can be replaced by a character set
345 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000346 if len(item) != 1 or item[0][0] != LITERAL:
347 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000348 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000349 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000350 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000351 set = []
352 for item in items:
353 set.append(item[0])
354 subpattern.append((IN, set))
355 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000356
357 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000358 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000359
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000360def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000361 # parse a simple pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000362
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000363 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000364
365 while 1:
366
Fredrik Lundh90a07912000-06-30 07:50:59 +0000367 if source.next in ("|", ")"):
368 break # end of subpattern
369 this = source.get()
370 if this is None:
371 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000372
Fredrik Lundh90a07912000-06-30 07:50:59 +0000373 if state.flags & SRE_FLAG_VERBOSE:
374 # skip whitespace and comments
375 if this in WHITESPACE:
376 continue
377 if this == "#":
378 while 1:
379 this = source.get()
380 if this in (None, "\n"):
381 break
382 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000383
Fredrik Lundh90a07912000-06-30 07:50:59 +0000384 if this and this[0] not in SPECIAL_CHARS:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000385 subpattern.append((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000386
Fredrik Lundh90a07912000-06-30 07:50:59 +0000387 elif this == "[":
388 # character set
389 set = []
390## if source.match(":"):
391## pass # handle character classes
392 if source.match("^"):
393 set.append((NEGATE, None))
394 # check remaining characters
395 start = set[:]
396 while 1:
397 this = source.get()
398 if this == "]" and set != start:
399 break
400 elif this and this[0] == "\\":
401 code1 = _class_escape(source, this)
402 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000403 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000404 else:
405 raise error, "unexpected end of regular expression"
406 if source.match("-"):
407 # potential range
408 this = source.get()
409 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000410 if code1[0] is IN:
411 code1 = code1[1][0]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000412 set.append(code1)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000413 set.append((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000414 break
415 else:
416 if this[0] == "\\":
417 code2 = _class_escape(source, this)
418 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000419 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000420 if code1[0] != LITERAL or code2[0] != LITERAL:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000421 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000422 lo = code1[1]
423 hi = code2[1]
424 if hi < lo:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000425 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000426 set.append((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000427 else:
428 if code1[0] is IN:
429 code1 = code1[1][0]
430 set.append(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000431
Fredrik Lundh770617b2001-01-14 15:06:11 +0000432 # XXX: <fl> should move set optimization to compiler!
Fredrik Lundh90a07912000-06-30 07:50:59 +0000433 if len(set)==1 and set[0][0] is LITERAL:
434 subpattern.append(set[0]) # optimization
435 elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
436 subpattern.append((NOT_LITERAL, set[1][1])) # optimization
437 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000438 # XXX: <fl> should add charmap optimization here
Fredrik Lundh90a07912000-06-30 07:50:59 +0000439 subpattern.append((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000440
Fredrik Lundh90a07912000-06-30 07:50:59 +0000441 elif this and this[0] in REPEAT_CHARS:
442 # repeat previous item
443 if this == "?":
444 min, max = 0, 1
445 elif this == "*":
446 min, max = 0, MAXREPEAT
447 elif this == "+":
448 min, max = 1, MAXREPEAT
449 elif this == "{":
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000450 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000451 min, max = 0, MAXREPEAT
452 lo = hi = ""
453 while source.next in DIGITS:
454 lo = lo + source.get()
455 if source.match(","):
456 while source.next in DIGITS:
457 hi = hi + source.get()
458 else:
459 hi = lo
460 if not source.match("}"):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000461 subpattern.append((LITERAL, ord(this)))
462 source.seek(here)
463 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000464 if lo:
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000465 min = atoi(lo)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000466 if hi:
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000467 max = atoi(hi)
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000468 if max < min:
469 raise error, "bad repeat interval"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000470 else:
471 raise error, "not supported"
472 # figure out which item to repeat
473 if subpattern:
474 item = subpattern[-1:]
475 else:
476 raise error, "nothing to repeat"
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000477 if item[0][0] in (MIN_REPEAT, MAX_REPEAT):
478 raise error, "multiple repeat"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000479 if source.match("?"):
480 subpattern[-1] = (MIN_REPEAT, (min, max, item))
481 else:
482 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000483
Fredrik Lundh90a07912000-06-30 07:50:59 +0000484 elif this == ".":
485 subpattern.append((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000486
Fredrik Lundh90a07912000-06-30 07:50:59 +0000487 elif this == "(":
488 group = 1
489 name = None
490 if source.match("?"):
491 group = 0
492 # options
493 if source.match("P"):
494 # python extensions
495 if source.match("<"):
496 # named group: skip forward to end of name
497 name = ""
498 while 1:
499 char = source.get()
500 if char is None:
501 raise error, "unterminated name"
502 if char == ">":
503 break
504 name = name + char
505 group = 1
506 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000507 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000508 elif source.match("="):
509 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000510 name = ""
511 while 1:
512 char = source.get()
513 if char is None:
514 raise error, "unterminated name"
515 if char == ")":
516 break
517 name = name + char
518 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000519 raise error, "bad character in group name"
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000520 gid = state.groupdict.get(name)
521 if gid is None:
522 raise error, "unknown group name"
Fredrik Lundh72b82ba2000-07-03 21:31:48 +0000523 subpattern.append((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000524 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000525 else:
526 char = source.get()
527 if char is None:
528 raise error, "unexpected end of pattern"
529 raise error, "unknown specifier: ?P%s" % char
530 elif source.match(":"):
531 # non-capturing group
532 group = 2
533 elif source.match("#"):
534 # comment
535 while 1:
536 if source.next is None or source.next == ")":
537 break
538 source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000539 if not source.match(")"):
540 raise error, "unbalanced parenthesis"
541 continue
Fredrik Lundh6f013982000-07-03 18:44:21 +0000542 elif source.next in ("=", "!", "<"):
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000543 # lookahead assertions
544 char = source.get()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000545 dir = 1
546 if char == "<":
547 if source.next not in ("=", "!"):
548 raise error, "syntax error"
549 dir = -1 # lookbehind
550 char = source.get()
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 if char == "=":
555 subpattern.append((ASSERT, (dir, p)))
556 else:
557 subpattern.append((ASSERT_NOT, (dir, p)))
558 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000559 else:
560 # flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000561 if not FLAGS.has_key(source.next):
562 raise error, "unexpected end of pattern"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000563 while FLAGS.has_key(source.next):
564 state.flags = state.flags | FLAGS[source.get()]
565 if group:
566 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000567 if group == 2:
568 # anonymous group
569 group = None
570 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000571 group = state.opengroup(name)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000572 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000573 if not source.match(")"):
574 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000575 if group is not None:
576 state.closegroup(group)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000577 subpattern.append((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000578 else:
579 while 1:
580 char = source.get()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000581 if char is None:
582 raise error, "unexpected end of pattern"
583 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000584 break
585 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000586
Fredrik Lundh90a07912000-06-30 07:50:59 +0000587 elif this == "^":
588 subpattern.append((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000589
Fredrik Lundh90a07912000-06-30 07:50:59 +0000590 elif this == "$":
591 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000592
Fredrik Lundh90a07912000-06-30 07:50:59 +0000593 elif this and this[0] == "\\":
594 code = _escape(source, this, state)
595 subpattern.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000596
Fredrik Lundh90a07912000-06-30 07:50:59 +0000597 else:
598 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000599
600 return subpattern
601
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000602def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000603 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000604
605 source = Tokenizer(str)
606
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000607 if pattern is None:
608 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000609 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000610 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000611
612 p = _parse_sub(source, pattern, 0)
613
614 tail = source.get()
615 if tail == ")":
616 raise error, "unbalanced parenthesis"
617 elif tail:
618 raise error, "bogus characters at end of regular expression"
619
Fredrik Lundh770617b2001-01-14 15:06:11 +0000620 if flags & SRE_FLAG_DEBUG:
621 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000622
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000623 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
624 # the VERBOSE flag was switched on inside the pattern. to be
625 # on the safe side, we'll parse the whole thing again...
626 return parse(str, p.pattern.flags)
627
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000628 return p
629
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000630def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000631 # parse 're' replacement string into list of literals and
632 # group references
633 s = Tokenizer(source)
634 p = []
635 a = p.append
636 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000637 this = s.get()
638 if this is None:
639 break # end of replacement string
640 if this and this[0] == "\\":
641 # group
642 if this == "\\g":
643 name = ""
644 if s.match("<"):
645 while 1:
646 char = s.get()
647 if char is None:
648 raise error, "unterminated group name"
649 if char == ">":
650 break
651 name = name + char
652 if not name:
653 raise error, "bad group name"
654 try:
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000655 index = atoi(name)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000656 except ValueError:
657 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000658 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000659 try:
660 index = pattern.groupindex[name]
661 except KeyError:
662 raise IndexError, "unknown group name"
663 a((MARK, index))
664 elif len(this) > 1 and this[1] in DIGITS:
665 code = None
666 while 1:
667 group = _group(this, pattern.groups+1)
668 if group:
Fredrik Lundh19f977b2000-09-24 14:46:23 +0000669 if (s.next not in DIGITS or
Fredrik Lundh90a07912000-06-30 07:50:59 +0000670 not _group(this + s.next, pattern.groups+1)):
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000671 code = MARK, group
Fredrik Lundh90a07912000-06-30 07:50:59 +0000672 break
673 elif s.next in OCTDIGITS:
674 this = this + s.get()
675 else:
676 break
677 if not code:
678 this = this[1:]
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000679 code = LITERAL, atoi(this[-6:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000680 a(code)
681 else:
682 try:
683 a(ESCAPES[this])
684 except KeyError:
685 for c in this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000686 a((LITERAL, ord(c)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000687 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000688 a((LITERAL, ord(this)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000689 return p
690
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000691def expand_template(template, match):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000692 # XXX: <fl> this is sooooo slow. drop in the slicelist code instead
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000693 p = []
694 a = p.append
Fredrik Lundh0640e112000-06-30 13:55:15 +0000695 sep = match.string[:0]
696 if type(sep) is type(""):
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000697 char = chr
Fredrik Lundh0640e112000-06-30 13:55:15 +0000698 else:
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000699 char = unichr
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000700 for c, s in template:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000701 if c is LITERAL:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000702 a(char(s))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000703 elif c is MARK:
704 s = match.group(s)
705 if s is None:
706 raise error, "empty group"
707 a(s)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000708 return string.join(p, sep)