blob: c29cc1685cb663626fcccbae3c56b15bdf90b02c [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
19SPECIAL_CHARS = ".\\[{()*+?^$|"
Fredrik Lundh143328b2000-09-02 11:03:34 +000020REPEAT_CHARS = "*+?{"
Guido van Rossum7627c0d2000-03-31 14:58:54 +000021
Raymond Hettinger049ade22005-02-28 19:27:52 +000022DIGITS = set("0123456789")
Guido van Rossumb81e70e2000-04-10 17:10:48 +000023
Raymond Hettinger049ade22005-02-28 19:27:52 +000024OCTDIGITS = set("01234567")
25HEXDIGITS = set("0123456789abcdefABCDEF")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000026
Raymond Hettinger049ade22005-02-28 19:27:52 +000027WHITESPACE = set(" \t\n\r\v\f")
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000028
Guido van Rossum7627c0d2000-03-31 14:58:54 +000029ESCAPES = {
Fredrik Lundhf2989b22001-02-18 12:05:16 +000030 r"\a": (LITERAL, ord("\a")),
31 r"\b": (LITERAL, ord("\b")),
32 r"\f": (LITERAL, ord("\f")),
33 r"\n": (LITERAL, ord("\n")),
34 r"\r": (LITERAL, ord("\r")),
35 r"\t": (LITERAL, ord("\t")),
36 r"\v": (LITERAL, ord("\v")),
Fredrik Lundh0640e112000-06-30 13:55:15 +000037 r"\\": (LITERAL, ord("\\"))
Guido van Rossum7627c0d2000-03-31 14:58:54 +000038}
39
40CATEGORIES = {
Fredrik Lundh770617b2001-01-14 15:06:11 +000041 r"\A": (AT, AT_BEGINNING_STRING), # start of string
Fredrik Lundh01016fe2000-06-30 00:27:46 +000042 r"\b": (AT, AT_BOUNDARY),
43 r"\B": (AT, AT_NON_BOUNDARY),
44 r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]),
45 r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]),
46 r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]),
47 r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]),
48 r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]),
49 r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]),
Fredrik Lundh770617b2001-01-14 15:06:11 +000050 r"\Z": (AT, AT_END_STRING), # end of string
Guido van Rossum7627c0d2000-03-31 14:58:54 +000051}
52
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000053FLAGS = {
Fredrik Lundh436c3d52000-06-29 08:58:44 +000054 # standard flags
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000055 "i": SRE_FLAG_IGNORECASE,
56 "L": SRE_FLAG_LOCALE,
57 "m": SRE_FLAG_MULTILINE,
58 "s": SRE_FLAG_DOTALL,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000059 "x": SRE_FLAG_VERBOSE,
Fredrik Lundh436c3d52000-06-29 08:58:44 +000060 # extensions
61 "t": SRE_FLAG_TEMPLATE,
62 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000063}
64
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000065class Pattern:
66 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000067 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000068 self.flags = 0
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -050069 self.open = []
70 self.groups = 1
Fredrik Lundh90a07912000-06-30 07:50:59 +000071 self.groupdict = {}
Serhiy Storchaka4809d1f2015-02-21 12:08:36 +020072 self.lookbehind = 0
73
Fredrik Lundhebc37b22000-10-28 19:30:41 +000074 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000075 gid = self.groups
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -050076 self.groups = gid + 1
Raymond Hettingerf13eb552002-06-02 00:40:05 +000077 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000078 ogid = self.groupdict.get(name, None)
79 if ogid is not None:
Fredrik Lundh82b23072001-12-09 16:13:15 +000080 raise error, ("redefinition of group name %s as group %d; "
81 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000082 self.groupdict[name] = gid
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -050083 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000084 return gid
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -050085 def closegroup(self, gid):
86 self.open.remove(gid)
Fredrik Lundhebc37b22000-10-28 19:30:41 +000087 def checkgroup(self, gid):
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -050088 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000089
90class SubPattern:
91 # a subpattern, in intermediate form
92 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000093 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000094 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000095 data = []
96 self.data = data
97 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000098 def dump(self, level=0):
Serhiy Storchakac0799e32014-09-21 22:47:30 +030099 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000100 for op, av in self.data:
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300101 print level*" " + op,
102 if op == IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000103 # member sublanguage
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300104 print
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000105 for op, a in av:
106 print (level+1)*" " + op, a
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300107 elif op == BRANCH:
108 print
109 for i, a in enumerate(av[1]):
110 if i:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000111 print level*" " + "or"
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300112 a.dump(level+1)
113 elif op == GROUPREF_EXISTS:
114 condgroup, item_yes, item_no = av
115 print condgroup
116 item_yes.dump(level+1)
117 if item_no:
118 print level*" " + "else"
119 item_no.dump(level+1)
120 elif isinstance(av, seqtypes):
121 nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000122 for a in av:
123 if isinstance(a, SubPattern):
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300124 if not nl:
125 print
126 a.dump(level+1)
127 nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000128 else:
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300129 print a,
130 nl = 0
131 if not nl:
132 print
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000133 else:
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300134 print av
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000135 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000136 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000137 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000138 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000139 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000140 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000141 def __getitem__(self, index):
Thomas Wouterse3a985f2006-12-19 08:17:50 +0000142 if isinstance(index, slice):
143 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000144 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000145 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000146 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000147 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000148 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000149 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000150 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000151 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000152 # determine the width (min, max) for this subpattern
153 if self.width:
154 return self.width
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300155 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000156 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
157 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000158 for op, av in self.data:
159 if op is BRANCH:
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300160 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000161 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000162 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000163 l, h = av.getwidth()
164 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000165 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000166 lo = lo + i
167 hi = hi + j
168 elif op is CALL:
169 i, j = av.getwidth()
170 lo = lo + i
171 hi = hi + j
172 elif op is SUBPATTERN:
173 i, j = av[1].getwidth()
174 lo = lo + i
175 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000176 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000177 i, j = av[2].getwidth()
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300178 lo = lo + i * av[0]
179 hi = hi + j * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000180 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000181 lo = lo + 1
182 hi = hi + 1
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -0500183 elif op == SUCCESS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000184 break
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300185 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000186 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000187
188class Tokenizer:
189 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000190 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000191 self.index = 0
192 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000193 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000194 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000195 self.next = None
196 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000197 char = self.string[self.index]
198 if char[0] == "\\":
199 try:
200 c = self.string[self.index + 1]
201 except IndexError:
Fredrik Lundh8a0232d2001-11-02 13:59:51 +0000202 raise error, "bogus escape (end of line)"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000203 char = char + c
204 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000205 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000206 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000207 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000208 if skip:
209 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000210 return 1
211 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000212 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000213 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000214 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000215 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000216 def tell(self):
217 return self.index, self.next
218 def seek(self, index):
219 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000220
Fredrik Lundh4781b072000-06-29 12:38:45 +0000221def isident(char):
222 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
223
224def isdigit(char):
225 return "0" <= char <= "9"
226
227def isname(name):
228 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000229 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000230 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000231 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000232 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000233 return False
234 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000235
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000236def _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)
Ezio Melotti5c4e32b2013-01-11 08:32:01 +0200242 if code and code[0] == IN:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000243 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000244 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000245 c = escape[1:2]
246 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000247 # hexadecimal escape (exactly two digits)
248 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000249 escape = escape + source.get()
250 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000251 if len(escape) != 2:
252 raise error, "bogus escape: %s" % repr("\\" + escape)
Barry Warsaw8bee7612004-08-25 02:22:30 +0000253 return LITERAL, int(escape, 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000254 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000255 # octal escape (up to three digits)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000256 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000257 escape = escape + source.get()
258 escape = escape[1:]
Barry Warsaw8bee7612004-08-25 02:22:30 +0000259 return LITERAL, int(escape, 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000260 elif c in DIGITS:
261 raise error, "bogus escape: %s" % repr(escape)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000262 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000263 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000264 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000265 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000266 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000267
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000268def _escape(source, escape, state):
269 # handle escape code in expression
270 code = CATEGORIES.get(escape)
271 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000272 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000273 code = ESCAPES.get(escape)
274 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000275 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000276 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000277 c = escape[1:2]
278 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000279 # hexadecimal escape
280 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000281 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000282 if len(escape) != 4:
283 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000284 return LITERAL, int(escape[2:], 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000285 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000286 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000287 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000288 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000289 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000290 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000291 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000292 if source.next in DIGITS:
293 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000294 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
295 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000296 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000297 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000298 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000299 # not an octal escape, so this is a group reference
300 group = int(escape[1:])
301 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000302 if not state.checkgroup(group):
303 raise error, "cannot refer to open group"
Serhiy Storchaka4809d1f2015-02-21 12:08:36 +0200304 if state.lookbehind:
305 import warnings
306 warnings.warn('group references in lookbehind '
307 'assertions are not supported',
308 RuntimeWarning)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000309 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000310 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000311 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000312 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000313 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000314 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000315 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000316
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000317def _parse_sub(source, state, nested=1):
318 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000319
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000320 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000321 itemsappend = items.append
322 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000323 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000324 itemsappend(_parse(source, state))
325 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000326 continue
327 if not nested:
328 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000329 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000330 break
331 else:
332 raise error, "pattern not properly closed"
333
334 if len(items) == 1:
335 return items[0]
336
337 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000338 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000339
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000340 # check if all items share a common prefix
341 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000342 prefix = None
343 for item in items:
344 if not item:
345 break
346 if prefix is None:
347 prefix = item[0]
348 elif item[0] != prefix:
349 break
350 else:
351 # all subitems start with a common "prefix".
352 # move it out of the branch
353 for item in items:
354 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000355 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000356 continue # check next one
357 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000358
359 # check if the branch can be replaced by a character set
360 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000361 if len(item) != 1 or item[0][0] != LITERAL:
362 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000363 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000364 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000365 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000366 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000367 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000368 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000369 setappend(item[0])
370 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000371 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000372
373 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000374 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000375
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000376def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000377 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000378 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000379 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000380 if source.match("|"):
381 raise error, "conditional backref with more than two branches"
382 else:
383 item_no = None
384 if source.next and not source.match(")", 0):
385 raise error, "pattern not properly closed"
386 subpattern = SubPattern(state)
387 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
388 return subpattern
389
Raymond Hettinger049ade22005-02-28 19:27:52 +0000390_PATTERNENDERS = set("|)")
391_ASSERTCHARS = set("=!<")
392_LOOKBEHINDASSERTCHARS = set("=!")
393_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
394
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000395def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000396 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000397 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000398
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000399 # precompute constants into local variables
400 subpatternappend = subpattern.append
401 sourceget = source.get
402 sourcematch = source.match
403 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000404 PATTERNENDERS = _PATTERNENDERS
405 ASSERTCHARS = _ASSERTCHARS
406 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
407 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000408
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000409 while 1:
410
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000411 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000412 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000413 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000414 if this is None:
415 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000416
Fredrik Lundh90a07912000-06-30 07:50:59 +0000417 if state.flags & SRE_FLAG_VERBOSE:
418 # skip whitespace and comments
419 if this in WHITESPACE:
420 continue
421 if this == "#":
422 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000423 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000424 if this in (None, "\n"):
425 break
426 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000427
Fredrik Lundh90a07912000-06-30 07:50:59 +0000428 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000429 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000430
Fredrik Lundh90a07912000-06-30 07:50:59 +0000431 elif this == "[":
432 # character set
433 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000434 setappend = set.append
435## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000436## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000437 if sourcematch("^"):
438 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000439 # check remaining characters
440 start = set[:]
441 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000442 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000443 if this == "]" and set != start:
444 break
445 elif this and this[0] == "\\":
446 code1 = _class_escape(source, this)
447 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000448 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000449 else:
450 raise error, "unexpected end of regular expression"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000451 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000452 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000453 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000454 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000455 if code1[0] is IN:
456 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000457 setappend(code1)
458 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000459 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000460 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000461 if this[0] == "\\":
462 code2 = _class_escape(source, this)
463 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000464 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000465 if code1[0] != LITERAL or code2[0] != LITERAL:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000466 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000467 lo = code1[1]
468 hi = code2[1]
469 if hi < lo:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000470 raise error, "bad character range"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000471 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000472 else:
473 raise error, "unexpected end of regular expression"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000474 else:
475 if code1[0] is IN:
476 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000477 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000478
Fredrik Lundh770617b2001-01-14 15:06:11 +0000479 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000480 if _len(set)==1 and set[0][0] is LITERAL:
481 subpatternappend(set[0]) # optimization
482 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
483 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000484 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000485 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000486 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000487
Fredrik Lundh90a07912000-06-30 07:50:59 +0000488 elif this and this[0] in REPEAT_CHARS:
489 # repeat previous item
490 if this == "?":
491 min, max = 0, 1
492 elif this == "*":
493 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000494
Fredrik Lundh90a07912000-06-30 07:50:59 +0000495 elif this == "+":
496 min, max = 1, MAXREPEAT
497 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000498 if source.next == "}":
499 subpatternappend((LITERAL, ord(this)))
500 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000501 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000502 min, max = 0, MAXREPEAT
503 lo = hi = ""
504 while source.next in DIGITS:
505 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000506 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000507 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000508 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000509 else:
510 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000511 if not sourcematch("}"):
512 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000513 source.seek(here)
514 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000515 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000516 min = int(lo)
Serhiy Storchakae18e05c2013-02-16 16:47:15 +0200517 if min >= MAXREPEAT:
518 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000519 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000520 max = int(hi)
Serhiy Storchakae18e05c2013-02-16 16:47:15 +0200521 if max >= MAXREPEAT:
522 raise OverflowError("the repetition number is too large")
523 if max < min:
524 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000525 else:
526 raise error, "not supported"
527 # figure out which item to repeat
528 if subpattern:
529 item = subpattern[-1:]
530 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000531 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000532 if not item or (_len(item) == 1 and item[0][0] == AT):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000533 raise error, "nothing to repeat"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000534 if item[0][0] in REPEATCODES:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000535 raise error, "multiple repeat"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000536 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000537 subpattern[-1] = (MIN_REPEAT, (min, max, item))
538 else:
539 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000540
Fredrik Lundh90a07912000-06-30 07:50:59 +0000541 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000542 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000543
Fredrik Lundh90a07912000-06-30 07:50:59 +0000544 elif this == "(":
545 group = 1
546 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000547 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000548 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000549 group = 0
550 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000551 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000552 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000553 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000554 # named group: skip forward to end of name
555 name = ""
556 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000557 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000558 if char is None:
559 raise error, "unterminated name"
560 if char == ">":
561 break
562 name = name + char
563 group = 1
Ezio Melottief317382012-11-03 20:31:12 +0200564 if not name:
565 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000566 if not isname(name):
R David Murray60773392013-04-14 13:08:50 -0400567 raise error("bad character in group name %r" %
568 name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000569 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000570 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000571 name = ""
572 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000573 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000574 if char is None:
575 raise error, "unterminated name"
576 if char == ")":
577 break
578 name = name + char
Ezio Melottief317382012-11-03 20:31:12 +0200579 if not name:
580 raise error("missing group name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000581 if not isname(name):
R David Murray60773392013-04-14 13:08:50 -0400582 raise error("bad character in backref group name "
583 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000584 gid = state.groupdict.get(name)
585 if gid is None:
Raymond Hettingerf595a122014-06-22 19:33:19 -0700586 msg = "unknown group name: {0!r}".format(name)
587 raise error(msg)
Serhiy Storchaka4809d1f2015-02-21 12:08:36 +0200588 if state.lookbehind:
589 import warnings
590 warnings.warn('group references in lookbehind '
591 'assertions are not supported',
592 RuntimeWarning)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000593 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000594 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000595 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000596 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000597 if char is None:
598 raise error, "unexpected end of pattern"
599 raise error, "unknown specifier: ?P%s" % char
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000600 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000601 # non-capturing group
602 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000603 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000604 # comment
605 while 1:
606 if source.next is None or source.next == ")":
607 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000608 sourceget()
609 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000610 raise error, "unbalanced parenthesis"
611 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000612 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000613 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000614 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000615 dir = 1
616 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000617 if source.next not in LOOKBEHINDASSERTCHARS:
Fredrik Lundh6f013982000-07-03 18:44:21 +0000618 raise error, "syntax error"
619 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000620 char = sourceget()
Serhiy Storchaka4809d1f2015-02-21 12:08:36 +0200621 state.lookbehind += 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000622 p = _parse_sub(source, state)
Serhiy Storchaka4809d1f2015-02-21 12:08:36 +0200623 if dir < 0:
624 state.lookbehind -= 1
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000625 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000626 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000627 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000628 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000629 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000630 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000631 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000632 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000633 # conditional backreference group
634 condname = ""
635 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000636 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000637 if char is None:
638 raise error, "unterminated name"
639 if char == ")":
640 break
641 condname = condname + char
642 group = 2
Ezio Melottief317382012-11-03 20:31:12 +0200643 if not condname:
644 raise error("missing group name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000645 if isname(condname):
646 condgroup = state.groupdict.get(condname)
647 if condgroup is None:
Raymond Hettinger008651c2014-06-22 19:45:07 -0700648 msg = "unknown group name: {0!r}".format(condname)
Raymond Hettingerf595a122014-06-22 19:33:19 -0700649 raise error(msg)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000650 else:
651 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000652 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000653 except ValueError:
654 raise error, "bad character in group name"
Serhiy Storchaka4809d1f2015-02-21 12:08:36 +0200655 if state.lookbehind:
656 import warnings
657 warnings.warn('group references in lookbehind '
658 'assertions are not supported',
659 RuntimeWarning)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000660 else:
661 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000662 if not source.next in FLAGS:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000663 raise error, "unexpected end of pattern"
Raymond Hettinger54f02222002-06-01 14:18:47 +0000664 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000665 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000666 if group:
667 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000668 if group == 2:
669 # anonymous group
670 group = None
671 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000672 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000673 if condgroup:
674 p = _parse_sub_cond(source, state, condgroup)
675 else:
676 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000677 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000678 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000679 if group is not None:
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -0500680 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000681 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000682 else:
683 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000684 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000685 if char is None:
686 raise error, "unexpected end of pattern"
687 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000688 break
689 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000690
Fredrik Lundh90a07912000-06-30 07:50:59 +0000691 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000692 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000693
Fredrik Lundh90a07912000-06-30 07:50:59 +0000694 elif this == "$":
695 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000696
Fredrik Lundh90a07912000-06-30 07:50:59 +0000697 elif this and this[0] == "\\":
698 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000699 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000700
Fredrik Lundh90a07912000-06-30 07:50:59 +0000701 else:
702 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000703
704 return subpattern
705
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000706def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000707 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000708
709 source = Tokenizer(str)
710
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000711 if pattern is None:
712 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000713 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000714 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000715
716 p = _parse_sub(source, pattern, 0)
717
718 tail = source.get()
719 if tail == ")":
720 raise error, "unbalanced parenthesis"
721 elif tail:
722 raise error, "bogus characters at end of regular expression"
723
Fredrik Lundh770617b2001-01-14 15:06:11 +0000724 if flags & SRE_FLAG_DEBUG:
725 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000726
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000727 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
728 # the VERBOSE flag was switched on inside the pattern. to be
729 # on the safe side, we'll parse the whole thing again...
730 return parse(str, p.pattern.flags)
731
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000732 return p
733
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000734def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000735 # parse 're' replacement string into list of literals and
736 # group references
737 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000738 sget = s.get
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000739 p = []
740 a = p.append
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000741 def literal(literal, p=p, pappend=a):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000742 if p and p[-1][0] is LITERAL:
743 p[-1] = LITERAL, p[-1][1] + literal
744 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000745 pappend((LITERAL, literal))
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000746 sep = source[:0]
747 if type(sep) is type(""):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000748 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000749 else:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000750 makechar = unichr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000751 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000752 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000753 if this is None:
754 break # end of replacement string
755 if this and this[0] == "\\":
756 # group
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000757 c = this[1:2]
758 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000759 name = ""
760 if s.match("<"):
761 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000762 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000763 if char is None:
764 raise error, "unterminated group name"
765 if char == ">":
766 break
767 name = name + char
768 if not name:
Ezio Melottief317382012-11-03 20:31:12 +0200769 raise error, "missing group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000770 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000771 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000772 if index < 0:
773 raise error, "negative group number"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000774 except ValueError:
775 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000776 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000777 try:
778 index = pattern.groupindex[name]
779 except KeyError:
Raymond Hettingerf595a122014-06-22 19:33:19 -0700780 msg = "unknown group name: {0!r}".format(name)
781 raise IndexError(msg)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000782 a((MARK, index))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000783 elif c == "0":
784 if s.next in OCTDIGITS:
785 this = this + sget()
786 if s.next in OCTDIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000787 this = this + sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000788 literal(makechar(int(this[1:], 8) & 0xff))
789 elif c in DIGITS:
790 isoctal = False
791 if s.next in DIGITS:
792 this = this + sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000793 if (c in OCTDIGITS and this[2] in OCTDIGITS and
794 s.next in OCTDIGITS):
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000795 this = this + sget()
796 isoctal = True
797 literal(makechar(int(this[1:], 8) & 0xff))
798 if not isoctal:
799 a((MARK, int(this[1:])))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000800 else:
801 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000802 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000803 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000804 pass
805 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000806 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000807 literal(this)
808 # convert template to groups and literals lists
809 i = 0
810 groups = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000811 groupsappend = groups.append
812 literals = [None] * len(p)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000813 for c, s in p:
814 if c is MARK:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000815 groupsappend((i, s))
816 # literal[i] is already None
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000817 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000818 literals[i] = s
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000819 i = i + 1
820 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000821
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000822def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000823 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000824 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000825 groups, literals = template
826 literals = literals[:]
827 try:
828 for index, group in groups:
829 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000830 if s is None:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000831 raise error, "unmatched group"
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000832 except IndexError:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000833 raise error, "invalid group reference"
Barry Warsaw8bee7612004-08-25 02:22:30 +0000834 return sep.join(literals)