blob: bf3e23ff03cc64fdf5da794926e8962d73f66c43 [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
Barry Warsaw8bee7612004-08-25 02:22:30 +000015import sys
Guido van Rossum7627c0d2000-03-31 14:58:54 +000016
17from sre_constants import *
18
Raymond Hettinger049ade22005-02-28 19:27:52 +000019def set(seq):
20 s = {}
21 for elem in seq:
22 s[elem] = 1
23 return s
24
Guido van Rossum7627c0d2000-03-31 14:58:54 +000025SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000026REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000027
Raymond Hettinger049ade22005-02-28 19:27:52 +000028DIGITS = set("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000029
Raymond Hettinger049ade22005-02-28 19:27:52 +000030OCTDIGITS = set("01234567")
31HEXDIGITS = set("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000032
Raymond Hettinger049ade22005-02-28 19:27:52 +000033WHITESPACE = set(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000034
Guido van Rossum7627c0d2000-03-31 14:58:54 +000035ESCAPES = {
Fredrik Lundhf2989b22001-02-18 12:05:16 +000036 r"\a": (LITERAL, ord("\a")),
37 r"\b": (LITERAL, ord("\b")),
38 r"\f": (LITERAL, ord("\f")),
39 r"\n": (LITERAL, ord("\n")),
40 r"\r": (LITERAL, ord("\r")),
41 r"\t": (LITERAL, ord("\t")),
42 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000043 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000044}
45
46CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000047 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000048 r"\b": (AT, AT_BOUNDARY),
49 r"\B": (AT, AT_NON_BOUNDARY),
50 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
51 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
52 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
53 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
54 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
55 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000056 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000057}
58
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000059FLAGS = {
Fredrik Lundh436c3d582000-06-29 08:58:44 +000060 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000061 "i": SRE_FLAG_IGNORECASE,
62 "L": SRE_FLAG_LOCALE,
63 "m": SRE_FLAG_MULTILINE,
64 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000065 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000066 # extensions
67 "t": SRE_FLAG_TEMPLATE,
68 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000069}
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
Raymond Hettingerf13eb552002-06-02 00:40:05 +000081 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000082 ogid = self.groupdict.get(name, None)
83 if ogid is not None:
Collin Winterce36ad82007-08-30 01:19:48 +000084 raise error("redefinition of group name %s as group %d; "
85 "was group %d" % (repr(name), gid, ogid))
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
Raymond Hettingerf13eb552002-06-02 00:40:05 +000098 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000099 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
Guido van Rossum13257902007-06-07 23:15:56 +0000104 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000105 for op, av in self.data:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000106 print(level*" " + op, end=' '); nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000107 if op == "in":
108 # member sublanguage
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000109 print(); nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000110 for op, a in av:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000111 print((level+1)*" " + op, a)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000112 elif op == "branch":
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000113 print(); nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000114 i = 0
115 for a in av[1]:
116 if i > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000117 print(level*" " + "or")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000118 a.dump(level+1); nl = 1
119 i = i + 1
Guido van Rossum13257902007-06-07 23:15:56 +0000120 elif isinstance(av, seqtypes):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000121 for a in av:
122 if isinstance(a, SubPattern):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000123 if not nl: print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000124 a.dump(level+1); nl = 1
125 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000126 print(a, end=' ') ; nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000127 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000128 print(av, end=' ') ; nl = 0
129 if not nl: print()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000130 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000131 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000132 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000133 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000134 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000135 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000136 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000137 if isinstance(index, slice):
138 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000139 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000140 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000141 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000142 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000143 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000144 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000145 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000146 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000147 # determine the width (min, max) for this subpattern
148 if self.width:
149 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000150 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000151 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
152 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000153 for op, av in self.data:
154 if op is BRANCH:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000155 i = sys.maxint
156 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000157 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000158 l, h = av.getwidth()
159 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000160 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000161 lo = lo + i
162 hi = hi + j
163 elif op is CALL:
164 i, j = av.getwidth()
165 lo = lo + i
166 hi = hi + j
167 elif op is SUBPATTERN:
168 i, j = av[1].getwidth()
169 lo = lo + i
170 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000171 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000172 i, j = av[2].getwidth()
Guido van Rossume2a383d2007-01-15 16:59:06 +0000173 lo = lo + int(i) * av[0]
174 hi = hi + int(j) * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000175 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000176 lo = lo + 1
177 hi = hi + 1
178 elif op == SUCCESS:
179 break
180 self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint))
181 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000182
183class Tokenizer:
184 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000185 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000186 self.index = 0
187 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000188 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000189 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000190 self.next = None
191 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000192 char = self.string[self.index:self.index+1]
193 # Special case for the str8, since indexing returns a integer
194 # XXX This is only needed for test_bug_926075 in test_re.py
195 if isinstance(self.string, str8):
196 char = chr(char)
197 if char == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000198 try:
199 c = self.string[self.index + 1]
200 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000201 raise error("bogus escape (end of line)")
Guido van Rossum75a902d2007-10-19 22:06:24 +0000202 if isinstance(self.string, str8):
203 char = chr(c)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000204 char = char + c
205 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000206 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000207 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000208 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000209 if skip:
210 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000211 return 1
212 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000213 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000214 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000215 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000216 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000217 def tell(self):
218 return self.index, self.next
219 def seek(self, index):
220 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000221
Fredrik Lundh4781b072000-06-29 12:38:45 +0000222def isident(char):
223 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
224
225def isdigit(char):
226 return "0" <= char <= "9"
227
228def isname(name):
229 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000230 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000231 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000232 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000233 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000234 return False
235 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000236
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000237def _class_escape(source, escape):
238 # handle escape code inside character class
239 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000240 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000241 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000242 code = CATEGORIES.get(escape)
243 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000244 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000245 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000246 c = escape[1:2]
247 if c == "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:
Collin Winterce36ad82007-08-30 01:19:48 +0000253 raise error("bogus escape: %s" % repr("\\" + escape))
Barry Warsaw8bee7612004-08-25 02:22:30 +0000254 return LITERAL, int(escape, 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000255 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000256 # octal escape (up to three digits)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000257 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000258 escape = escape + source.get()
259 escape = escape[1:]
Barry Warsaw8bee7612004-08-25 02:22:30 +0000260 return LITERAL, int(escape, 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000261 elif c in DIGITS:
Collin Winterce36ad82007-08-30 01:19:48 +0000262 raise error("bogus escape: %s" % repr(escape))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000263 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000264 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000265 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000266 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000267 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000268
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000269def _escape(source, escape, state):
270 # handle escape code in expression
271 code = CATEGORIES.get(escape)
272 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000273 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000274 code = ESCAPES.get(escape)
275 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000276 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000277 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000278 c = escape[1:2]
279 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000280 # hexadecimal escape
281 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000282 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000283 if len(escape) != 4:
284 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000285 return LITERAL, int(escape[2:], 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000286 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000287 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000288 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000289 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000290 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000291 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000292 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000293 if source.next in DIGITS:
294 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000295 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
296 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000297 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000298 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000299 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000300 # not an octal escape, so this is a group reference
301 group = int(escape[1:])
302 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000303 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000304 raise error("cannot refer to open group")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000305 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000306 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000307 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000308 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000309 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000310 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000311 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000312
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000313def _parse_sub(source, state, nested=1):
314 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000315
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000316 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000317 itemsappend = items.append
318 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000319 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000320 itemsappend(_parse(source, state))
321 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000322 continue
323 if not nested:
324 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000325 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000326 break
327 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000328 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000329
330 if len(items) == 1:
331 return items[0]
332
333 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000334 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000335
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000336 # check if all items share a common prefix
337 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000338 prefix = None
339 for item in items:
340 if not item:
341 break
342 if prefix is None:
343 prefix = item[0]
344 elif item[0] != prefix:
345 break
346 else:
347 # all subitems start with a common "prefix".
348 # move it out of the branch
349 for item in items:
350 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000351 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000352 continue # check next one
353 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000354
355 # check if the branch can be replaced by a character set
356 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000357 if len(item) != 1 or item[0][0] != LITERAL:
358 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000359 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000360 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000361 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000362 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000363 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000364 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000365 setappend(item[0])
366 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000367 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000368
369 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000370 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000371
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000372def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000373 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000374 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000375 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000376 if source.match("|"):
Collin Winterce36ad82007-08-30 01:19:48 +0000377 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000378 else:
379 item_no = None
380 if source.next and not source.match(")", 0):
Collin Winterce36ad82007-08-30 01:19:48 +0000381 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000382 subpattern = SubPattern(state)
383 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
384 return subpattern
385
Raymond Hettinger049ade22005-02-28 19:27:52 +0000386_PATTERNENDERS = set("|)")
387_ASSERTCHARS = set("=!<")
388_LOOKBEHINDASSERTCHARS = set("=!")
389_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
390
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000391def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000392 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000393 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000394
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000395 # precompute constants into local variables
396 subpatternappend = subpattern.append
397 sourceget = source.get
398 sourcematch = source.match
399 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000400 PATTERNENDERS = _PATTERNENDERS
401 ASSERTCHARS = _ASSERTCHARS
402 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
403 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000404
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000405 while 1:
406
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000407 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000408 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000409 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000410 if this is None:
411 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000412
Fredrik Lundh90a07912000-06-30 07:50:59 +0000413 if state.flags & SRE_FLAG_VERBOSE:
414 # skip whitespace and comments
415 if this in WHITESPACE:
416 continue
417 if this == "#":
418 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000419 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000420 if this in (None, "\n"):
421 break
422 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000423
Fredrik Lundh90a07912000-06-30 07:50:59 +0000424 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000425 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000426
Fredrik Lundh90a07912000-06-30 07:50:59 +0000427 elif this == "[":
428 # character set
429 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000430 setappend = set.append
431## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000432## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000433 if sourcematch("^"):
434 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000435 # check remaining characters
436 start = set[:]
437 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000438 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000439 if this == "]" and set != start:
440 break
441 elif this and this[0] == "\\":
442 code1 = _class_escape(source, this)
443 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000444 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000445 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000446 raise error("unexpected end of regular expression")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000447 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000448 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000449 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000450 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000451 if code1[0] is IN:
452 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000453 setappend(code1)
454 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000455 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000456 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000457 if this[0] == "\\":
458 code2 = _class_escape(source, this)
459 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000460 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000461 if code1[0] != LITERAL or code2[0] != LITERAL:
Collin Winterce36ad82007-08-30 01:19:48 +0000462 raise error("bad character range")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000463 lo = code1[1]
464 hi = code2[1]
465 if hi < lo:
Collin Winterce36ad82007-08-30 01:19:48 +0000466 raise error("bad character range")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000467 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000468 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000469 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000470 else:
471 if code1[0] is IN:
472 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000473 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000474
Fredrik Lundh770617b2001-01-14 15:06:11 +0000475 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000476 if _len(set)==1 and set[0][0] is LITERAL:
477 subpatternappend(set[0]) # optimization
478 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
479 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000480 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000481 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000482 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000483
Fredrik Lundh90a07912000-06-30 07:50:59 +0000484 elif this and this[0] in REPEAT_CHARS:
485 # repeat previous item
486 if this == "?":
487 min, max = 0, 1
488 elif this == "*":
489 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000490
Fredrik Lundh90a07912000-06-30 07:50:59 +0000491 elif this == "+":
492 min, max = 1, MAXREPEAT
493 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000494 if source.next == "}":
495 subpatternappend((LITERAL, ord(this)))
496 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000497 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000498 min, max = 0, MAXREPEAT
499 lo = hi = ""
500 while source.next in DIGITS:
501 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000502 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000503 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000504 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000505 else:
506 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000507 if not sourcematch("}"):
508 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000509 source.seek(here)
510 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000511 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000512 min = int(lo)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000513 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000514 max = int(hi)
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000515 if max < min:
Collin Winterce36ad82007-08-30 01:19:48 +0000516 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000517 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000518 raise error("not supported")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000519 # figure out which item to repeat
520 if subpattern:
521 item = subpattern[-1:]
522 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000523 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000524 if not item or (_len(item) == 1 and item[0][0] == AT):
Collin Winterce36ad82007-08-30 01:19:48 +0000525 raise error("nothing to repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000526 if item[0][0] in REPEATCODES:
Collin Winterce36ad82007-08-30 01:19:48 +0000527 raise error("multiple repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000528 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000529 subpattern[-1] = (MIN_REPEAT, (min, max, item))
530 else:
531 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000532
Fredrik Lundh90a07912000-06-30 07:50:59 +0000533 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000534 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000535
Fredrik Lundh90a07912000-06-30 07:50:59 +0000536 elif this == "(":
537 group = 1
538 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000539 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000540 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000541 group = 0
542 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000543 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000544 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000545 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000546 # named group: skip forward to end of name
547 name = ""
548 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000549 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000550 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000551 raise error("unterminated name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000552 if char == ">":
553 break
554 name = name + char
555 group = 1
556 if not isname(name):
Collin Winterce36ad82007-08-30 01:19:48 +0000557 raise error("bad character in group name")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000558 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000559 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000560 name = ""
561 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000562 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000563 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000564 raise error("unterminated name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000565 if char == ")":
566 break
567 name = name + char
568 if not isname(name):
Collin Winterce36ad82007-08-30 01:19:48 +0000569 raise error("bad character in group name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000570 gid = state.groupdict.get(name)
571 if gid is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000572 raise error("unknown group name")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000573 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000574 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000575 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000576 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000577 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000578 raise error("unexpected end of pattern")
579 raise error("unknown specifier: ?P%s" % char)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000580 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000581 # non-capturing group
582 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000583 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000584 # comment
585 while 1:
586 if source.next is None or source.next == ")":
587 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000588 sourceget()
589 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000590 raise error("unbalanced parenthesis")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000591 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000592 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000593 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000594 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000595 dir = 1
596 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000597 if source.next not in LOOKBEHINDASSERTCHARS:
Collin Winterce36ad82007-08-30 01:19:48 +0000598 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000599 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000600 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000601 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000602 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000603 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000604 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000605 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000606 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000607 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000608 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000609 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000610 # conditional backreference group
611 condname = ""
612 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000613 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000614 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000615 raise error("unterminated name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000616 if char == ")":
617 break
618 condname = condname + char
619 group = 2
620 if isname(condname):
621 condgroup = state.groupdict.get(condname)
622 if condgroup is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000623 raise error("unknown group name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000624 else:
625 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000626 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000627 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000628 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000629 else:
630 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000631 if not source.next in FLAGS:
Collin Winterce36ad82007-08-30 01:19:48 +0000632 raise error("unexpected end of pattern")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000633 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000634 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000635 if group:
636 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000637 if group == 2:
638 # anonymous group
639 group = None
640 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000641 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000642 if condgroup:
643 p = _parse_sub_cond(source, state, condgroup)
644 else:
645 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000646 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000647 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000648 if group is not None:
649 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000650 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000651 else:
652 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000653 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000654 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000655 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000656 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000657 break
Collin Winterce36ad82007-08-30 01:19:48 +0000658 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000659
Fredrik Lundh90a07912000-06-30 07:50:59 +0000660 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000661 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000662
Fredrik Lundh90a07912000-06-30 07:50:59 +0000663 elif this == "$":
664 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000665
Fredrik Lundh90a07912000-06-30 07:50:59 +0000666 elif this and this[0] == "\\":
667 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000668 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000669
Fredrik Lundh90a07912000-06-30 07:50:59 +0000670 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000671 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000672
673 return subpattern
674
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000675def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000676 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000677
678 source = Tokenizer(str)
679
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000680 if pattern is None:
681 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000682 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000683 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000684
685 p = _parse_sub(source, pattern, 0)
686
687 tail = source.get()
688 if tail == ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000689 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000690 elif tail:
Collin Winterce36ad82007-08-30 01:19:48 +0000691 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000692
Fredrik Lundh770617b2001-01-14 15:06:11 +0000693 if flags & SRE_FLAG_DEBUG:
694 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000695
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000696 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
697 # the VERBOSE flag was switched on inside the pattern. to be
698 # on the safe side, we'll parse the whole thing again...
699 return parse(str, p.pattern.flags)
700
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000701 return p
702
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000703def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000704 # parse 're' replacement string into list of literals and
705 # group references
706 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000707 sget = s.get
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000708 p = []
709 a = p.append
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000710 def literal(literal, p=p, pappend=a):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000711 if p and p[-1][0] is LITERAL:
712 p[-1] = LITERAL, p[-1][1] + literal
713 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000714 pappend((LITERAL, literal))
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000715 sep = source[:0]
Guido van Rossum13257902007-06-07 23:15:56 +0000716 if isinstance(sep, str):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000717 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000718 else:
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000719 makechar = chr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000720 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000721 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000722 if this is None:
723 break # end of replacement string
724 if this and this[0] == "\\":
725 # group
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000726 c = this[1:2]
727 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000728 name = ""
729 if s.match("<"):
730 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000731 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000732 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000733 raise error("unterminated group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000734 if char == ">":
735 break
736 name = name + char
737 if not name:
Collin Winterce36ad82007-08-30 01:19:48 +0000738 raise error("bad group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000739 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000740 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000741 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000742 raise error("negative group number")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000743 except ValueError:
744 if not isname(name):
Collin Winterce36ad82007-08-30 01:19:48 +0000745 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000746 try:
747 index = pattern.groupindex[name]
748 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +0000749 raise IndexError("unknown group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000750 a((MARK, index))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000751 elif c == "0":
752 if s.next in OCTDIGITS:
753 this = this + sget()
754 if s.next in OCTDIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000755 this = this + sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000756 literal(makechar(int(this[1:], 8) & 0xff))
757 elif c in DIGITS:
758 isoctal = False
759 if s.next in DIGITS:
760 this = this + sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000761 if (c in OCTDIGITS and this[2] in OCTDIGITS and
762 s.next in OCTDIGITS):
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000763 this = this + sget()
764 isoctal = True
765 literal(makechar(int(this[1:], 8) & 0xff))
766 if not isoctal:
767 a((MARK, int(this[1:])))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000768 else:
769 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000770 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000771 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000772 pass
773 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000774 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000775 literal(this)
776 # convert template to groups and literals lists
777 i = 0
778 groups = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000779 groupsappend = groups.append
780 literals = [None] * len(p)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000781 for c, s in p:
782 if c is MARK:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000783 groupsappend((i, s))
784 # literal[i] is already None
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000785 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000786 literals[i] = s
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000787 i = i + 1
788 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000789
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000790def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000791 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000792 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000793 groups, literals = template
794 literals = literals[:]
795 try:
796 for index, group in groups:
797 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000798 if s is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000799 raise error("unmatched group")
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000800 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000801 raise error("invalid group reference")
Barry Warsaw8bee7612004-08-25 02:22:30 +0000802 return sep.join(literals)