blob: 7d9b8899bc6406aa85c983ac7fa3542bebd52a08 [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:
84 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000085 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000086 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000087 def closegroup(self, gid):
88 self.open.remove(gid)
89 def checkgroup(self, gid):
90 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000091
92class SubPattern:
93 # a subpattern, in intermediate form
94 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000095 self.pattern = pattern
96 if not data:
97 data = []
98 self.data = data
99 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000100 def dump(self, level=0):
101 nl = 1
102 for op, av in self.data:
103 print level*" " + op,; nl = 0
104 if op == "in":
105 # member sublanguage
106 print; nl = 1
107 for op, a in av:
108 print (level+1)*" " + op, a
109 elif op == "branch":
110 print; nl = 1
111 i = 0
112 for a in av[1]:
113 if i > 0:
114 print level*" " + "or"
115 a.dump(level+1); nl = 1
116 i = i + 1
117 elif type(av) in (type(()), type([])):
118 for a in av:
119 if isinstance(a, SubPattern):
120 if not nl: print
121 a.dump(level+1); nl = 1
122 else:
123 print a, ; nl = 0
124 else:
125 print av, ; nl = 0
126 if not nl: print
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000127 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000128 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000129 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000130 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000131 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000132 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000133 def __getitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000134 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000135 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000136 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000137 def __getslice__(self, start, stop):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000138 return SubPattern(self.pattern, self.data[start:stop])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000139 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000140 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000141 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000142 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000143 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000144 # determine the width (min, max) for this subpattern
145 if self.width:
146 return self.width
147 lo = hi = 0L
148 for op, av in self.data:
149 if op is BRANCH:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000150 i = sys.maxint
151 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000152 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000153 l, h = av.getwidth()
154 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000155 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000156 lo = lo + i
157 hi = hi + j
158 elif op is CALL:
159 i, j = av.getwidth()
160 lo = lo + i
161 hi = hi + j
162 elif op is SUBPATTERN:
163 i, j = av[1].getwidth()
164 lo = lo + i
165 hi = hi + j
166 elif op in (MIN_REPEAT, MAX_REPEAT):
167 i, j = av[2].getwidth()
168 lo = lo + long(i) * av[0]
169 hi = hi + long(j) * av[1]
170 elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY):
171 lo = lo + 1
172 hi = hi + 1
173 elif op == SUCCESS:
174 break
175 self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint))
176 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000177
178class Tokenizer:
179 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000180 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000181 self.index = 0
182 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000183 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000184 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000185 self.next = None
186 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000187 char = self.string[self.index]
188 if char[0] == "\\":
189 try:
190 c = self.string[self.index + 1]
191 except IndexError:
192 raise error, "bogus escape"
193 char = char + c
194 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000195 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000196 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000197 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000198 if skip:
199 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000200 return 1
201 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000202 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000203 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000204 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000205 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000206 def tell(self):
207 return self.index, self.next
208 def seek(self, index):
209 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000210
Fredrik Lundh4781b072000-06-29 12:38:45 +0000211def isident(char):
212 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
213
214def isdigit(char):
215 return "0" <= char <= "9"
216
217def isname(name):
218 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000219 if not isident(name[0]):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000220 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000221 for char in name:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000222 if not isident(char) and not isdigit(char):
223 return 0
Fredrik Lundh4781b072000-06-29 12:38:45 +0000224 return 1
225
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000226def _group(escape, groups):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000227 # check if the escape string represents a valid group
228 try:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000229 gid = atoi(escape[1:])
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000230 if gid and gid < groups:
231 return gid
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000232 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000233 pass
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000234 return None # not a valid group
235
236def _class_escape(source, escape):
237 # handle escape code inside character class
238 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000239 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000240 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000241 code = CATEGORIES.get(escape)
242 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000243 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000244 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000245 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000246 # hexadecimal escape (exactly two digits)
247 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000248 escape = escape + source.get()
249 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000250 if len(escape) != 2:
251 raise error, "bogus escape: %s" % repr("\\" + escape)
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000252 return LITERAL, atoi(escape, 16) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000253 elif str(escape[1:2]) in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000254 # octal escape (up to three digits)
255 while source.next in OCTDIGITS and len(escape) < 5:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000256 escape = escape + source.get()
257 escape = escape[1:]
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000258 return LITERAL, atoi(escape, 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000259 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000260 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000261 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000262 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000263 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000264
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000265def _escape(source, escape, state):
266 # handle escape code in expression
267 code = CATEGORIES.get(escape)
268 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000269 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000270 code = ESCAPES.get(escape)
271 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000272 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000273 try:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000274 if escape[1:2] == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000275 # hexadecimal escape
276 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000277 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000278 if len(escape) != 4:
279 raise ValueError
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000280 return LITERAL, atoi(escape[2:], 16) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000281 elif escape[1:2] == "0":
282 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000283 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000284 escape = escape + source.get()
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000285 return LITERAL, atoi(escape[1:], 8) & 0xff
Fredrik Lundh90a07912000-06-30 07:50:59 +0000286 elif escape[1:2] in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000287 # octal escape *or* decimal group reference (sigh)
288 here = source.tell()
289 if source.next in DIGITS:
290 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000291 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
292 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000293 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000294 escape = escape + source.get()
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000295 return LITERAL, atoi(escape[1:], 8) & 0xff
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000296 # got at least one decimal digit; this is a group reference
297 group = _group(escape, state.groups)
298 if group:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000299 if not state.checkgroup(group):
300 raise error, "cannot refer to open group"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000301 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000302 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000303 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000304 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000305 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000306 pass
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000307 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000308
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000309def _parse_sub(source, state, nested=1):
310 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000311
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000312 items = []
313 while 1:
314 items.append(_parse(source, state))
315 if source.match("|"):
316 continue
317 if not nested:
318 break
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000319 if not source.next or source.match(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000320 break
321 else:
322 raise error, "pattern not properly closed"
323
324 if len(items) == 1:
325 return items[0]
326
327 subpattern = SubPattern(state)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000328
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000329 # check if all items share a common prefix
330 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000331 prefix = None
332 for item in items:
333 if not item:
334 break
335 if prefix is None:
336 prefix = item[0]
337 elif item[0] != prefix:
338 break
339 else:
340 # all subitems start with a common "prefix".
341 # move it out of the branch
342 for item in items:
343 del item[0]
344 subpattern.append(prefix)
345 continue # check next one
346 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000347
348 # check if the branch can be replaced by a character set
349 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000350 if len(item) != 1 or item[0][0] != LITERAL:
351 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000352 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000353 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000354 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000355 set = []
356 for item in items:
357 set.append(item[0])
358 subpattern.append((IN, set))
359 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000360
361 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000362 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000363
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000364def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000365 # parse a simple pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000366
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000367 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000368
369 while 1:
370
Fredrik Lundh90a07912000-06-30 07:50:59 +0000371 if source.next in ("|", ")"):
372 break # end of subpattern
373 this = source.get()
374 if this is None:
375 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000376
Fredrik Lundh90a07912000-06-30 07:50:59 +0000377 if state.flags & SRE_FLAG_VERBOSE:
378 # skip whitespace and comments
379 if this in WHITESPACE:
380 continue
381 if this == "#":
382 while 1:
383 this = source.get()
384 if this in (None, "\n"):
385 break
386 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000387
Fredrik Lundh90a07912000-06-30 07:50:59 +0000388 if this and this[0] not in SPECIAL_CHARS:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000389 subpattern.append((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000390
Fredrik Lundh90a07912000-06-30 07:50:59 +0000391 elif this == "[":
392 # character set
393 set = []
394## if source.match(":"):
395## pass # handle character classes
396 if source.match("^"):
397 set.append((NEGATE, None))
398 # check remaining characters
399 start = set[:]
400 while 1:
401 this = source.get()
402 if this == "]" and set != start:
403 break
404 elif this and this[0] == "\\":
405 code1 = _class_escape(source, this)
406 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000407 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000408 else:
409 raise error, "unexpected end of regular expression"
410 if source.match("-"):
411 # potential range
412 this = source.get()
413 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000414 if code1[0] is IN:
415 code1 = code1[1][0]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000416 set.append(code1)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000417 set.append((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000418 break
419 else:
420 if this[0] == "\\":
421 code2 = _class_escape(source, this)
422 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000423 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000424 if code1[0] != LITERAL or code2[0] != LITERAL:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000425 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000426 lo = code1[1]
427 hi = code2[1]
428 if hi < lo:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000429 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000430 set.append((RANGE, (lo, hi)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000431 else:
432 if code1[0] is IN:
433 code1 = code1[1][0]
434 set.append(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000435
Fredrik Lundh770617b2001-01-14 15:06:11 +0000436 # XXX: <fl> should move set optimization to compiler!
Fredrik Lundh90a07912000-06-30 07:50:59 +0000437 if len(set)==1 and set[0][0] is LITERAL:
438 subpattern.append(set[0]) # optimization
439 elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
440 subpattern.append((NOT_LITERAL, set[1][1])) # optimization
441 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000442 # XXX: <fl> should add charmap optimization here
Fredrik Lundh90a07912000-06-30 07:50:59 +0000443 subpattern.append((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000444
Fredrik Lundh90a07912000-06-30 07:50:59 +0000445 elif this and this[0] in REPEAT_CHARS:
446 # repeat previous item
447 if this == "?":
448 min, max = 0, 1
449 elif this == "*":
450 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000451
Fredrik Lundh90a07912000-06-30 07:50:59 +0000452 elif this == "+":
453 min, max = 1, MAXREPEAT
454 elif this == "{":
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000455 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000456 min, max = 0, MAXREPEAT
457 lo = hi = ""
458 while source.next in DIGITS:
459 lo = lo + source.get()
460 if source.match(","):
461 while source.next in DIGITS:
462 hi = hi + source.get()
463 else:
464 hi = lo
465 if not source.match("}"):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000466 subpattern.append((LITERAL, ord(this)))
467 source.seek(here)
468 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000469 if lo:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000470 min = atoi(lo)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000471 if hi:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000472 max = atoi(hi)
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000473 if max < min:
474 raise error, "bad repeat interval"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000475 else:
476 raise error, "not supported"
477 # figure out which item to repeat
478 if subpattern:
479 item = subpattern[-1:]
480 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000481 item = None
482 if not item or (len(item) == 1 and item[0][0] == AT):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000483 raise error, "nothing to repeat"
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000484 if item[0][0] in (MIN_REPEAT, MAX_REPEAT):
485 raise error, "multiple repeat"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000486 if source.match("?"):
487 subpattern[-1] = (MIN_REPEAT, (min, max, item))
488 else:
489 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000490
Fredrik Lundh90a07912000-06-30 07:50:59 +0000491 elif this == ".":
492 subpattern.append((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000493
Fredrik Lundh90a07912000-06-30 07:50:59 +0000494 elif this == "(":
495 group = 1
496 name = None
497 if source.match("?"):
498 group = 0
499 # options
500 if source.match("P"):
501 # python extensions
502 if source.match("<"):
503 # named group: skip forward to end of name
504 name = ""
505 while 1:
506 char = source.get()
507 if char is None:
508 raise error, "unterminated name"
509 if char == ">":
510 break
511 name = name + char
512 group = 1
513 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000514 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000515 elif source.match("="):
516 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000517 name = ""
518 while 1:
519 char = source.get()
520 if char is None:
521 raise error, "unterminated name"
522 if char == ")":
523 break
524 name = name + char
525 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000526 raise error, "bad character in group name"
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000527 gid = state.groupdict.get(name)
528 if gid is None:
529 raise error, "unknown group name"
Fredrik Lundh72b82ba2000-07-03 21:31:48 +0000530 subpattern.append((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000531 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000532 else:
533 char = source.get()
534 if char is None:
535 raise error, "unexpected end of pattern"
536 raise error, "unknown specifier: ?P%s" % char
537 elif source.match(":"):
538 # non-capturing group
539 group = 2
540 elif source.match("#"):
541 # comment
542 while 1:
543 if source.next is None or source.next == ")":
544 break
545 source.get()
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000546 if not source.match(")"):
547 raise error, "unbalanced parenthesis"
548 continue
Fredrik Lundh6f013982000-07-03 18:44:21 +0000549 elif source.next in ("=", "!", "<"):
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000550 # lookahead assertions
551 char = source.get()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000552 dir = 1
553 if char == "<":
554 if source.next not in ("=", "!"):
555 raise error, "syntax error"
556 dir = -1 # lookbehind
557 char = source.get()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000558 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000559 if not source.match(")"):
560 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000561 if char == "=":
562 subpattern.append((ASSERT, (dir, p)))
563 else:
564 subpattern.append((ASSERT_NOT, (dir, p)))
565 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000566 else:
567 # flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000568 if not FLAGS.has_key(source.next):
569 raise error, "unexpected end of pattern"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000570 while FLAGS.has_key(source.next):
571 state.flags = state.flags | FLAGS[source.get()]
572 if group:
573 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000574 if group == 2:
575 # anonymous group
576 group = None
577 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000578 group = state.opengroup(name)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000579 p = _parse_sub(source, state)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000580 if not source.match(")"):
581 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000582 if group is not None:
583 state.closegroup(group)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000584 subpattern.append((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000585 else:
586 while 1:
587 char = source.get()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000588 if char is None:
589 raise error, "unexpected end of pattern"
590 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000591 break
592 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000593
Fredrik Lundh90a07912000-06-30 07:50:59 +0000594 elif this == "^":
595 subpattern.append((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000596
Fredrik Lundh90a07912000-06-30 07:50:59 +0000597 elif this == "$":
598 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000599
Fredrik Lundh90a07912000-06-30 07:50:59 +0000600 elif this and this[0] == "\\":
601 code = _escape(source, this, state)
602 subpattern.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000603
Fredrik Lundh90a07912000-06-30 07:50:59 +0000604 else:
605 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000606
607 return subpattern
608
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000609def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000610 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000611
612 source = Tokenizer(str)
613
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000614 if pattern is None:
615 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000616 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000617 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000618
619 p = _parse_sub(source, pattern, 0)
620
621 tail = source.get()
622 if tail == ")":
623 raise error, "unbalanced parenthesis"
624 elif tail:
625 raise error, "bogus characters at end of regular expression"
626
Fredrik Lundh770617b2001-01-14 15:06:11 +0000627 if flags & SRE_FLAG_DEBUG:
628 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000629
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000630 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
631 # the VERBOSE flag was switched on inside the pattern. to be
632 # on the safe side, we'll parse the whole thing again...
633 return parse(str, p.pattern.flags)
634
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000635 return p
636
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000637def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000638 # parse 're' replacement string into list of literals and
639 # group references
640 s = Tokenizer(source)
641 p = []
642 a = p.append
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000643 def literal(literal, p=p):
644 if p and p[-1][0] is LITERAL:
645 p[-1] = LITERAL, p[-1][1] + literal
646 else:
647 p.append((LITERAL, literal))
648 sep = source[:0]
649 if type(sep) is type(""):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000650 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000651 else:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000652 makechar = unichr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000653 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000654 this = s.get()
655 if this is None:
656 break # end of replacement string
657 if this and this[0] == "\\":
658 # group
659 if this == "\\g":
660 name = ""
661 if s.match("<"):
662 while 1:
663 char = s.get()
664 if char is None:
665 raise error, "unterminated group name"
666 if char == ">":
667 break
668 name = name + char
669 if not name:
670 raise error, "bad group name"
671 try:
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000672 index = atoi(name)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000673 except ValueError:
674 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000675 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000676 try:
677 index = pattern.groupindex[name]
678 except KeyError:
679 raise IndexError, "unknown group name"
680 a((MARK, index))
681 elif len(this) > 1 and this[1] in DIGITS:
682 code = None
683 while 1:
684 group = _group(this, pattern.groups+1)
685 if group:
Fredrik Lundh19f977b2000-09-24 14:46:23 +0000686 if (s.next not in DIGITS or
Fredrik Lundh90a07912000-06-30 07:50:59 +0000687 not _group(this + s.next, pattern.groups+1)):
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000688 code = MARK, group
Fredrik Lundh90a07912000-06-30 07:50:59 +0000689 break
690 elif s.next in OCTDIGITS:
691 this = this + s.get()
692 else:
693 break
694 if not code:
695 this = this[1:]
Fredrik Lundh59b68652001-09-18 20:55:24 +0000696 code = LITERAL, makechar(atoi(this[-6:], 8) & 0xff)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000697 if code[0] is LITERAL:
698 literal(code[1])
699 else:
700 a(code)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000701 else:
702 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000703 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000704 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000705 pass
706 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000707 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000708 literal(this)
709 # convert template to groups and literals lists
710 i = 0
711 groups = []
712 literals = []
713 for c, s in p:
714 if c is MARK:
715 groups.append((i, s))
716 literals.append(None)
717 else:
718 literals.append(s)
719 i = i + 1
720 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000721
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000722def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000723 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000724 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000725 groups, literals = template
726 literals = literals[:]
727 try:
728 for index, group in groups:
729 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000730 if s is None:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000731 raise IndexError
732 except IndexError:
733 raise error, "empty group"
734 return string.join(literals, sep)