blob: 3840365b8ef03dd055328aaa50161a4fb650d63d [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
Fredrik Lundhf2989b22001-02-18 12:05:16 +000013# this module works under 1.5.2 and later. don't use string methods
14import string, sys
Guido van Rossum7627c0d2000-03-31 14:58:54 +000015
16from sre_constants import *
17
18SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000019REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000020
Tim Peters17289422000-09-02 07:44:32 +000021DIGITS = tuple("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000022
Fredrik Lundh75f2d672000-06-29 11:34:28 +000023OCTDIGITS = tuple("01234567")
24HEXDIGITS = tuple("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000025
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000026WHITESPACE = tuple(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000027
Guido van Rossum7627c0d2000-03-31 14:58:54 +000028ESCAPES = {
Fredrik Lundhf2989b22001-02-18 12:05:16 +000029 r"\a": (LITERAL, ord("\a")),
30 r"\b": (LITERAL, ord("\b")),
31 r"\f": (LITERAL, ord("\f")),
32 r"\n": (LITERAL, ord("\n")),
33 r"\r": (LITERAL, ord("\r")),
34 r"\t": (LITERAL, ord("\t")),
35 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000036 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000037}
38
39CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000040 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000041 r"\b": (AT, AT_BOUNDARY),
42 r"\B": (AT, AT_NON_BOUNDARY),
43 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
44 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
45 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
46 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
47 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
48 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000049 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000050}
51
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000052FLAGS = {
Fredrik Lundh436c3d582000-06-29 08:58:44 +000053 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000054 "i": SRE_FLAG_IGNORECASE,
55 "L": SRE_FLAG_LOCALE,
56 "m": SRE_FLAG_MULTILINE,
57 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000058 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000059 # extensions
60 "t": SRE_FLAG_TEMPLATE,
61 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000062}
63
Fredrik Lundhf2989b22001-02-18 12:05:16 +000064# figure out best way to convert hex/octal numbers to integers
65try:
66 int("10", 8)
67 atoi = int # 2.0 and later
68except TypeError:
69 atoi = string.atoi # 1.5.2
70
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000071class Pattern:
72 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000073 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000074 self.flags = 0
Fredrik Lundhebc37b22000-10-28 19:30:41 +000075 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000076 self.groups = 1
77 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000078 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000079 gid = self.groups
80 self.groups = gid + 1
81 if name:
82 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000083 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000084 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000085 def closegroup(self, gid):
86 self.open.remove(gid)
87 def checkgroup(self, gid):
88 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000089
90class SubPattern:
91 # a subpattern, in intermediate form
92 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000093 self.pattern = pattern
94 if not data:
95 data = []
96 self.data = data
97 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000098 def dump(self, level=0):
99 nl = 1
100 for op, av in self.data:
101 print level*" " + op,; nl = 0
102 if op == "in":
103 # member sublanguage
104 print; nl = 1
105 for op, a in av:
106 print (level+1)*" " + op, a
107 elif op == "branch":
108 print; nl = 1
109 i = 0
110 for a in av[1]:
111 if i > 0:
112 print level*" " + "or"
113 a.dump(level+1); nl = 1
114 i = i + 1
115 elif type(av) in (type(()), type([])):
116 for a in av:
117 if isinstance(a, SubPattern):
118 if not nl: print
119 a.dump(level+1); nl = 1
120 else:
121 print a, ; nl = 0
122 else:
123 print av, ; nl = 0
124 if not nl: print
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000125 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000126 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000127 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000128 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000129 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000130 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000131 def __getitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000132 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000133 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000134 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000135 def __getslice__(self, start, stop):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000136 return SubPattern(self.pattern, self.data[start:stop])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000137 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000138 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000139 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000140 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000141 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000142 # determine the width (min, max) for this subpattern
143 if self.width:
144 return self.width
145 lo = hi = 0L
146 for op, av in self.data:
147 if op is BRANCH:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000148 i = sys.maxint
149 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000150 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000151 l, h = av.getwidth()
152 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000153 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000154 lo = lo + i
155 hi = hi + j
156 elif op is CALL:
157 i, j = av.getwidth()
158 lo = lo + i
159 hi = hi + j
160 elif op is SUBPATTERN:
161 i, j = av[1].getwidth()
162 lo = lo + i
163 hi = hi + j
164 elif op in (MIN_REPEAT, MAX_REPEAT):
165 i, j = av[2].getwidth()
166 lo = lo + long(i) * av[0]
167 hi = hi + long(j) * av[1]
168 elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY):
169 lo = lo + 1
170 hi = hi + 1
171 elif op == SUCCESS:
172 break
173 self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint))
174 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000175
176class Tokenizer:
177 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000178 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000179 self.index = 0
180 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000181 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000182 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000183 self.next = None
184 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000185 char = self.string[self.index]
186 if char[0] == "\\":
187 try:
188 c = self.string[self.index + 1]
189 except IndexError:
190 raise error, "bogus escape"
191 char = char + c
192 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000193 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000194 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000195 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000196 if skip:
197 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000198 return 1
199 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000200 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000201 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000202 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000203 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000204 def tell(self):
205 return self.index, self.next
206 def seek(self, index):
207 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000208
Fredrik Lundh4781b072000-06-29 12:38:45 +0000209def isident(char):
210 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
211
212def isdigit(char):
213 return "0" <= char <= "9"
214
215def isname(name):
216 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000217 if not isident(name[0]):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000218 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000219 for char in name:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000220 if not isident(char) and not isdigit(char):
221 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000222 return 1
223
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000224def _group(escape, groups):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000225 # check if the escape string represents a valid group
226 try:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000227 gid = atoi(escape[1:])
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000228 if gid and gid < groups:
229 return gid
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000230 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000231 pass
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000232 return None # not a valid group
233
234def _class_escape(source, escape):
235 # handle escape code inside character class
236 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000237 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000238 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000239 code = CATEGORIES.get(escape)
240 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000241 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000242 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000243 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000244 # hexadecimal escape (exactly two digits)
245 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000246 escape = escape + source.get()
247 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000248 if len(escape) != 2:
249 raise error, "bogus escape: %s" % repr("\\" + escape)
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000250 return LITERAL, atoi(escape, 16) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000251 elif str(escape[1:2]) in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000252 # octal escape (up to three digits)
253 while source.next in OCTDIGITS and len(escape) < 5:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000254 escape = escape + source.get()
255 escape = escape[1:]
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000256 return LITERAL, atoi(escape, 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000257 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000258 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000259 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000260 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000261 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000262
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000263def _escape(source, escape, state):
264 # handle escape code in expression
265 code = CATEGORIES.get(escape)
266 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000267 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000268 code = ESCAPES.get(escape)
269 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000270 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000271 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000272 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000273 # hexadecimal escape
274 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000275 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000276 if len(escape) != 4:
277 raise ValueError
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000278 return LITERAL, atoi(escape[2:], 16) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000279 elif escape[1:2] == "0":
280 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000281 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000282 escape = escape + source.get()
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000283 return LITERAL, atoi(escape[1:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000284 elif escape[1:2] in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000285 # octal escape *or* decimal group reference (sigh)
286 here = source.tell()
287 if source.next in DIGITS:
288 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000289 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
290 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000291 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000292 escape = escape + source.get()
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000293 return LITERAL, atoi(escape[1:], 8) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000294 # got at least one decimal digit; this is a group reference
295 group = _group(escape, state.groups)
296 if group:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000297 if not state.checkgroup(group):
298 raise error, "cannot refer to open group"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000299 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000300 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000301 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000302 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000303 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000304 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000305 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000306
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000307def _parse_sub(source, state, nested=1):
308 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000309
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000310 items = []
311 while 1:
312 items.append(_parse(source, state))
313 if source.match("|"):
314 continue
315 if not nested:
316 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000317 if not source.next or source.match(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000318 break
319 else:
320 raise error, "pattern not properly closed"
321
322 if len(items) == 1:
323 return items[0]
324
325 subpattern = SubPattern(state)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000326
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000327 # check if all items share a common prefix
328 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000329 prefix = None
330 for item in items:
331 if not item:
332 break
333 if prefix is None:
334 prefix = item[0]
335 elif item[0] != prefix:
336 break
337 else:
338 # all subitems start with a common "prefix".
339 # move it out of the branch
340 for item in items:
341 del item[0]
342 subpattern.append(prefix)
343 continue # check next one
344 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000345
346 # check if the branch can be replaced by a character set
347 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000348 if len(item) != 1 or item[0][0] != LITERAL:
349 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000350 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000351 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000352 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000353 set = []
354 for item in items:
355 set.append(item[0])
356 subpattern.append((IN, set))
357 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000358
359 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000360 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000361
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000362def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000363 # parse a simple pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000364
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000365 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000366
367 while 1:
368
Fredrik Lundh90a07912000-06-30 07:50:59 +0000369 if source.next in ("|", ")"):
370 break # end of subpattern
371 this = source.get()
372 if this is None:
373 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000374
Fredrik Lundh90a07912000-06-30 07:50:59 +0000375 if state.flags & SRE_FLAG_VERBOSE:
376 # skip whitespace and comments
377 if this in WHITESPACE:
378 continue
379 if this == "#":
380 while 1:
381 this = source.get()
382 if this in (None, "\n"):
383 break
384 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000385
Fredrik Lundh90a07912000-06-30 07:50:59 +0000386 if this and this[0] not in SPECIAL_CHARS:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000387 subpattern.append((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000388
Fredrik Lundh90a07912000-06-30 07:50:59 +0000389 elif this == "[":
390 # character set
391 set = []
392## if source.match(":"):
393## pass # handle character classes
394 if source.match("^"):
395 set.append((NEGATE, None))
396 # check remaining characters
397 start = set[:]
398 while 1:
399 this = source.get()
400 if this == "]" and set != start:
401 break
402 elif this and this[0] == "\\":
403 code1 = _class_escape(source, this)
404 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000405 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000406 else:
407 raise error, "unexpected end of regular expression"
408 if source.match("-"):
409 # potential range
410 this = source.get()
411 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000412 if code1[0] is IN:
413 code1 = code1[1][0]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000414 set.append(code1)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000415 set.append((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000416 break
417 else:
418 if this[0] == "\\":
419 code2 = _class_escape(source, this)
420 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000421 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000422 if code1[0] != LITERAL or code2[0] != LITERAL:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000423 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000424 lo = code1[1]
425 hi = code2[1]
426 if hi < lo:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000427 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000428 set.append((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000429 else:
430 if code1[0] is IN:
431 code1 = code1[1][0]
432 set.append(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000433
Fredrik Lundh770617b2001-01-14 15:06:11 +0000434 # XXX: <fl> should move set optimization to compiler!
Fredrik Lundh90a07912000-06-30 07:50:59 +0000435 if len(set)==1 and set[0][0] is LITERAL:
436 subpattern.append(set[0]) # optimization
437 elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
438 subpattern.append((NOT_LITERAL, set[1][1])) # optimization
439 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000440 # XXX: <fl> should add charmap optimization here
Fredrik Lundh90a07912000-06-30 07:50:59 +0000441 subpattern.append((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000442
Fredrik Lundh90a07912000-06-30 07:50:59 +0000443 elif this and this[0] in REPEAT_CHARS:
444 # repeat previous item
445 if this == "?":
446 min, max = 0, 1
447 elif this == "*":
448 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000449
Fredrik Lundh90a07912000-06-30 07:50:59 +0000450 elif this == "+":
451 min, max = 1, MAXREPEAT
452 elif this == "{":
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000453 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000454 min, max = 0, MAXREPEAT
455 lo = hi = ""
456 while source.next in DIGITS:
457 lo = lo + source.get()
458 if source.match(","):
459 while source.next in DIGITS:
460 hi = hi + source.get()
461 else:
462 hi = lo
463 if not source.match("}"):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000464 subpattern.append((LITERAL, ord(this)))
465 source.seek(here)
466 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000467 if lo:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000468 min = atoi(lo)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000469 if hi:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000470 max = atoi(hi)
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000471 if max < min:
472 raise error, "bad repeat interval"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000473 else:
474 raise error, "not supported"
475 # figure out which item to repeat
476 if subpattern:
477 item = subpattern[-1:]
478 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000479 item = None
480 if not item or (len(item) == 1 and item[0][0] == AT):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000481 raise error, "nothing to repeat"
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000482 if item[0][0] in (MIN_REPEAT, MAX_REPEAT):
483 raise error, "multiple repeat"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000484 if source.match("?"):
485 subpattern[-1] = (MIN_REPEAT, (min, max, item))
486 else:
487 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000488
Fredrik Lundh90a07912000-06-30 07:50:59 +0000489 elif this == ".":
490 subpattern.append((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000491
Fredrik Lundh90a07912000-06-30 07:50:59 +0000492 elif this == "(":
493 group = 1
494 name = None
495 if source.match("?"):
496 group = 0
497 # options
498 if source.match("P"):
499 # python extensions
500 if source.match("<"):
501 # named group: skip forward to end of name
502 name = ""
503 while 1:
504 char = source.get()
505 if char is None:
506 raise error, "unterminated name"
507 if char == ">":
508 break
509 name = name + char
510 group = 1
511 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000512 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000513 elif source.match("="):
514 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000515 name = ""
516 while 1:
517 char = source.get()
518 if char is None:
519 raise error, "unterminated name"
520 if char == ")":
521 break
522 name = name + char
523 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000524 raise error, "bad character in group name"
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000525 gid = state.groupdict.get(name)
526 if gid is None:
527 raise error, "unknown group name"
Fredrik Lundh72b82ba2000-07-03 21:31:48 +0000528 subpattern.append((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000529 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000530 else:
531 char = source.get()
532 if char is None:
533 raise error, "unexpected end of pattern"
534 raise error, "unknown specifier: ?P%s" % char
535 elif source.match(":"):
536 # non-capturing group
537 group = 2
538 elif source.match("#"):
539 # comment
540 while 1:
541 if source.next is None or source.next == ")":
542 break
543 source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000544 if not source.match(")"):
545 raise error, "unbalanced parenthesis"
546 continue
Fredrik Lundh6f013982000-07-03 18:44:21 +0000547 elif source.next in ("=", "!", "<"):
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000548 # lookahead assertions
549 char = source.get()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000550 dir = 1
551 if char == "<":
552 if source.next not in ("=", "!"):
553 raise error, "syntax error"
554 dir = -1 # lookbehind
555 char = source.get()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000556 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000557 if not source.match(")"):
558 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000559 if char == "=":
560 subpattern.append((ASSERT, (dir, p)))
561 else:
562 subpattern.append((ASSERT_NOT, (dir, p)))
563 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000564 else:
565 # flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000566 if not FLAGS.has_key(source.next):
567 raise error, "unexpected end of pattern"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000568 while FLAGS.has_key(source.next):
569 state.flags = state.flags | FLAGS[source.get()]
570 if group:
571 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000572 if group == 2:
573 # anonymous group
574 group = None
575 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000576 group = state.opengroup(name)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000577 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000578 if not source.match(")"):
579 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000580 if group is not None:
581 state.closegroup(group)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000582 subpattern.append((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000583 else:
584 while 1:
585 char = source.get()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000586 if char is None:
587 raise error, "unexpected end of pattern"
588 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000589 break
590 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000591
Fredrik Lundh90a07912000-06-30 07:50:59 +0000592 elif this == "^":
593 subpattern.append((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000594
Fredrik Lundh90a07912000-06-30 07:50:59 +0000595 elif this == "$":
596 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000597
Fredrik Lundh90a07912000-06-30 07:50:59 +0000598 elif this and this[0] == "\\":
599 code = _escape(source, this, state)
600 subpattern.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000601
Fredrik Lundh90a07912000-06-30 07:50:59 +0000602 else:
603 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000604
605 return subpattern
606
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000607def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000608 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000609
610 source = Tokenizer(str)
611
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000612 if pattern is None:
613 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000614 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000615 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000616
617 p = _parse_sub(source, pattern, 0)
618
619 tail = source.get()
620 if tail == ")":
621 raise error, "unbalanced parenthesis"
622 elif tail:
623 raise error, "bogus characters at end of regular expression"
624
Fredrik Lundh770617b2001-01-14 15:06:11 +0000625 if flags & SRE_FLAG_DEBUG:
626 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000627
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000628 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
629 # the VERBOSE flag was switched on inside the pattern. to be
630 # on the safe side, we'll parse the whole thing again...
631 return parse(str, p.pattern.flags)
632
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000633 return p
634
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000635def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000636 # parse 're' replacement string into list of literals and
637 # group references
638 s = Tokenizer(source)
639 p = []
640 a = p.append
641 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000642 this = s.get()
643 if this is None:
644 break # end of replacement string
645 if this and this[0] == "\\":
646 # group
647 if this == "\\g":
648 name = ""
649 if s.match("<"):
650 while 1:
651 char = s.get()
652 if char is None:
653 raise error, "unterminated group name"
654 if char == ">":
655 break
656 name = name + char
657 if not name:
658 raise error, "bad group name"
659 try:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000660 index = atoi(name)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000661 except ValueError:
662 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000663 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000664 try:
665 index = pattern.groupindex[name]
666 except KeyError:
667 raise IndexError, "unknown group name"
668 a((MARK, index))
669 elif len(this) > 1 and this[1] in DIGITS:
670 code = None
671 while 1:
672 group = _group(this, pattern.groups+1)
673 if group:
Fredrik Lundh19f977b2000-09-24 14:46:23 +0000674 if (s.next not in DIGITS or
Fredrik Lundh90a07912000-06-30 07:50:59 +0000675 not _group(this + s.next, pattern.groups+1)):
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000676 code = MARK, group
Fredrik Lundh90a07912000-06-30 07:50:59 +0000677 break
678 elif s.next in OCTDIGITS:
679 this = this + s.get()
680 else:
681 break
682 if not code:
683 this = this[1:]
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000684 code = LITERAL, atoi(this[-6:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000685 a(code)
686 else:
687 try:
688 a(ESCAPES[this])
689 except KeyError:
690 for c in this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000691 a((LITERAL, ord(c)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000692 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000693 a((LITERAL, ord(this)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000694 return p
695
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000696def expand_template(template, match):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000697 # XXX: <fl> this is sooooo slow. drop in the slicelist code instead
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000698 p = []
699 a = p.append
Fredrik Lundh0640e112000-06-30 13:55:15 +0000700 sep = match.string[:0]
701 if type(sep) is type(""):
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000702 char = chr
Fredrik Lundh0640e112000-06-30 13:55:15 +0000703 else:
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000704 char = unichr
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000705 for c, s in template:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000706 if c is LITERAL:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000707 a(char(s))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000708 elif c is MARK:
709 s = match.group(s)
710 if s is None:
711 raise error, "empty group"
712 a(s)
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000713 return string.join(p, sep)