blob: fc3c4928bce772f19e00131ec4180614c3cd57bd [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
Skip Montanaro0de65802001-02-15 22:15:14 +000017__all__ = ["Pattern","SubPattern","Tokenizer","parse","parse_template",
18 "expand_template"]
19
Guido van Rossum7627c0d2000-03-31 14:58:54 +000020SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000021REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000022
Tim Peters17289422000-09-02 07:44:32 +000023DIGITS = tuple("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000024
Fredrik Lundh75f2d672000-06-29 11:34:28 +000025OCTDIGITS = tuple("01234567")
26HEXDIGITS = tuple("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000027
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000028WHITESPACE = tuple(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000029
Guido van Rossum7627c0d2000-03-31 14:58:54 +000030ESCAPES = {
Fredrik Lundh0640e112000-06-30 13:55:15 +000031 r"\a": (LITERAL, 7),
32 r"\b": (LITERAL, 8),
33 r"\f": (LITERAL, 12),
34 r"\n": (LITERAL, 10),
35 r"\r": (LITERAL, 13),
36 r"\t": (LITERAL, 9),
37 r"\v": (LITERAL, 11),
38 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000039}
40
41CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000042 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000043 r"\b": (AT, AT_BOUNDARY),
44 r"\B": (AT, AT_NON_BOUNDARY),
45 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
46 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
47 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
48 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
49 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
50 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000051 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000052}
53
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000054FLAGS = {
Fredrik Lundh436c3d582000-06-29 08:58:44 +000055 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000056 "i": SRE_FLAG_IGNORECASE,
57 "L": SRE_FLAG_LOCALE,
58 "m": SRE_FLAG_MULTILINE,
59 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000060 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000061 # extensions
62 "t": SRE_FLAG_TEMPLATE,
63 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000064}
65
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000066class Pattern:
67 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000068 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000069 self.flags = 0
Fredrik Lundhebc37b22000-10-28 19:30:41 +000070 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000071 self.groups = 1
72 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000073 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000074 gid = self.groups
75 self.groups = gid + 1
76 if name:
77 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000078 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000079 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000080 def closegroup(self, gid):
81 self.open.remove(gid)
82 def checkgroup(self, gid):
83 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000084
85class SubPattern:
86 # a subpattern, in intermediate form
87 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000088 self.pattern = pattern
89 if not data:
90 data = []
91 self.data = data
92 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000093 def dump(self, level=0):
94 nl = 1
95 for op, av in self.data:
96 print level*" " + op,; nl = 0
97 if op == "in":
98 # member sublanguage
99 print; nl = 1
100 for op, a in av:
101 print (level+1)*" " + op, a
102 elif op == "branch":
103 print; nl = 1
104 i = 0
105 for a in av[1]:
106 if i > 0:
107 print level*" " + "or"
108 a.dump(level+1); nl = 1
109 i = i + 1
110 elif type(av) in (type(()), type([])):
111 for a in av:
112 if isinstance(a, SubPattern):
113 if not nl: print
114 a.dump(level+1); nl = 1
115 else:
116 print a, ; nl = 0
117 else:
118 print av, ; nl = 0
119 if not nl: print
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000120 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000121 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000122 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000123 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000124 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000125 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000126 def __getitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000127 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000128 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000129 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000130 def __getslice__(self, start, stop):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000131 return SubPattern(self.pattern, self.data[start:stop])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000132 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000133 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000134 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000135 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000136 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000137 # determine the width (min, max) for this subpattern
138 if self.width:
139 return self.width
140 lo = hi = 0L
141 for op, av in self.data:
142 if op is BRANCH:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000143 i = sys.maxint
144 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000145 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000146 l, h = av.getwidth()
147 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000148 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000149 lo = lo + i
150 hi = hi + j
151 elif op is CALL:
152 i, j = av.getwidth()
153 lo = lo + i
154 hi = hi + j
155 elif op is SUBPATTERN:
156 i, j = av[1].getwidth()
157 lo = lo + i
158 hi = hi + j
159 elif op in (MIN_REPEAT, MAX_REPEAT):
160 i, j = av[2].getwidth()
161 lo = lo + long(i) * av[0]
162 hi = hi + long(j) * av[1]
163 elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY):
164 lo = lo + 1
165 hi = hi + 1
166 elif op == SUCCESS:
167 break
168 self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint))
169 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000170
171class Tokenizer:
172 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000173 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000174 self.index = 0
175 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000176 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000177 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000178 self.next = None
179 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000180 char = self.string[self.index]
181 if char[0] == "\\":
182 try:
183 c = self.string[self.index + 1]
184 except IndexError:
185 raise error, "bogus escape"
186 char = char + c
187 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000188 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000189 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000190 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000191 if skip:
192 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000193 return 1
194 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000195 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000196 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000197 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000198 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000199 def tell(self):
200 return self.index, self.next
201 def seek(self, index):
202 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000203
Fredrik Lundh4781b072000-06-29 12:38:45 +0000204def isident(char):
205 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
206
207def isdigit(char):
208 return "0" <= char <= "9"
209
210def isname(name):
211 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000212 if not isident(name[0]):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000213 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000214 for char in name:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000215 if not isident(char) and not isdigit(char):
216 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000217 return 1
218
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000219def _group(escape, groups):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000220 # check if the escape string represents a valid group
221 try:
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000222 gid = int(escape[1:])
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000223 if gid and gid < groups:
224 return gid
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000225 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000226 pass
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000227 return None # not a valid group
228
229def _class_escape(source, escape):
230 # handle escape code inside character class
231 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000232 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000233 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000234 code = CATEGORIES.get(escape)
235 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000236 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000237 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000238 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000239 # hexadecimal escape (exactly two digits)
240 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000241 escape = escape + source.get()
242 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000243 if len(escape) != 2:
244 raise error, "bogus escape: %s" % repr("\\" + escape)
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000245 return LITERAL, int(escape, 16) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000246 elif str(escape[1:2]) in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000247 # octal escape (up to three digits)
248 while source.next in OCTDIGITS and len(escape) < 5:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000249 escape = escape + source.get()
250 escape = escape[1:]
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000251 return LITERAL, int(escape, 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000252 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000253 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000254 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000255 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000256 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000257
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000258def _escape(source, escape, state):
259 # handle escape code in expression
260 code = CATEGORIES.get(escape)
261 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000262 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000263 code = ESCAPES.get(escape)
264 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000265 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000266 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000267 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000268 # hexadecimal escape
269 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000270 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000271 if len(escape) != 4:
272 raise ValueError
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000273 return LITERAL, int(escape[2:], 16) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000274 elif escape[1:2] == "0":
275 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000276 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000277 escape = escape + source.get()
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000278 return LITERAL, int(escape[1:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000279 elif escape[1:2] in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000280 # octal escape *or* decimal group reference (sigh)
281 here = source.tell()
282 if source.next in DIGITS:
283 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000284 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
285 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000286 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000287 escape = escape + source.get()
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000288 return LITERAL, int(escape[1:], 8) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000289 # got at least one decimal digit; this is a group reference
290 group = _group(escape, state.groups)
291 if group:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000292 if not state.checkgroup(group):
293 raise error, "cannot refer to open group"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000294 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000295 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000296 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000297 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000298 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000299 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000300 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000301
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000302def _parse_sub(source, state, nested=1):
303 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000304
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000305 items = []
306 while 1:
307 items.append(_parse(source, state))
308 if source.match("|"):
309 continue
310 if not nested:
311 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000312 if not source.next or source.match(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000313 break
314 else:
315 raise error, "pattern not properly closed"
316
317 if len(items) == 1:
318 return items[0]
319
320 subpattern = SubPattern(state)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000321
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000322 # check if all items share a common prefix
323 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000324 prefix = None
325 for item in items:
326 if not item:
327 break
328 if prefix is None:
329 prefix = item[0]
330 elif item[0] != prefix:
331 break
332 else:
333 # all subitems start with a common "prefix".
334 # move it out of the branch
335 for item in items:
336 del item[0]
337 subpattern.append(prefix)
338 continue # check next one
339 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000340
341 # check if the branch can be replaced by a character set
342 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000343 if len(item) != 1 or item[0][0] != LITERAL:
344 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000345 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000346 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000347 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000348 set = []
349 for item in items:
350 set.append(item[0])
351 subpattern.append((IN, set))
352 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000353
354 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000355 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000356
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000357def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000358 # parse a simple pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000359
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000360 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000361
362 while 1:
363
Fredrik Lundh90a07912000-06-30 07:50:59 +0000364 if source.next in ("|", ")"):
365 break # end of subpattern
366 this = source.get()
367 if this is None:
368 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000369
Fredrik Lundh90a07912000-06-30 07:50:59 +0000370 if state.flags & SRE_FLAG_VERBOSE:
371 # skip whitespace and comments
372 if this in WHITESPACE:
373 continue
374 if this == "#":
375 while 1:
376 this = source.get()
377 if this in (None, "\n"):
378 break
379 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000380
Fredrik Lundh90a07912000-06-30 07:50:59 +0000381 if this and this[0] not in SPECIAL_CHARS:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000382 subpattern.append((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000383
Fredrik Lundh90a07912000-06-30 07:50:59 +0000384 elif this == "[":
385 # character set
386 set = []
387## if source.match(":"):
388## pass # handle character classes
389 if source.match("^"):
390 set.append((NEGATE, None))
391 # check remaining characters
392 start = set[:]
393 while 1:
394 this = source.get()
395 if this == "]" and set != start:
396 break
397 elif this and this[0] == "\\":
398 code1 = _class_escape(source, this)
399 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000400 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000401 else:
402 raise error, "unexpected end of regular expression"
403 if source.match("-"):
404 # potential range
405 this = source.get()
406 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000407 if code1[0] is IN:
408 code1 = code1[1][0]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000409 set.append(code1)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000410 set.append((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000411 break
412 else:
413 if this[0] == "\\":
414 code2 = _class_escape(source, this)
415 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000416 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000417 if code1[0] != LITERAL or code2[0] != LITERAL:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000418 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000419 lo = code1[1]
420 hi = code2[1]
421 if hi < lo:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000422 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000423 set.append((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000424 else:
425 if code1[0] is IN:
426 code1 = code1[1][0]
427 set.append(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000428
Fredrik Lundh770617b2001-01-14 15:06:11 +0000429 # XXX: <fl> should move set optimization to compiler!
Fredrik Lundh90a07912000-06-30 07:50:59 +0000430 if len(set)==1 and set[0][0] is LITERAL:
431 subpattern.append(set[0]) # optimization
432 elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
433 subpattern.append((NOT_LITERAL, set[1][1])) # optimization
434 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000435 # XXX: <fl> should add charmap optimization here
Fredrik Lundh90a07912000-06-30 07:50:59 +0000436 subpattern.append((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000437
Fredrik Lundh90a07912000-06-30 07:50:59 +0000438 elif this and this[0] in REPEAT_CHARS:
439 # repeat previous item
440 if this == "?":
441 min, max = 0, 1
442 elif this == "*":
443 min, max = 0, MAXREPEAT
444 elif this == "+":
445 min, max = 1, MAXREPEAT
446 elif this == "{":
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000447 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000448 min, max = 0, MAXREPEAT
449 lo = hi = ""
450 while source.next in DIGITS:
451 lo = lo + source.get()
452 if source.match(","):
453 while source.next in DIGITS:
454 hi = hi + source.get()
455 else:
456 hi = lo
457 if not source.match("}"):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000458 subpattern.append((LITERAL, ord(this)))
459 source.seek(here)
460 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000461 if lo:
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000462 min = int(lo)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000463 if hi:
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000464 max = int(hi)
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000465 if max < min:
466 raise error, "bad repeat interval"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000467 else:
468 raise error, "not supported"
469 # figure out which item to repeat
470 if subpattern:
471 item = subpattern[-1:]
472 else:
473 raise error, "nothing to repeat"
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000474 if item[0][0] in (MIN_REPEAT, MAX_REPEAT):
475 raise error, "multiple repeat"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000476 if source.match("?"):
477 subpattern[-1] = (MIN_REPEAT, (min, max, item))
478 else:
479 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000480
Fredrik Lundh90a07912000-06-30 07:50:59 +0000481 elif this == ".":
482 subpattern.append((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000483
Fredrik Lundh90a07912000-06-30 07:50:59 +0000484 elif this == "(":
485 group = 1
486 name = None
487 if source.match("?"):
488 group = 0
489 # options
490 if source.match("P"):
491 # python extensions
492 if source.match("<"):
493 # named group: skip forward to end of name
494 name = ""
495 while 1:
496 char = source.get()
497 if char is None:
498 raise error, "unterminated name"
499 if char == ">":
500 break
501 name = name + char
502 group = 1
503 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000504 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000505 elif source.match("="):
506 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000507 name = ""
508 while 1:
509 char = source.get()
510 if char is None:
511 raise error, "unterminated name"
512 if char == ")":
513 break
514 name = name + char
515 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000516 raise error, "bad character in group name"
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000517 gid = state.groupdict.get(name)
518 if gid is None:
519 raise error, "unknown group name"
Fredrik Lundh72b82ba2000-07-03 21:31:48 +0000520 subpattern.append((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000521 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000522 else:
523 char = source.get()
524 if char is None:
525 raise error, "unexpected end of pattern"
526 raise error, "unknown specifier: ?P%s" % char
527 elif source.match(":"):
528 # non-capturing group
529 group = 2
530 elif source.match("#"):
531 # comment
532 while 1:
533 if source.next is None or source.next == ")":
534 break
535 source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000536 if not source.match(")"):
537 raise error, "unbalanced parenthesis"
538 continue
Fredrik Lundh6f013982000-07-03 18:44:21 +0000539 elif source.next in ("=", "!", "<"):
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000540 # lookahead assertions
541 char = source.get()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000542 dir = 1
543 if char == "<":
544 if source.next not in ("=", "!"):
545 raise error, "syntax error"
546 dir = -1 # lookbehind
547 char = source.get()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000548 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000549 if not source.match(")"):
550 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000551 if char == "=":
552 subpattern.append((ASSERT, (dir, p)))
553 else:
554 subpattern.append((ASSERT_NOT, (dir, p)))
555 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000556 else:
557 # flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000558 if not FLAGS.has_key(source.next):
559 raise error, "unexpected end of pattern"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000560 while FLAGS.has_key(source.next):
561 state.flags = state.flags | FLAGS[source.get()]
562 if group:
563 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000564 if group == 2:
565 # anonymous group
566 group = None
567 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000568 group = state.opengroup(name)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000569 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000570 if not source.match(")"):
571 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000572 if group is not None:
573 state.closegroup(group)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000574 subpattern.append((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000575 else:
576 while 1:
577 char = source.get()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000578 if char is None:
579 raise error, "unexpected end of pattern"
580 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000581 break
582 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000583
Fredrik Lundh90a07912000-06-30 07:50:59 +0000584 elif this == "^":
585 subpattern.append((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000586
Fredrik Lundh90a07912000-06-30 07:50:59 +0000587 elif this == "$":
588 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000589
Fredrik Lundh90a07912000-06-30 07:50:59 +0000590 elif this and this[0] == "\\":
591 code = _escape(source, this, state)
592 subpattern.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000593
Fredrik Lundh90a07912000-06-30 07:50:59 +0000594 else:
595 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000596
597 return subpattern
598
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000599def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000600 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000601
602 source = Tokenizer(str)
603
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000604 if pattern is None:
605 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000606 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000607 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000608
609 p = _parse_sub(source, pattern, 0)
610
611 tail = source.get()
612 if tail == ")":
613 raise error, "unbalanced parenthesis"
614 elif tail:
615 raise error, "bogus characters at end of regular expression"
616
Fredrik Lundh770617b2001-01-14 15:06:11 +0000617 if flags & SRE_FLAG_DEBUG:
618 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000619
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000620 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
621 # the VERBOSE flag was switched on inside the pattern. to be
622 # on the safe side, we'll parse the whole thing again...
623 return parse(str, p.pattern.flags)
624
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000625 return p
626
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000627def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000628 # parse 're' replacement string into list of literals and
629 # group references
630 s = Tokenizer(source)
631 p = []
632 a = p.append
633 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000634 this = s.get()
635 if this is None:
636 break # end of replacement string
637 if this and this[0] == "\\":
638 # group
639 if this == "\\g":
640 name = ""
641 if s.match("<"):
642 while 1:
643 char = s.get()
644 if char is None:
645 raise error, "unterminated group name"
646 if char == ">":
647 break
648 name = name + char
649 if not name:
650 raise error, "bad group name"
651 try:
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000652 index = int(name)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000653 except ValueError:
654 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000655 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000656 try:
657 index = pattern.groupindex[name]
658 except KeyError:
659 raise IndexError, "unknown group name"
660 a((MARK, index))
661 elif len(this) > 1 and this[1] in DIGITS:
662 code = None
663 while 1:
664 group = _group(this, pattern.groups+1)
665 if group:
Fredrik Lundh19f977b2000-09-24 14:46:23 +0000666 if (s.next not in DIGITS or
Fredrik Lundh90a07912000-06-30 07:50:59 +0000667 not _group(this + s.next, pattern.groups+1)):
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000668 code = MARK, group
Fredrik Lundh90a07912000-06-30 07:50:59 +0000669 break
670 elif s.next in OCTDIGITS:
671 this = this + s.get()
672 else:
673 break
674 if not code:
675 this = this[1:]
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000676 code = LITERAL, int(this[-6:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000677 a(code)
678 else:
679 try:
680 a(ESCAPES[this])
681 except KeyError:
682 for c in this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000683 a((LITERAL, ord(c)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000684 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000685 a((LITERAL, ord(this)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000686 return p
687
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000688def expand_template(template, match):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000689 # XXX: <fl> this is sooooo slow. drop in the slicelist code instead
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000690 p = []
691 a = p.append
Fredrik Lundh0640e112000-06-30 13:55:15 +0000692 sep = match.string[:0]
693 if type(sep) is type(""):
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000694 char = chr
Fredrik Lundh0640e112000-06-30 13:55:15 +0000695 else:
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000696 char = unichr
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000697 for c, s in template:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000698 if c is LITERAL:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000699 a(char(s))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000700 elif c is MARK:
701 s = match.group(s)
702 if s is None:
703 raise error, "empty group"
704 a(s)
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000705 return sep.join(p)