blob: 36036b6ecbee122cf83539505ed7c382ec30a5ab [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
449 elif this == "+":
450 min, max = 1, MAXREPEAT
451 elif this == "{":
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000452 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000453 min, max = 0, MAXREPEAT
454 lo = hi = ""
455 while source.next in DIGITS:
456 lo = lo + source.get()
457 if source.match(","):
458 while source.next in DIGITS:
459 hi = hi + source.get()
460 else:
461 hi = lo
462 if not source.match("}"):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000463 subpattern.append((LITERAL, ord(this)))
464 source.seek(here)
465 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000466 if lo:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000467 min = atoi(lo)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000468 if hi:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000469 max = atoi(hi)
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000470 if max < min:
471 raise error, "bad repeat interval"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000472 else:
473 raise error, "not supported"
474 # figure out which item to repeat
475 if subpattern:
476 item = subpattern[-1:]
477 else:
478 raise error, "nothing to repeat"
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000479 if item[0][0] in (MIN_REPEAT, MAX_REPEAT):
480 raise error, "multiple repeat"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000481 if source.match("?"):
482 subpattern[-1] = (MIN_REPEAT, (min, max, item))
483 else:
484 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000485
Fredrik Lundh90a07912000-06-30 07:50:59 +0000486 elif this == ".":
487 subpattern.append((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000488
Fredrik Lundh90a07912000-06-30 07:50:59 +0000489 elif this == "(":
490 group = 1
491 name = None
492 if source.match("?"):
493 group = 0
494 # options
495 if source.match("P"):
496 # python extensions
497 if source.match("<"):
498 # named group: skip forward to end of name
499 name = ""
500 while 1:
501 char = source.get()
502 if char is None:
503 raise error, "unterminated name"
504 if char == ">":
505 break
506 name = name + char
507 group = 1
508 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000509 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000510 elif source.match("="):
511 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000512 name = ""
513 while 1:
514 char = source.get()
515 if char is None:
516 raise error, "unterminated name"
517 if char == ")":
518 break
519 name = name + char
520 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000521 raise error, "bad character in group name"
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000522 gid = state.groupdict.get(name)
523 if gid is None:
524 raise error, "unknown group name"
Fredrik Lundh72b82ba2000-07-03 21:31:48 +0000525 subpattern.append((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000526 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000527 else:
528 char = source.get()
529 if char is None:
530 raise error, "unexpected end of pattern"
531 raise error, "unknown specifier: ?P%s" % char
532 elif source.match(":"):
533 # non-capturing group
534 group = 2
535 elif source.match("#"):
536 # comment
537 while 1:
538 if source.next is None or source.next == ")":
539 break
540 source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000541 if not source.match(")"):
542 raise error, "unbalanced parenthesis"
543 continue
Fredrik Lundh6f013982000-07-03 18:44:21 +0000544 elif source.next in ("=", "!", "<"):
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000545 # lookahead assertions
546 char = source.get()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000547 dir = 1
548 if char == "<":
549 if source.next not in ("=", "!"):
550 raise error, "syntax error"
551 dir = -1 # lookbehind
552 char = source.get()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000553 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000554 if not source.match(")"):
555 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000556 if char == "=":
557 subpattern.append((ASSERT, (dir, p)))
558 else:
559 subpattern.append((ASSERT_NOT, (dir, p)))
560 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000561 else:
562 # flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000563 if not FLAGS.has_key(source.next):
564 raise error, "unexpected end of pattern"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000565 while FLAGS.has_key(source.next):
566 state.flags = state.flags | FLAGS[source.get()]
567 if group:
568 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000569 if group == 2:
570 # anonymous group
571 group = None
572 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000573 group = state.opengroup(name)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000574 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000575 if not source.match(")"):
576 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000577 if group is not None:
578 state.closegroup(group)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000579 subpattern.append((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000580 else:
581 while 1:
582 char = source.get()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000583 if char is None:
584 raise error, "unexpected end of pattern"
585 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000586 break
587 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000588
Fredrik Lundh90a07912000-06-30 07:50:59 +0000589 elif this == "^":
590 subpattern.append((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000591
Fredrik Lundh90a07912000-06-30 07:50:59 +0000592 elif this == "$":
593 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000594
Fredrik Lundh90a07912000-06-30 07:50:59 +0000595 elif this and this[0] == "\\":
596 code = _escape(source, this, state)
597 subpattern.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000598
Fredrik Lundh90a07912000-06-30 07:50:59 +0000599 else:
600 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000601
602 return subpattern
603
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000604def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000605 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000606
607 source = Tokenizer(str)
608
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000609 if pattern is None:
610 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000611 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000612 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000613
614 p = _parse_sub(source, pattern, 0)
615
616 tail = source.get()
617 if tail == ")":
618 raise error, "unbalanced parenthesis"
619 elif tail:
620 raise error, "bogus characters at end of regular expression"
621
Fredrik Lundh770617b2001-01-14 15:06:11 +0000622 if flags & SRE_FLAG_DEBUG:
623 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000624
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000625 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
626 # the VERBOSE flag was switched on inside the pattern. to be
627 # on the safe side, we'll parse the whole thing again...
628 return parse(str, p.pattern.flags)
629
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000630 return p
631
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000632def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000633 # parse 're' replacement string into list of literals and
634 # group references
635 s = Tokenizer(source)
636 p = []
637 a = p.append
638 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000639 this = s.get()
640 if this is None:
641 break # end of replacement string
642 if this and this[0] == "\\":
643 # group
644 if this == "\\g":
645 name = ""
646 if s.match("<"):
647 while 1:
648 char = s.get()
649 if char is None:
650 raise error, "unterminated group name"
651 if char == ">":
652 break
653 name = name + char
654 if not name:
655 raise error, "bad group name"
656 try:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000657 index = atoi(name)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000658 except ValueError:
659 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000660 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000661 try:
662 index = pattern.groupindex[name]
663 except KeyError:
664 raise IndexError, "unknown group name"
665 a((MARK, index))
666 elif len(this) > 1 and this[1] in DIGITS:
667 code = None
668 while 1:
669 group = _group(this, pattern.groups+1)
670 if group:
Fredrik Lundh19f977b2000-09-24 14:46:23 +0000671 if (s.next not in DIGITS or
Fredrik Lundh90a07912000-06-30 07:50:59 +0000672 not _group(this + s.next, pattern.groups+1)):
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000673 code = MARK, group
Fredrik Lundh90a07912000-06-30 07:50:59 +0000674 break
675 elif s.next in OCTDIGITS:
676 this = this + s.get()
677 else:
678 break
679 if not code:
680 this = this[1:]
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000681 code = LITERAL, atoi(this[-6:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000682 a(code)
683 else:
684 try:
685 a(ESCAPES[this])
686 except KeyError:
687 for c in this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000688 a((LITERAL, ord(c)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000689 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000690 a((LITERAL, ord(this)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000691 return p
692
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000693def expand_template(template, match):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000694 # XXX: <fl> this is sooooo slow. drop in the slicelist code instead
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000695 p = []
696 a = p.append
Fredrik Lundh0640e112000-06-30 13:55:15 +0000697 sep = match.string[:0]
698 if type(sep) is type(""):
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000699 char = chr
Fredrik Lundh0640e112000-06-30 13:55:15 +0000700 else:
Fredrik Lundh4ccea942000-06-30 18:39:20 +0000701 char = unichr
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000702 for c, s in template:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000703 if c is LITERAL:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000704 a(char(s))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000705 elif c is MARK:
706 s = match.group(s)
707 if s is None:
708 raise error, "empty group"
709 a(s)
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000710 return string.join(p, sep)