blob: 4596f3b458ca7ac2f708dddc163ae4abb60ccfb7 [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
Fred Drakeb8f22742001-09-04 19:10:20 +000011"""Internal support module for sre"""
12
Fredrik Lundh470ea5a2001-01-14 21:00:44 +000013# XXX: show string offset and offending character for all errors
14
Fredrik Lundhf2989b22001-02-18 12:05:16 +000015# this module works under 1.5.2 and later. don't use string methods
16import string, sys
Guido van Rossum7627c0d2000-03-31 14:58:54 +000017
18from sre_constants import *
19
20SPECIAL_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 Lundhf2989b22001-02-18 12:05:16 +000031 r"\a": (LITERAL, ord("\a")),
32 r"\b": (LITERAL, ord("\b")),
33 r"\f": (LITERAL, ord("\f")),
34 r"\n": (LITERAL, ord("\n")),
35 r"\r": (LITERAL, ord("\r")),
36 r"\t": (LITERAL, ord("\t")),
37 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000038 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 Lundhf2989b22001-02-18 12:05:16 +000066# figure out best way to convert hex/octal numbers to integers
67try:
68 int("10", 8)
69 atoi = int # 2.0 and later
70except TypeError:
71 atoi = string.atoi # 1.5.2
72
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000073class Pattern:
74 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000075 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000076 self.flags = 0
Fredrik Lundhebc37b22000-10-28 19:30:41 +000077 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000078 self.groups = 1
79 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000080 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000081 gid = self.groups
82 self.groups = gid + 1
83 if name:
Fredrik Lundh8a0232d2001-11-02 13:59:51 +000084 if self.groupdict.has_key(name):
85 raise error, "can only use each group name once"
Fredrik Lundh90a07912000-06-30 07:50:59 +000086 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000087 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000088 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000089 def closegroup(self, gid):
90 self.open.remove(gid)
91 def checkgroup(self, gid):
92 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000093
94class SubPattern:
95 # a subpattern, in intermediate form
96 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000097 self.pattern = pattern
98 if not data:
99 data = []
100 self.data = data
101 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000102 def dump(self, level=0):
103 nl = 1
104 for op, av in self.data:
105 print level*" " + op,; nl = 0
106 if op == "in":
107 # member sublanguage
108 print; nl = 1
109 for op, a in av:
110 print (level+1)*" " + op, a
111 elif op == "branch":
112 print; nl = 1
113 i = 0
114 for a in av[1]:
115 if i > 0:
116 print level*" " + "or"
117 a.dump(level+1); nl = 1
118 i = i + 1
119 elif type(av) in (type(()), type([])):
120 for a in av:
121 if isinstance(a, SubPattern):
122 if not nl: print
123 a.dump(level+1); nl = 1
124 else:
125 print a, ; nl = 0
126 else:
127 print av, ; nl = 0
128 if not nl: print
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000129 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000130 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000131 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000132 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000133 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000134 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000135 def __getitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000136 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000137 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000138 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000139 def __getslice__(self, start, stop):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000140 return SubPattern(self.pattern, self.data[start:stop])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000141 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000142 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000143 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000144 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000145 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000146 # determine the width (min, max) for this subpattern
147 if self.width:
148 return self.width
149 lo = hi = 0L
150 for op, av in self.data:
151 if op is BRANCH:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000152 i = sys.maxint
153 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000154 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000155 l, h = av.getwidth()
156 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000157 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000158 lo = lo + i
159 hi = hi + j
160 elif op is CALL:
161 i, j = av.getwidth()
162 lo = lo + i
163 hi = hi + j
164 elif op is SUBPATTERN:
165 i, j = av[1].getwidth()
166 lo = lo + i
167 hi = hi + j
168 elif op in (MIN_REPEAT, MAX_REPEAT):
169 i, j = av[2].getwidth()
170 lo = lo + long(i) * av[0]
171 hi = hi + long(j) * av[1]
172 elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY):
173 lo = lo + 1
174 hi = hi + 1
175 elif op == SUCCESS:
176 break
177 self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint))
178 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000179
180class Tokenizer:
181 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000182 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000183 self.index = 0
184 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000185 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000186 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000187 self.next = None
188 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000189 char = self.string[self.index]
190 if char[0] == "\\":
191 try:
192 c = self.string[self.index + 1]
193 except IndexError:
Fredrik Lundh8a0232d2001-11-02 13:59:51 +0000194 raise error, "bogus escape (end of line)"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000195 char = char + c
196 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000197 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000198 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000199 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000200 if skip:
201 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000202 return 1
203 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000204 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000205 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000206 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000207 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000208 def tell(self):
209 return self.index, self.next
210 def seek(self, index):
211 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000212
Fredrik Lundh4781b072000-06-29 12:38:45 +0000213def isident(char):
214 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
215
216def isdigit(char):
217 return "0" <= char <= "9"
218
219def isname(name):
220 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000221 if not isident(name[0]):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000222 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000223 for char in name:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000224 if not isident(char) and not isdigit(char):
225 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000226 return 1
227
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000228def _group(escape, groups):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000229 # check if the escape string represents a valid group
230 try:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000231 gid = atoi(escape[1:])
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000232 if gid and gid < groups:
233 return gid
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000234 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000235 pass
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000236 return None # not a valid group
237
238def _class_escape(source, escape):
239 # handle escape code inside character class
240 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000241 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000242 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000243 code = CATEGORIES.get(escape)
244 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000245 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000246 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000247 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000248 # hexadecimal escape (exactly two digits)
249 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000250 escape = escape + source.get()
251 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000252 if len(escape) != 2:
253 raise error, "bogus escape: %s" % repr("\\" + escape)
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000254 return LITERAL, atoi(escape, 16) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000255 elif str(escape[1:2]) in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000256 # octal escape (up to three digits)
257 while source.next in OCTDIGITS and len(escape) < 5:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000258 escape = escape + source.get()
259 escape = escape[1:]
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000260 return LITERAL, atoi(escape, 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000261 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000262 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000263 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000264 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000265 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000266
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000267def _escape(source, escape, state):
268 # handle escape code in expression
269 code = CATEGORIES.get(escape)
270 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000271 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000272 code = ESCAPES.get(escape)
273 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000274 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000275 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000276 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000277 # hexadecimal escape
278 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000279 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000280 if len(escape) != 4:
281 raise ValueError
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000282 return LITERAL, atoi(escape[2:], 16) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000283 elif escape[1:2] == "0":
284 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000285 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000286 escape = escape + source.get()
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000287 return LITERAL, atoi(escape[1:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000288 elif escape[1:2] in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000289 # octal escape *or* decimal group reference (sigh)
290 here = source.tell()
291 if source.next in DIGITS:
292 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000293 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
294 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000295 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000296 escape = escape + source.get()
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000297 return LITERAL, atoi(escape[1:], 8) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000298 # got at least one decimal digit; this is a group reference
299 group = _group(escape, state.groups)
300 if group:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000301 if not state.checkgroup(group):
302 raise error, "cannot refer to open group"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000303 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000304 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000305 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000306 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000307 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000308 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000309 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000310
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000311def _parse_sub(source, state, nested=1):
312 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000313
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000314 items = []
315 while 1:
316 items.append(_parse(source, state))
317 if source.match("|"):
318 continue
319 if not nested:
320 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000321 if not source.next or source.match(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000322 break
323 else:
324 raise error, "pattern not properly closed"
325
326 if len(items) == 1:
327 return items[0]
328
329 subpattern = SubPattern(state)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000330
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000331 # check if all items share a common prefix
332 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000333 prefix = None
334 for item in items:
335 if not item:
336 break
337 if prefix is None:
338 prefix = item[0]
339 elif item[0] != prefix:
340 break
341 else:
342 # all subitems start with a common "prefix".
343 # move it out of the branch
344 for item in items:
345 del item[0]
346 subpattern.append(prefix)
347 continue # check next one
348 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000349
350 # check if the branch can be replaced by a character set
351 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000352 if len(item) != 1 or item[0][0] != LITERAL:
353 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000354 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000355 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000356 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000357 set = []
358 for item in items:
359 set.append(item[0])
360 subpattern.append((IN, set))
361 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000362
363 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000364 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000365
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000366def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000367 # parse a simple pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000368
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000369 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000370
371 while 1:
372
Fredrik Lundh90a07912000-06-30 07:50:59 +0000373 if source.next in ("|", ")"):
374 break # end of subpattern
375 this = source.get()
376 if this is None:
377 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000378
Fredrik Lundh90a07912000-06-30 07:50:59 +0000379 if state.flags & SRE_FLAG_VERBOSE:
380 # skip whitespace and comments
381 if this in WHITESPACE:
382 continue
383 if this == "#":
384 while 1:
385 this = source.get()
386 if this in (None, "\n"):
387 break
388 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000389
Fredrik Lundh90a07912000-06-30 07:50:59 +0000390 if this and this[0] not in SPECIAL_CHARS:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000391 subpattern.append((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000392
Fredrik Lundh90a07912000-06-30 07:50:59 +0000393 elif this == "[":
394 # character set
395 set = []
396## if source.match(":"):
397## pass # handle character classes
398 if source.match("^"):
399 set.append((NEGATE, None))
400 # check remaining characters
401 start = set[:]
402 while 1:
403 this = source.get()
404 if this == "]" and set != start:
405 break
406 elif this and this[0] == "\\":
407 code1 = _class_escape(source, this)
408 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000409 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000410 else:
411 raise error, "unexpected end of regular expression"
412 if source.match("-"):
413 # potential range
414 this = source.get()
415 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000416 if code1[0] is IN:
417 code1 = code1[1][0]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000418 set.append(code1)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000419 set.append((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000420 break
421 else:
422 if this[0] == "\\":
423 code2 = _class_escape(source, this)
424 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000425 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000426 if code1[0] != LITERAL or code2[0] != LITERAL:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000427 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000428 lo = code1[1]
429 hi = code2[1]
430 if hi < lo:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000431 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000432 set.append((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000433 else:
434 if code1[0] is IN:
435 code1 = code1[1][0]
436 set.append(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000437
Fredrik Lundh770617b2001-01-14 15:06:11 +0000438 # XXX: <fl> should move set optimization to compiler!
Fredrik Lundh90a07912000-06-30 07:50:59 +0000439 if len(set)==1 and set[0][0] is LITERAL:
440 subpattern.append(set[0]) # optimization
441 elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
442 subpattern.append((NOT_LITERAL, set[1][1])) # optimization
443 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000444 # XXX: <fl> should add charmap optimization here
Fredrik Lundh90a07912000-06-30 07:50:59 +0000445 subpattern.append((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000446
Fredrik Lundh90a07912000-06-30 07:50:59 +0000447 elif this and this[0] in REPEAT_CHARS:
448 # repeat previous item
449 if this == "?":
450 min, max = 0, 1
451 elif this == "*":
452 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000453
Fredrik Lundh90a07912000-06-30 07:50:59 +0000454 elif this == "+":
455 min, max = 1, MAXREPEAT
456 elif this == "{":
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000457 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000458 min, max = 0, MAXREPEAT
459 lo = hi = ""
460 while source.next in DIGITS:
461 lo = lo + source.get()
462 if source.match(","):
463 while source.next in DIGITS:
464 hi = hi + source.get()
465 else:
466 hi = lo
467 if not source.match("}"):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000468 subpattern.append((LITERAL, ord(this)))
469 source.seek(here)
470 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000471 if lo:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000472 min = atoi(lo)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000473 if hi:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000474 max = atoi(hi)
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000475 if max < min:
476 raise error, "bad repeat interval"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000477 else:
478 raise error, "not supported"
479 # figure out which item to repeat
480 if subpattern:
481 item = subpattern[-1:]
482 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000483 item = None
484 if not item or (len(item) == 1 and item[0][0] == AT):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000485 raise error, "nothing to repeat"
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000486 if item[0][0] in (MIN_REPEAT, MAX_REPEAT):
487 raise error, "multiple repeat"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000488 if source.match("?"):
489 subpattern[-1] = (MIN_REPEAT, (min, max, item))
490 else:
491 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000492
Fredrik Lundh90a07912000-06-30 07:50:59 +0000493 elif this == ".":
494 subpattern.append((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000495
Fredrik Lundh90a07912000-06-30 07:50:59 +0000496 elif this == "(":
497 group = 1
498 name = None
499 if source.match("?"):
500 group = 0
501 # options
502 if source.match("P"):
503 # python extensions
504 if source.match("<"):
505 # named group: skip forward to end of name
506 name = ""
507 while 1:
508 char = source.get()
509 if char is None:
510 raise error, "unterminated name"
511 if char == ">":
512 break
513 name = name + char
514 group = 1
515 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000516 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000517 elif source.match("="):
518 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000519 name = ""
520 while 1:
521 char = source.get()
522 if char is None:
523 raise error, "unterminated name"
524 if char == ")":
525 break
526 name = name + char
527 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000528 raise error, "bad character in group name"
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000529 gid = state.groupdict.get(name)
530 if gid is None:
531 raise error, "unknown group name"
Fredrik Lundh72b82ba2000-07-03 21:31:48 +0000532 subpattern.append((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000533 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000534 else:
535 char = source.get()
536 if char is None:
537 raise error, "unexpected end of pattern"
538 raise error, "unknown specifier: ?P%s" % char
539 elif source.match(":"):
540 # non-capturing group
541 group = 2
542 elif source.match("#"):
543 # comment
544 while 1:
545 if source.next is None or source.next == ")":
546 break
547 source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000548 if not source.match(")"):
549 raise error, "unbalanced parenthesis"
550 continue
Fredrik Lundh6f013982000-07-03 18:44:21 +0000551 elif source.next in ("=", "!", "<"):
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000552 # lookahead assertions
553 char = source.get()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000554 dir = 1
555 if char == "<":
556 if source.next not in ("=", "!"):
557 raise error, "syntax error"
558 dir = -1 # lookbehind
559 char = source.get()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000560 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000561 if not source.match(")"):
562 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000563 if char == "=":
564 subpattern.append((ASSERT, (dir, p)))
565 else:
566 subpattern.append((ASSERT_NOT, (dir, p)))
567 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000568 else:
569 # flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000570 if not FLAGS.has_key(source.next):
571 raise error, "unexpected end of pattern"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000572 while FLAGS.has_key(source.next):
573 state.flags = state.flags | FLAGS[source.get()]
574 if group:
575 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000576 if group == 2:
577 # anonymous group
578 group = None
579 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000580 group = state.opengroup(name)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000581 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000582 if not source.match(")"):
583 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000584 if group is not None:
585 state.closegroup(group)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000586 subpattern.append((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000587 else:
588 while 1:
589 char = source.get()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000590 if char is None:
591 raise error, "unexpected end of pattern"
592 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000593 break
594 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000595
Fredrik Lundh90a07912000-06-30 07:50:59 +0000596 elif this == "^":
597 subpattern.append((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000598
Fredrik Lundh90a07912000-06-30 07:50:59 +0000599 elif this == "$":
600 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000601
Fredrik Lundh90a07912000-06-30 07:50:59 +0000602 elif this and this[0] == "\\":
603 code = _escape(source, this, state)
604 subpattern.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000605
Fredrik Lundh90a07912000-06-30 07:50:59 +0000606 else:
607 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000608
609 return subpattern
610
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000611def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000612 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000613
614 source = Tokenizer(str)
615
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000616 if pattern is None:
617 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000618 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000619 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000620
621 p = _parse_sub(source, pattern, 0)
622
623 tail = source.get()
624 if tail == ")":
625 raise error, "unbalanced parenthesis"
626 elif tail:
627 raise error, "bogus characters at end of regular expression"
628
Fredrik Lundh770617b2001-01-14 15:06:11 +0000629 if flags & SRE_FLAG_DEBUG:
630 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000631
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000632 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
633 # the VERBOSE flag was switched on inside the pattern. to be
634 # on the safe side, we'll parse the whole thing again...
635 return parse(str, p.pattern.flags)
636
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000637 return p
638
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000639def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000640 # parse 're' replacement string into list of literals and
641 # group references
642 s = Tokenizer(source)
643 p = []
644 a = p.append
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000645 def literal(literal, p=p):
646 if p and p[-1][0] is LITERAL:
647 p[-1] = LITERAL, p[-1][1] + literal
648 else:
649 p.append((LITERAL, literal))
650 sep = source[:0]
651 if type(sep) is type(""):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000652 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000653 else:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000654 makechar = unichr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000655 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000656 this = s.get()
657 if this is None:
658 break # end of replacement string
659 if this and this[0] == "\\":
660 # group
661 if this == "\\g":
662 name = ""
663 if s.match("<"):
664 while 1:
665 char = s.get()
666 if char is None:
667 raise error, "unterminated group name"
668 if char == ">":
669 break
670 name = name + char
671 if not name:
672 raise error, "bad group name"
673 try:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000674 index = atoi(name)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000675 except ValueError:
676 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000677 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000678 try:
679 index = pattern.groupindex[name]
680 except KeyError:
681 raise IndexError, "unknown group name"
682 a((MARK, index))
683 elif len(this) > 1 and this[1] in DIGITS:
684 code = None
685 while 1:
686 group = _group(this, pattern.groups+1)
687 if group:
Fredrik Lundh19f977b2000-09-24 14:46:23 +0000688 if (s.next not in DIGITS or
Fredrik Lundh90a07912000-06-30 07:50:59 +0000689 not _group(this + s.next, pattern.groups+1)):
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000690 code = MARK, group
Fredrik Lundh90a07912000-06-30 07:50:59 +0000691 break
692 elif s.next in OCTDIGITS:
693 this = this + s.get()
694 else:
695 break
696 if not code:
697 this = this[1:]
Fredrik Lundh59b68652001-09-18 20:55:24 +0000698 code = LITERAL, makechar(atoi(this[-6:], 8) & 0xff)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000699 if code[0] is LITERAL:
700 literal(code[1])
701 else:
702 a(code)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000703 else:
704 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000705 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000706 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000707 pass
708 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000709 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000710 literal(this)
711 # convert template to groups and literals lists
712 i = 0
713 groups = []
714 literals = []
715 for c, s in p:
716 if c is MARK:
717 groups.append((i, s))
718 literals.append(None)
719 else:
720 literals.append(s)
721 i = i + 1
722 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000723
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000724def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000725 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000726 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000727 groups, literals = template
728 literals = literals[:]
729 try:
730 for index, group in groups:
731 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000732 if s is None:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000733 raise IndexError
734 except IndexError:
735 raise error, "empty group"
736 return string.join(literals, sep)