blob: e0d003ed85bda19080a298a8f4fc01be4135c9a0 [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")
Serhiy Storchaka955b6762017-05-18 12:34:40 +030026ASCIILETTERS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
Guido van Rossum7627c0d2000-03-31 14:58:54 +000027
Raymond Hettinger049ade22005-02-28 19:27:52 +000028WHITESPACE = set(" \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 Lundh436c3d52000-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 Lundh436c3d52000-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 Lundh8a3ebf82000-07-23 21:46:17 +000066class Pattern:
67 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000068 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000069 self.flags = 0
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -050070 self.open = []
71 self.groups = 1
Fredrik Lundh90a07912000-06-30 07:50:59 +000072 self.groupdict = {}
Serhiy Storchaka4809d1f2015-02-21 12:08:36 +020073 self.lookbehind = 0
74
Fredrik Lundhebc37b22000-10-28 19:30:41 +000075 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000076 gid = self.groups
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -050077 self.groups = gid + 1
Raymond Hettingerf13eb552002-06-02 00:40:05 +000078 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000079 ogid = self.groupdict.get(name, None)
80 if ogid is not None:
Fredrik Lundh82b23072001-12-09 16:13:15 +000081 raise error, ("redefinition of group name %s as group %d; "
82 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000083 self.groupdict[name] = gid
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -050084 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000085 return gid
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -050086 def closegroup(self, gid):
87 self.open.remove(gid)
Fredrik Lundhebc37b22000-10-28 19:30:41 +000088 def checkgroup(self, gid):
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -050089 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000090
91class SubPattern:
92 # a subpattern, in intermediate form
93 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000094 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000095 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +000096 data = []
97 self.data = data
98 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000099 def dump(self, level=0):
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300100 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000101 for op, av in self.data:
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300102 print level*" " + op,
103 if op == IN:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000104 # member sublanguage
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300105 print
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000106 for op, a in av:
107 print (level+1)*" " + op, a
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300108 elif op == BRANCH:
109 print
110 for i, a in enumerate(av[1]):
111 if i:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000112 print level*" " + "or"
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300113 a.dump(level+1)
114 elif op == GROUPREF_EXISTS:
115 condgroup, item_yes, item_no = av
116 print condgroup
117 item_yes.dump(level+1)
118 if item_no:
119 print level*" " + "else"
120 item_no.dump(level+1)
121 elif isinstance(av, seqtypes):
122 nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000123 for a in av:
124 if isinstance(a, SubPattern):
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300125 if not nl:
126 print
127 a.dump(level+1)
128 nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000129 else:
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300130 print a,
131 nl = 0
132 if not nl:
133 print
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000134 else:
Serhiy Storchakac0799e32014-09-21 22:47:30 +0300135 print av
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000136 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000137 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000138 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000139 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000140 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000141 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000142 def __getitem__(self, index):
Thomas Wouterse3a985f2006-12-19 08:17:50 +0000143 if isinstance(index, slice):
144 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000145 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000146 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000147 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000148 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000149 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000150 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000151 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000152 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000153 # determine the width (min, max) for this subpattern
154 if self.width:
155 return self.width
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300156 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000157 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
158 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000159 for op, av in self.data:
160 if op is BRANCH:
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300161 i = MAXREPEAT - 1
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000162 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000163 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000164 l, h = av.getwidth()
165 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000166 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000167 lo = lo + i
168 hi = hi + j
169 elif op is CALL:
170 i, j = av.getwidth()
171 lo = lo + i
172 hi = hi + j
173 elif op is SUBPATTERN:
174 i, j = av[1].getwidth()
175 lo = lo + i
176 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000177 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000178 i, j = av[2].getwidth()
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300179 lo = lo + i * av[0]
180 hi = hi + j * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000181 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000182 lo = lo + 1
183 hi = hi + 1
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -0500184 elif op == SUCCESS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000185 break
Serhiy Storchaka34ecb112013-08-19 22:53:46 +0300186 self.width = min(lo, MAXREPEAT - 1), min(hi, MAXREPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000187 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000188
189class Tokenizer:
190 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000191 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000192 self.index = 0
193 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000194 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000195 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000196 self.next = None
197 return
Fredrik Lundh90a07912000-06-30 07:50:59 +0000198 char = self.string[self.index]
199 if char[0] == "\\":
200 try:
201 c = self.string[self.index + 1]
202 except IndexError:
Fredrik Lundh8a0232d2001-11-02 13:59:51 +0000203 raise error, "bogus escape (end of line)"
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)
Ezio Melotti5c4e32b2013-01-11 08:32:01 +0200243 if code and code[0] == IN:
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:
253 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:
262 raise error, "bogus escape: %s" % repr(escape)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000263 if len(escape) == 2:
Serhiy Storchaka955b6762017-05-18 12:34:40 +0300264 if sys.py3kwarning and c in ASCIILETTERS:
265 import warnings
266 if c in 'Uu':
267 warnings.warn('bad escape %s; Unicode escapes are '
268 'supported only since Python 3.3' % escape,
269 FutureWarning, stacklevel=8)
270 else:
271 warnings.warnpy3k('bad escape %s' % escape,
272 DeprecationWarning, stacklevel=8)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000273 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000274 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000275 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000276 raise error, "bogus escape: %s" % repr(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000277
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000278def _escape(source, escape, state):
279 # handle escape code in expression
280 code = CATEGORIES.get(escape)
281 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000282 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000283 code = ESCAPES.get(escape)
284 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000285 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000286 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000287 c = escape[1:2]
288 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000289 # hexadecimal escape
290 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000291 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000292 if len(escape) != 4:
293 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000294 return LITERAL, int(escape[2:], 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000295 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000296 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000297 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +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 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000301 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000302 if source.next in DIGITS:
303 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000304 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
305 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000306 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000307 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000308 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000309 # not an octal escape, so this is a group reference
310 group = int(escape[1:])
311 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000312 if not state.checkgroup(group):
313 raise error, "cannot refer to open group"
Serhiy Storchaka4809d1f2015-02-21 12:08:36 +0200314 if state.lookbehind:
315 import warnings
316 warnings.warn('group references in lookbehind '
317 'assertions are not supported',
318 RuntimeWarning)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000319 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000320 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000321 if len(escape) == 2:
Serhiy Storchaka955b6762017-05-18 12:34:40 +0300322 if sys.py3kwarning and c in ASCIILETTERS:
323 import warnings
324 if c in 'Uu':
325 warnings.warn('bad escape %s; Unicode escapes are '
326 'supported only since Python 3.3' % escape,
327 FutureWarning, stacklevel=8)
328 else:
329 warnings.warnpy3k('bad escape %s' % escape,
330 DeprecationWarning, stacklevel=8)
Fredrik Lundh0640e112000-06-30 13:55:15 +0000331 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000332 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000333 pass
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000334 raise error, "bogus escape: %s" % repr(escape)
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000335
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000336def _parse_sub(source, state, nested=1):
337 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000338
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000339 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000340 itemsappend = items.append
341 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000342 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000343 itemsappend(_parse(source, state))
344 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000345 continue
346 if not nested:
347 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000348 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000349 break
350 else:
351 raise error, "pattern not properly closed"
352
353 if len(items) == 1:
354 return items[0]
355
356 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000357 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000358
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000359 # check if all items share a common prefix
360 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000361 prefix = None
362 for item in items:
363 if not item:
364 break
365 if prefix is None:
366 prefix = item[0]
367 elif item[0] != prefix:
368 break
369 else:
370 # all subitems start with a common "prefix".
371 # move it out of the branch
372 for item in items:
373 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000374 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000375 continue # check next one
376 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000377
378 # check if the branch can be replaced by a character set
379 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000380 if len(item) != 1 or item[0][0] != LITERAL:
381 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000382 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000383 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000384 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000385 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000386 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000387 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000388 setappend(item[0])
389 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000390 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000391
392 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000393 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000394
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000395def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000396 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000397 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000398 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000399 if source.match("|"):
400 raise error, "conditional backref with more than two branches"
401 else:
402 item_no = None
403 if source.next and not source.match(")", 0):
404 raise error, "pattern not properly closed"
405 subpattern = SubPattern(state)
406 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
407 return subpattern
408
Raymond Hettinger049ade22005-02-28 19:27:52 +0000409_PATTERNENDERS = set("|)")
410_ASSERTCHARS = set("=!<")
411_LOOKBEHINDASSERTCHARS = set("=!")
412_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
413
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000414def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000415 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000416 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000417
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000418 # precompute constants into local variables
419 subpatternappend = subpattern.append
420 sourceget = source.get
421 sourcematch = source.match
422 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000423 PATTERNENDERS = _PATTERNENDERS
424 ASSERTCHARS = _ASSERTCHARS
425 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
426 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000427
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000428 while 1:
429
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000430 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000431 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000432 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000433 if this is None:
434 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000435
Fredrik Lundh90a07912000-06-30 07:50:59 +0000436 if state.flags & SRE_FLAG_VERBOSE:
437 # skip whitespace and comments
438 if this in WHITESPACE:
439 continue
440 if this == "#":
441 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000442 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000443 if this in (None, "\n"):
444 break
445 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000446
Fredrik Lundh90a07912000-06-30 07:50:59 +0000447 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000448 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000449
Fredrik Lundh90a07912000-06-30 07:50:59 +0000450 elif this == "[":
451 # character set
452 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000453 setappend = set.append
454## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000455## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000456 if sourcematch("^"):
457 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000458 # check remaining characters
459 start = set[:]
460 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000461 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000462 if this == "]" and set != start:
463 break
464 elif this and this[0] == "\\":
465 code1 = _class_escape(source, this)
466 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000467 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000468 else:
469 raise error, "unexpected end of regular expression"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000470 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000471 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000472 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000473 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000474 if code1[0] is IN:
475 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000476 setappend(code1)
477 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000478 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000479 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000480 if this[0] == "\\":
481 code2 = _class_escape(source, this)
482 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000483 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000484 if code1[0] != LITERAL or code2[0] != LITERAL:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000485 raise error, "bad character range"
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000486 lo = code1[1]
487 hi = code2[1]
488 if hi < lo:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000489 raise error, "bad character range"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000490 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000491 else:
492 raise error, "unexpected end of regular expression"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000493 else:
494 if code1[0] is IN:
495 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000496 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000497
Fredrik Lundh770617b2001-01-14 15:06:11 +0000498 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000499 if _len(set)==1 and set[0][0] is LITERAL:
500 subpatternappend(set[0]) # optimization
501 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
502 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000503 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000504 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000505 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000506
Fredrik Lundh90a07912000-06-30 07:50:59 +0000507 elif this and this[0] in REPEAT_CHARS:
508 # repeat previous item
509 if this == "?":
510 min, max = 0, 1
511 elif this == "*":
512 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000513
Fredrik Lundh90a07912000-06-30 07:50:59 +0000514 elif this == "+":
515 min, max = 1, MAXREPEAT
516 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000517 if source.next == "}":
518 subpatternappend((LITERAL, ord(this)))
519 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000520 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000521 min, max = 0, MAXREPEAT
522 lo = hi = ""
523 while source.next in DIGITS:
524 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000525 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000526 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000527 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000528 else:
529 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000530 if not sourcematch("}"):
531 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000532 source.seek(here)
533 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000534 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000535 min = int(lo)
Serhiy Storchakae18e05c2013-02-16 16:47:15 +0200536 if min >= MAXREPEAT:
537 raise OverflowError("the repetition number is too large")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000538 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000539 max = int(hi)
Serhiy Storchakae18e05c2013-02-16 16:47:15 +0200540 if max >= MAXREPEAT:
541 raise OverflowError("the repetition number is too large")
542 if max < min:
543 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000544 else:
545 raise error, "not supported"
546 # figure out which item to repeat
547 if subpattern:
548 item = subpattern[-1:]
549 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000550 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000551 if not item or (_len(item) == 1 and item[0][0] == AT):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000552 raise error, "nothing to repeat"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000553 if item[0][0] in REPEATCODES:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000554 raise error, "multiple repeat"
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000555 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000556 subpattern[-1] = (MIN_REPEAT, (min, max, item))
557 else:
558 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000559
Fredrik Lundh90a07912000-06-30 07:50:59 +0000560 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000561 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000562
Fredrik Lundh90a07912000-06-30 07:50:59 +0000563 elif this == "(":
564 group = 1
565 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000566 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000567 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000568 group = 0
569 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000570 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000571 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000572 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000573 # named group: skip forward to end of name
574 name = ""
575 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000576 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000577 if char is None:
578 raise error, "unterminated name"
579 if char == ">":
580 break
581 name = name + char
582 group = 1
Ezio Melottief317382012-11-03 20:31:12 +0200583 if not name:
584 raise error("missing group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000585 if not isname(name):
R David Murray60773392013-04-14 13:08:50 -0400586 raise error("bad character in group name %r" %
587 name)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000588 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000589 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000590 name = ""
591 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000592 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000593 if char is None:
594 raise error, "unterminated name"
595 if char == ")":
596 break
597 name = name + char
Ezio Melottief317382012-11-03 20:31:12 +0200598 if not name:
599 raise error("missing group name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000600 if not isname(name):
R David Murray60773392013-04-14 13:08:50 -0400601 raise error("bad character in backref group name "
602 "%r" % name)
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000603 gid = state.groupdict.get(name)
604 if gid is None:
Raymond Hettingerf595a122014-06-22 19:33:19 -0700605 msg = "unknown group name: {0!r}".format(name)
606 raise error(msg)
Serhiy Storchaka4809d1f2015-02-21 12:08:36 +0200607 if state.lookbehind:
608 import warnings
609 warnings.warn('group references in lookbehind '
610 'assertions are not supported',
611 RuntimeWarning)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000612 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000613 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000614 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000615 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000616 if char is None:
617 raise error, "unexpected end of pattern"
618 raise error, "unknown specifier: ?P%s" % char
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000619 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000620 # non-capturing group
621 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000622 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000623 # comment
624 while 1:
625 if source.next is None or source.next == ")":
626 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000627 sourceget()
628 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000629 raise error, "unbalanced parenthesis"
630 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000631 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000632 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000633 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000634 dir = 1
635 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000636 if source.next not in LOOKBEHINDASSERTCHARS:
Fredrik Lundh6f013982000-07-03 18:44:21 +0000637 raise error, "syntax error"
638 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000639 char = sourceget()
Serhiy Storchaka4809d1f2015-02-21 12:08:36 +0200640 state.lookbehind += 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000641 p = _parse_sub(source, state)
Serhiy Storchaka4809d1f2015-02-21 12:08:36 +0200642 if dir < 0:
643 state.lookbehind -= 1
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000644 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000645 raise error, "unbalanced parenthesis"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000646 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000647 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000648 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000649 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000650 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000651 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000652 # conditional backreference group
653 condname = ""
654 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000655 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000656 if char is None:
657 raise error, "unterminated name"
658 if char == ")":
659 break
660 condname = condname + char
661 group = 2
Ezio Melottief317382012-11-03 20:31:12 +0200662 if not condname:
663 raise error("missing group name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000664 if isname(condname):
665 condgroup = state.groupdict.get(condname)
666 if condgroup is None:
Raymond Hettinger008651c2014-06-22 19:45:07 -0700667 msg = "unknown group name: {0!r}".format(condname)
Raymond Hettingerf595a122014-06-22 19:33:19 -0700668 raise error(msg)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000669 else:
670 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000671 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000672 except ValueError:
673 raise error, "bad character in group name"
Serhiy Storchaka4809d1f2015-02-21 12:08:36 +0200674 if state.lookbehind:
675 import warnings
676 warnings.warn('group references in lookbehind '
677 'assertions are not supported',
678 RuntimeWarning)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000679 else:
680 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000681 if not source.next in FLAGS:
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000682 raise error, "unexpected end of pattern"
Raymond Hettinger54f02222002-06-01 14:18:47 +0000683 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000684 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000685 if group:
686 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000687 if group == 2:
688 # anonymous group
689 group = None
690 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000691 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000692 if condgroup:
693 p = _parse_sub_cond(source, state, condgroup)
694 else:
695 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000696 if not sourcematch(")"):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000697 raise error, "unbalanced parenthesis"
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000698 if group is not None:
Benjamin Petersonf8c8d2e2014-11-30 11:47:54 -0500699 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000700 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000701 else:
702 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000703 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000704 if char is None:
705 raise error, "unexpected end of pattern"
706 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000707 break
708 raise error, "unknown extension"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000709
Fredrik Lundh90a07912000-06-30 07:50:59 +0000710 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000711 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000712
Fredrik Lundh90a07912000-06-30 07:50:59 +0000713 elif this == "$":
714 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000715
Fredrik Lundh90a07912000-06-30 07:50:59 +0000716 elif this and this[0] == "\\":
717 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000718 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000719
Fredrik Lundh90a07912000-06-30 07:50:59 +0000720 else:
721 raise error, "parser error"
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000722
723 return subpattern
724
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000725def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000726 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000727
728 source = Tokenizer(str)
729
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000730 if pattern is None:
731 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000732 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000733 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000734
735 p = _parse_sub(source, pattern, 0)
Serhiy Storchaka955b6762017-05-18 12:34:40 +0300736 if (sys.py3kwarning and
737 (p.pattern.flags & SRE_FLAG_LOCALE) and
738 (p.pattern.flags & SRE_FLAG_UNICODE)):
739 import warnings
740 warnings.warnpy3k("LOCALE and UNICODE flags are incompatible",
741 DeprecationWarning, stacklevel=5)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000742
743 tail = source.get()
744 if tail == ")":
745 raise error, "unbalanced parenthesis"
746 elif tail:
747 raise error, "bogus characters at end of regular expression"
748
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000749 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
750 # the VERBOSE flag was switched on inside the pattern. to be
751 # on the safe side, we'll parse the whole thing again...
752 return parse(str, p.pattern.flags)
753
Serhiy Storchakaa61bfdb2016-03-06 09:15:47 +0200754 if flags & SRE_FLAG_DEBUG:
755 p.dump()
756
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000757 return p
758
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000759def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000760 # parse 're' replacement string into list of literals and
761 # group references
762 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000763 sget = s.get
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000764 p = []
765 a = p.append
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000766 def literal(literal, p=p, pappend=a):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000767 if p and p[-1][0] is LITERAL:
768 p[-1] = LITERAL, p[-1][1] + literal
769 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000770 pappend((LITERAL, literal))
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000771 sep = source[:0]
772 if type(sep) is type(""):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000773 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000774 else:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000775 makechar = unichr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000776 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000777 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000778 if this is None:
779 break # end of replacement string
780 if this and this[0] == "\\":
781 # group
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000782 c = this[1:2]
783 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000784 name = ""
785 if s.match("<"):
786 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000787 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000788 if char is None:
789 raise error, "unterminated group name"
790 if char == ">":
791 break
792 name = name + char
793 if not name:
Ezio Melottief317382012-11-03 20:31:12 +0200794 raise error, "missing group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000795 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000796 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000797 if index < 0:
798 raise error, "negative group number"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000799 except ValueError:
800 if not isname(name):
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000801 raise error, "bad character in group name"
Fredrik Lundh90a07912000-06-30 07:50:59 +0000802 try:
803 index = pattern.groupindex[name]
804 except KeyError:
Raymond Hettingerf595a122014-06-22 19:33:19 -0700805 msg = "unknown group name: {0!r}".format(name)
806 raise IndexError(msg)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000807 a((MARK, index))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000808 elif c == "0":
809 if s.next in OCTDIGITS:
810 this = this + sget()
811 if s.next in OCTDIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000812 this = this + sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000813 literal(makechar(int(this[1:], 8) & 0xff))
814 elif c in DIGITS:
815 isoctal = False
816 if s.next in DIGITS:
817 this = this + sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000818 if (c in OCTDIGITS and this[2] in OCTDIGITS and
819 s.next in OCTDIGITS):
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000820 this = this + sget()
821 isoctal = True
822 literal(makechar(int(this[1:], 8) & 0xff))
823 if not isoctal:
824 a((MARK, int(this[1:])))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000825 else:
826 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000827 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000828 except KeyError:
Serhiy Storchaka955b6762017-05-18 12:34:40 +0300829 if sys.py3kwarning and c in ASCIILETTERS:
830 import warnings
831 warnings.warnpy3k('bad escape %s' % this,
832 DeprecationWarning, stacklevel=4)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000833 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000834 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000835 literal(this)
836 # convert template to groups and literals lists
837 i = 0
838 groups = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000839 groupsappend = groups.append
840 literals = [None] * len(p)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000841 for c, s in p:
842 if c is MARK:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000843 groupsappend((i, s))
844 # literal[i] is already None
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000845 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000846 literals[i] = s
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000847 i = i + 1
848 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000849
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000850def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000851 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000852 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000853 groups, literals = template
854 literals = literals[:]
855 try:
856 for index, group in groups:
857 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000858 if s is None:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000859 raise error, "unmatched group"
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000860 except IndexError:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000861 raise error, "invalid group reference"
Barry Warsaw8bee7612004-08-25 02:22:30 +0000862 return sep.join(literals)