blob: 9d6e631ef1f9f8cc7baace3aa203d77f9266e1bc [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
Antoine Pitroufd036452008-08-19 17:56:33 +000067 "a": SRE_FLAG_ASCII,
Fredrik Lundh436c3d582000-06-29 08:58:44 +000068 "t": SRE_FLAG_TEMPLATE,
69 "u": SRE_FLAG_UNICODE,
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +000070}
71
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000072class Pattern:
73 # master pattern object. keeps track of global attributes
Guido van Rossum7627c0d2000-03-31 14:58:54 +000074 def __init__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +000075 self.flags = 0
Fredrik Lundhebc37b22000-10-28 19:30:41 +000076 self.open = []
Fredrik Lundh90a07912000-06-30 07:50:59 +000077 self.groups = 1
78 self.groupdict = {}
Fredrik Lundhebc37b22000-10-28 19:30:41 +000079 def opengroup(self, name=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000080 gid = self.groups
81 self.groups = gid + 1
Raymond Hettingerf13eb552002-06-02 00:40:05 +000082 if name is not None:
Tim Peters75335872001-11-03 19:35:43 +000083 ogid = self.groupdict.get(name, None)
84 if ogid is not None:
Collin Winterce36ad82007-08-30 01:19:48 +000085 raise error("redefinition of group name %s as group %d; "
86 "was group %d" % (repr(name), gid, ogid))
Fredrik Lundh90a07912000-06-30 07:50:59 +000087 self.groupdict[name] = gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000088 self.open.append(gid)
Fredrik Lundh90a07912000-06-30 07:50:59 +000089 return gid
Fredrik Lundhebc37b22000-10-28 19:30:41 +000090 def closegroup(self, gid):
91 self.open.remove(gid)
92 def checkgroup(self, gid):
93 return gid < self.groups and gid not in self.open
Guido van Rossum7627c0d2000-03-31 14:58:54 +000094
95class SubPattern:
96 # a subpattern, in intermediate form
97 def __init__(self, pattern, data=None):
Fredrik Lundh90a07912000-06-30 07:50:59 +000098 self.pattern = pattern
Raymond Hettingerf13eb552002-06-02 00:40:05 +000099 if data is None:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000100 data = []
101 self.data = data
102 self.width = None
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000103 def dump(self, level=0):
104 nl = 1
Guido van Rossum13257902007-06-07 23:15:56 +0000105 seqtypes = (tuple, list)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000106 for op, av in self.data:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000107 print(level*" " + op, end=' '); nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000108 if op == "in":
109 # member sublanguage
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000110 print(); nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000111 for op, a in av:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000112 print((level+1)*" " + op, a)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000113 elif op == "branch":
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000114 print(); nl = 1
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000115 i = 0
116 for a in av[1]:
117 if i > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000118 print(level*" " + "or")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000119 a.dump(level+1); nl = 1
120 i = i + 1
Guido van Rossum13257902007-06-07 23:15:56 +0000121 elif isinstance(av, seqtypes):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000122 for a in av:
123 if isinstance(a, SubPattern):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000124 if not nl: print()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000125 a.dump(level+1); nl = 1
126 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000127 print(a, end=' ') ; nl = 0
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000128 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000129 print(av, end=' ') ; nl = 0
130 if not nl: print()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000131 def __repr__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000132 return repr(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000133 def __len__(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000134 return len(self.data)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000135 def __delitem__(self, index):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000136 del self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000137 def __getitem__(self, index):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000138 if isinstance(index, slice):
139 return SubPattern(self.pattern, self.data[index])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000140 return self.data[index]
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000141 def __setitem__(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000142 self.data[index] = code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000143 def insert(self, index, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000144 self.data.insert(index, code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000145 def append(self, code):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000146 self.data.append(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000147 def getwidth(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000148 # determine the width (min, max) for this subpattern
149 if self.width:
150 return self.width
Guido van Rossume2a383d2007-01-15 16:59:06 +0000151 lo = hi = 0
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000152 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
153 REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000154 for op, av in self.data:
155 if op is BRANCH:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000156 i = sys.maxsize
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000157 j = 0
Fredrik Lundh90a07912000-06-30 07:50:59 +0000158 for av in av[1]:
Fredrik Lundh2f2c67d2000-08-01 21:05:41 +0000159 l, h = av.getwidth()
160 i = min(i, l)
Fredrik Lundhe1869832000-08-01 22:47:49 +0000161 j = max(j, h)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000162 lo = lo + i
163 hi = hi + j
164 elif op is CALL:
165 i, j = av.getwidth()
166 lo = lo + i
167 hi = hi + j
168 elif op is SUBPATTERN:
169 i, j = av[1].getwidth()
170 lo = lo + i
171 hi = hi + j
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000172 elif op in REPEATCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000173 i, j = av[2].getwidth()
Guido van Rossume2a383d2007-01-15 16:59:06 +0000174 lo = lo + int(i) * av[0]
175 hi = hi + int(j) * av[1]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000176 elif op in UNITCODES:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000177 lo = lo + 1
178 hi = hi + 1
179 elif op == SUCCESS:
180 break
Christian Heimesa37d4c62007-12-04 23:02:19 +0000181 self.width = int(min(lo, sys.maxsize)), int(min(hi, sys.maxsize))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000182 return self.width
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000183
184class Tokenizer:
185 def __init__(self, string):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000186 self.string = string
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000187 self.index = 0
188 self.__next()
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000189 def __next(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000190 if self.index >= len(self.string):
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000191 self.next = None
192 return
Guido van Rossum75a902d2007-10-19 22:06:24 +0000193 char = self.string[self.index:self.index+1]
194 # Special case for the str8, since indexing returns a integer
195 # XXX This is only needed for test_bug_926075 in test_re.py
Thomas Wouters40a088d2008-03-18 20:19:54 +0000196 if char and isinstance(char, bytes):
197 char = chr(char[0])
Guido van Rossum75a902d2007-10-19 22:06:24 +0000198 if char == "\\":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000199 try:
200 c = self.string[self.index + 1]
201 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000202 raise error("bogus escape (end of line)")
Guido van Rossum98297ee2007-11-06 21:34:58 +0000203 if isinstance(self.string, bytes):
Antoine Pitrou22628c42008-07-22 17:53:22 +0000204 c = chr(c)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000205 char = char + c
206 self.index = self.index + len(char)
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000207 self.next = char
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000208 def match(self, char, skip=1):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000209 if char == self.next:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000210 if skip:
211 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000212 return 1
213 return 0
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000214 def get(self):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000215 this = self.next
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000216 self.__next()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000217 return this
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000218 def tell(self):
219 return self.index, self.next
220 def seek(self, index):
221 self.index, self.next = index
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000222
Fredrik Lundh4781b072000-06-29 12:38:45 +0000223def isident(char):
224 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
225
226def isdigit(char):
227 return "0" <= char <= "9"
228
229def isname(name):
230 # check that group name is a valid string
Fredrik Lundh4781b072000-06-29 12:38:45 +0000231 if not isident(name[0]):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000232 return False
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000233 for char in name[1:]:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000234 if not isident(char) and not isdigit(char):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000235 return False
236 return True
Fredrik Lundh4781b072000-06-29 12:38:45 +0000237
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000238def _class_escape(source, escape):
239 # handle escape code inside character class
240 code = ESCAPES.get(escape)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000241 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000242 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000243 code = CATEGORIES.get(escape)
244 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000245 return code
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000246 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000247 c = escape[1:2]
248 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000249 # hexadecimal escape (exactly two digits)
250 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000251 escape = escape + source.get()
252 escape = escape[2:]
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000253 if len(escape) != 2:
Collin Winterce36ad82007-08-30 01:19:48 +0000254 raise error("bogus escape: %s" % repr("\\" + escape))
Barry Warsaw8bee7612004-08-25 02:22:30 +0000255 return LITERAL, int(escape, 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000256 elif c in OCTDIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000257 # octal escape (up to three digits)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000258 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000259 escape = escape + source.get()
260 escape = escape[1:]
Barry Warsaw8bee7612004-08-25 02:22:30 +0000261 return LITERAL, int(escape, 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000262 elif c in DIGITS:
Collin Winterce36ad82007-08-30 01:19:48 +0000263 raise error("bogus escape: %s" % repr(escape))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000264 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000265 return LITERAL, ord(escape[1])
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000266 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000267 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000268 raise error("bogus escape: %s" % repr(escape))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000269
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000270def _escape(source, escape, state):
271 # handle escape code in expression
272 code = CATEGORIES.get(escape)
273 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000274 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000275 code = ESCAPES.get(escape)
276 if code:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000277 return code
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000278 try:
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000279 c = escape[1:2]
280 if c == "x":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000281 # hexadecimal escape
282 while source.next in HEXDIGITS and len(escape) < 4:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000283 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000284 if len(escape) != 4:
285 raise ValueError
Barry Warsaw8bee7612004-08-25 02:22:30 +0000286 return LITERAL, int(escape[2:], 16) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000287 elif c == "0":
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000288 # octal escape
Fredrik Lundh143328b2000-09-02 11:03:34 +0000289 while source.next in OCTDIGITS and len(escape) < 4:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000290 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000291 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000292 elif c in DIGITS:
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000293 # octal escape *or* decimal group reference (sigh)
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000294 if source.next in DIGITS:
295 escape = escape + source.get()
Fredrik Lundh143328b2000-09-02 11:03:34 +0000296 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
297 source.next in OCTDIGITS):
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000298 # got three octal digits; this is an octal escape
Fredrik Lundh90a07912000-06-30 07:50:59 +0000299 escape = escape + source.get()
Barry Warsaw8bee7612004-08-25 02:22:30 +0000300 return LITERAL, int(escape[1:], 8) & 0xff
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000301 # not an octal escape, so this is a group reference
302 group = int(escape[1:])
303 if group < state.groups:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000304 if not state.checkgroup(group):
Collin Winterce36ad82007-08-30 01:19:48 +0000305 raise error("cannot refer to open group")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000306 return GROUPREF, group
Fredrik Lundh143328b2000-09-02 11:03:34 +0000307 raise ValueError
Fredrik Lundh90a07912000-06-30 07:50:59 +0000308 if len(escape) == 2:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000309 return LITERAL, ord(escape[1])
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000310 except ValueError:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000311 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000312 raise error("bogus escape: %s" % repr(escape))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000313
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000314def _parse_sub(source, state, nested=1):
315 # parse an alternation: a|b|c
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000316
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000317 items = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000318 itemsappend = items.append
319 sourcematch = source.match
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000320 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000321 itemsappend(_parse(source, state))
322 if sourcematch("|"):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000323 continue
324 if not nested:
325 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000326 if not source.next or sourcematch(")", 0):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000327 break
328 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000329 raise error("pattern not properly closed")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000330
331 if len(items) == 1:
332 return items[0]
333
334 subpattern = SubPattern(state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000335 subpatternappend = subpattern.append
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000336
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000337 # check if all items share a common prefix
338 while 1:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000339 prefix = None
340 for item in items:
341 if not item:
342 break
343 if prefix is None:
344 prefix = item[0]
345 elif item[0] != prefix:
346 break
347 else:
348 # all subitems start with a common "prefix".
349 # move it out of the branch
350 for item in items:
351 del item[0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000352 subpatternappend(prefix)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000353 continue # check next one
354 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000355
356 # check if the branch can be replaced by a character set
357 for item in items:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000358 if len(item) != 1 or item[0][0] != LITERAL:
359 break
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000360 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000361 # we can store this as a character set instead of a
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000362 # branch (the compiler may optimize this even more)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000363 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000364 setappend = set.append
Fredrik Lundh90a07912000-06-30 07:50:59 +0000365 for item in items:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000366 setappend(item[0])
367 subpatternappend((IN, set))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000368 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000369
370 subpattern.append((BRANCH, (None, items)))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000371 return subpattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000372
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000373def _parse_sub_cond(source, state, condgroup):
Tim Peters58eb11c2004-01-18 20:29:55 +0000374 item_yes = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000375 if source.match("|"):
Tim Peters58eb11c2004-01-18 20:29:55 +0000376 item_no = _parse(source, state)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000377 if source.match("|"):
Collin Winterce36ad82007-08-30 01:19:48 +0000378 raise error("conditional backref with more than two branches")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000379 else:
380 item_no = None
381 if source.next and not source.match(")", 0):
Collin Winterce36ad82007-08-30 01:19:48 +0000382 raise error("pattern not properly closed")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000383 subpattern = SubPattern(state)
384 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
385 return subpattern
386
Raymond Hettinger049ade22005-02-28 19:27:52 +0000387_PATTERNENDERS = set("|)")
388_ASSERTCHARS = set("=!<")
389_LOOKBEHINDASSERTCHARS = set("=!")
390_REPEATCODES = set([MIN_REPEAT, MAX_REPEAT])
391
Fredrik Lundh55a4f4a2000-06-30 22:37:31 +0000392def _parse(source, state):
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000393 # parse a simple pattern
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000394 subpattern = SubPattern(state)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000395
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000396 # precompute constants into local variables
397 subpatternappend = subpattern.append
398 sourceget = source.get
399 sourcematch = source.match
400 _len = len
Raymond Hettinger049ade22005-02-28 19:27:52 +0000401 PATTERNENDERS = _PATTERNENDERS
402 ASSERTCHARS = _ASSERTCHARS
403 LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
404 REPEATCODES = _REPEATCODES
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000405
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000406 while 1:
407
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000408 if source.next in PATTERNENDERS:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000409 break # end of subpattern
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000410 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000411 if this is None:
412 break # end of pattern
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000413
Fredrik Lundh90a07912000-06-30 07:50:59 +0000414 if state.flags & SRE_FLAG_VERBOSE:
415 # skip whitespace and comments
416 if this in WHITESPACE:
417 continue
418 if this == "#":
419 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000420 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000421 if this in (None, "\n"):
422 break
423 continue
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000424
Fredrik Lundh90a07912000-06-30 07:50:59 +0000425 if this and this[0] not in SPECIAL_CHARS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000426 subpatternappend((LITERAL, ord(this)))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000427
Fredrik Lundh90a07912000-06-30 07:50:59 +0000428 elif this == "[":
429 # character set
430 set = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000431 setappend = set.append
432## if sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000433## pass # handle character classes
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000434 if sourcematch("^"):
435 setappend((NEGATE, None))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000436 # check remaining characters
437 start = set[:]
438 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000439 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000440 if this == "]" and set != start:
441 break
442 elif this and this[0] == "\\":
443 code1 = _class_escape(source, this)
444 elif this:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000445 code1 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000446 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000447 raise error("unexpected end of regular expression")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000448 if sourcematch("-"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000449 # potential range
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000450 this = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000451 if this == "]":
Fredrik Lundh025468d2000-10-07 10:16:19 +0000452 if code1[0] is IN:
453 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000454 setappend(code1)
455 setappend((LITERAL, ord("-")))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000456 break
Guido van Rossum41c99e72003-04-14 17:59:34 +0000457 elif this:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000458 if this[0] == "\\":
459 code2 = _class_escape(source, this)
460 else:
Fredrik Lundh0640e112000-06-30 13:55:15 +0000461 code2 = LITERAL, ord(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000462 if code1[0] != LITERAL or code2[0] != LITERAL:
Collin Winterce36ad82007-08-30 01:19:48 +0000463 raise error("bad character range")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000464 lo = code1[1]
465 hi = code2[1]
466 if hi < lo:
Collin Winterce36ad82007-08-30 01:19:48 +0000467 raise error("bad character range")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000468 setappend((RANGE, (lo, hi)))
Guido van Rossum41c99e72003-04-14 17:59:34 +0000469 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000470 raise error("unexpected end of regular expression")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000471 else:
472 if code1[0] is IN:
473 code1 = code1[1][0]
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000474 setappend(code1)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000475
Fredrik Lundh770617b2001-01-14 15:06:11 +0000476 # XXX: <fl> should move set optimization to compiler!
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000477 if _len(set)==1 and set[0][0] is LITERAL:
478 subpatternappend(set[0]) # optimization
479 elif _len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
480 subpatternappend((NOT_LITERAL, set[1][1])) # optimization
Fredrik Lundh90a07912000-06-30 07:50:59 +0000481 else:
Fredrik Lundh770617b2001-01-14 15:06:11 +0000482 # XXX: <fl> should add charmap optimization here
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000483 subpatternappend((IN, set))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000484
Fredrik Lundh90a07912000-06-30 07:50:59 +0000485 elif this and this[0] in REPEAT_CHARS:
486 # repeat previous item
487 if this == "?":
488 min, max = 0, 1
489 elif this == "*":
490 min, max = 0, MAXREPEAT
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000491
Fredrik Lundh90a07912000-06-30 07:50:59 +0000492 elif this == "+":
493 min, max = 1, MAXREPEAT
494 elif this == "{":
Gustavo Niemeyer6fa0c5a2005-09-14 08:54:39 +0000495 if source.next == "}":
496 subpatternappend((LITERAL, ord(this)))
497 continue
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000498 here = source.tell()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000499 min, max = 0, MAXREPEAT
500 lo = hi = ""
501 while source.next in DIGITS:
502 lo = lo + source.get()
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000503 if sourcematch(","):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000504 while source.next in DIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000505 hi = hi + sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000506 else:
507 hi = lo
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000508 if not sourcematch("}"):
509 subpatternappend((LITERAL, ord(this)))
Fredrik Lundhc13222c2000-07-01 23:49:14 +0000510 source.seek(here)
511 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000512 if lo:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000513 min = int(lo)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000514 if hi:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000515 max = int(hi)
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000516 if max < min:
Collin Winterce36ad82007-08-30 01:19:48 +0000517 raise error("bad repeat interval")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000518 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000519 raise error("not supported")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000520 # figure out which item to repeat
521 if subpattern:
522 item = subpattern[-1:]
523 else:
Fredrik Lundhc0c7ee32001-02-18 21:04:48 +0000524 item = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000525 if not item or (_len(item) == 1 and item[0][0] == AT):
Collin Winterce36ad82007-08-30 01:19:48 +0000526 raise error("nothing to repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000527 if item[0][0] in REPEATCODES:
Collin Winterce36ad82007-08-30 01:19:48 +0000528 raise error("multiple repeat")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000529 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000530 subpattern[-1] = (MIN_REPEAT, (min, max, item))
531 else:
532 subpattern[-1] = (MAX_REPEAT, (min, max, item))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000533
Fredrik Lundh90a07912000-06-30 07:50:59 +0000534 elif this == ".":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000535 subpatternappend((ANY, None))
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000536
Fredrik Lundh90a07912000-06-30 07:50:59 +0000537 elif this == "(":
538 group = 1
539 name = None
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000540 condgroup = None
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000541 if sourcematch("?"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000542 group = 0
543 # options
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000544 if sourcematch("P"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000545 # python extensions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000546 if sourcematch("<"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000547 # named group: skip forward to end of name
548 name = ""
549 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000550 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000551 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000552 raise error("unterminated name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000553 if char == ">":
554 break
555 name = name + char
556 group = 1
557 if not isname(name):
Collin Winterce36ad82007-08-30 01:19:48 +0000558 raise error("bad character in group name")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000559 elif sourcematch("="):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000560 # named backreference
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000561 name = ""
562 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000563 char = sourceget()
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000564 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000565 raise error("unterminated name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000566 if char == ")":
567 break
568 name = name + char
569 if not isname(name):
Collin Winterce36ad82007-08-30 01:19:48 +0000570 raise error("bad character in group name")
Fredrik Lundhb71624e2000-06-30 09:13:06 +0000571 gid = state.groupdict.get(name)
572 if gid is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000573 raise error("unknown group name")
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000574 subpatternappend((GROUPREF, gid))
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000575 continue
Fredrik Lundh90a07912000-06-30 07:50:59 +0000576 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000577 char = sourceget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000578 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000579 raise error("unexpected end of pattern")
580 raise error("unknown specifier: ?P%s" % char)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000581 elif sourcematch(":"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000582 # non-capturing group
583 group = 2
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000584 elif sourcematch("#"):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000585 # comment
586 while 1:
587 if source.next is None or source.next == ")":
588 break
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000589 sourceget()
590 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000591 raise error("unbalanced parenthesis")
Fredrik Lundh0c4fdba2000-08-31 22:57:55 +0000592 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000593 elif source.next in ASSERTCHARS:
Fredrik Lundh43b3b492000-06-30 10:41:31 +0000594 # lookahead assertions
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000595 char = sourceget()
Fredrik Lundh6f013982000-07-03 18:44:21 +0000596 dir = 1
597 if char == "<":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000598 if source.next not in LOOKBEHINDASSERTCHARS:
Collin Winterce36ad82007-08-30 01:19:48 +0000599 raise error("syntax error")
Fredrik Lundh6f013982000-07-03 18:44:21 +0000600 dir = -1 # lookbehind
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000601 char = sourceget()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000602 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000603 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000604 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000605 if char == "=":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000606 subpatternappend((ASSERT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000607 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000608 subpatternappend((ASSERT_NOT, (dir, p)))
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000609 continue
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000610 elif sourcematch("("):
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000611 # conditional backreference group
612 condname = ""
613 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000614 char = sourceget()
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000615 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000616 raise error("unterminated name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000617 if char == ")":
618 break
619 condname = condname + char
620 group = 2
621 if isname(condname):
622 condgroup = state.groupdict.get(condname)
623 if condgroup is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000624 raise error("unknown group name")
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000625 else:
626 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000627 condgroup = int(condname)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000628 except ValueError:
Collin Winterce36ad82007-08-30 01:19:48 +0000629 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000630 else:
631 # flags
Raymond Hettinger54f02222002-06-01 14:18:47 +0000632 if not source.next in FLAGS:
Collin Winterce36ad82007-08-30 01:19:48 +0000633 raise error("unexpected end of pattern")
Raymond Hettinger54f02222002-06-01 14:18:47 +0000634 while source.next in FLAGS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000635 state.flags = state.flags | FLAGS[sourceget()]
Fredrik Lundh90a07912000-06-30 07:50:59 +0000636 if group:
637 # parse group contents
Fredrik Lundh90a07912000-06-30 07:50:59 +0000638 if group == 2:
639 # anonymous group
640 group = None
641 else:
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000642 group = state.opengroup(name)
Gustavo Niemeyerad3fc442003-10-17 22:13:16 +0000643 if condgroup:
644 p = _parse_sub_cond(source, state, condgroup)
645 else:
646 p = _parse_sub(source, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000647 if not sourcematch(")"):
Collin Winterce36ad82007-08-30 01:19:48 +0000648 raise error("unbalanced parenthesis")
Fredrik Lundhebc37b22000-10-28 19:30:41 +0000649 if group is not None:
650 state.closegroup(group)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000651 subpatternappend((SUBPATTERN, (group, p)))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000652 else:
653 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000654 char = sourceget()
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000655 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000656 raise error("unexpected end of pattern")
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000657 if char == ")":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000658 break
Collin Winterce36ad82007-08-30 01:19:48 +0000659 raise error("unknown extension")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000660
Fredrik Lundh90a07912000-06-30 07:50:59 +0000661 elif this == "^":
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000662 subpatternappend((AT, AT_BEGINNING))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000663
Fredrik Lundh90a07912000-06-30 07:50:59 +0000664 elif this == "$":
665 subpattern.append((AT, AT_END))
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000666
Fredrik Lundh90a07912000-06-30 07:50:59 +0000667 elif this and this[0] == "\\":
668 code = _escape(source, this, state)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000669 subpatternappend(code)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000670
Fredrik Lundh90a07912000-06-30 07:50:59 +0000671 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000672 raise error("parser error")
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000673
674 return subpattern
675
Antoine Pitroufd036452008-08-19 17:56:33 +0000676def fix_flags(src, flags):
677 # Check and fix flags according to the type of pattern (str or bytes)
678 if isinstance(src, str):
679 if not flags & SRE_FLAG_ASCII:
680 flags |= SRE_FLAG_UNICODE
681 elif flags & SRE_FLAG_UNICODE:
682 raise ValueError("ASCII and UNICODE flags are incompatible")
683 else:
684 if flags & SRE_FLAG_UNICODE:
685 raise ValueError("can't use UNICODE flag with a bytes pattern")
686 return flags
687
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000688def parse(str, flags=0, pattern=None):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000689 # parse 're' pattern into list of (opcode, argument) tuples
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000690
691 source = Tokenizer(str)
692
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000693 if pattern is None:
694 pattern = Pattern()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000695 pattern.flags = flags
Fredrik Lundh470ea5a2001-01-14 21:00:44 +0000696 pattern.str = str
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000697
698 p = _parse_sub(source, pattern, 0)
Antoine Pitroufd036452008-08-19 17:56:33 +0000699 p.pattern.flags = fix_flags(str, p.pattern.flags)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000700
701 tail = source.get()
702 if tail == ")":
Collin Winterce36ad82007-08-30 01:19:48 +0000703 raise error("unbalanced parenthesis")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000704 elif tail:
Collin Winterce36ad82007-08-30 01:19:48 +0000705 raise error("bogus characters at end of regular expression")
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000706
Fredrik Lundh770617b2001-01-14 15:06:11 +0000707 if flags & SRE_FLAG_DEBUG:
708 p.dump()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000709
Fredrik Lundhd11b5e52000-10-03 19:22:26 +0000710 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
711 # the VERBOSE flag was switched on inside the pattern. to be
712 # on the safe side, we'll parse the whole thing again...
713 return parse(str, p.pattern.flags)
714
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000715 return p
716
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000717def parse_template(source, pattern):
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000718 # parse 're' replacement string into list of literals and
719 # group references
720 s = Tokenizer(source)
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000721 sget = s.get
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000722 p = []
723 a = p.append
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000724 def literal(literal, p=p, pappend=a):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000725 if p and p[-1][0] is LITERAL:
726 p[-1] = LITERAL, p[-1][1] + literal
727 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000728 pappend((LITERAL, literal))
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000729 sep = source[:0]
Guido van Rossum13257902007-06-07 23:15:56 +0000730 if isinstance(sep, str):
Fredrik Lundh59b68652001-09-18 20:55:24 +0000731 makechar = chr
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000732 else:
Guido van Rossum84fc66d2007-05-03 17:18:26 +0000733 makechar = chr
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000734 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000735 this = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000736 if this is None:
737 break # end of replacement string
738 if this and this[0] == "\\":
739 # group
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000740 c = this[1:2]
741 if c == "g":
Fredrik Lundh90a07912000-06-30 07:50:59 +0000742 name = ""
743 if s.match("<"):
744 while 1:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000745 char = sget()
Fredrik Lundh90a07912000-06-30 07:50:59 +0000746 if char is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000747 raise error("unterminated group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000748 if char == ">":
749 break
750 name = name + char
751 if not name:
Collin Winterce36ad82007-08-30 01:19:48 +0000752 raise error("bad group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000753 try:
Barry Warsaw8bee7612004-08-25 02:22:30 +0000754 index = int(name)
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000755 if index < 0:
Collin Winterce36ad82007-08-30 01:19:48 +0000756 raise error("negative group number")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000757 except ValueError:
758 if not isname(name):
Collin Winterce36ad82007-08-30 01:19:48 +0000759 raise error("bad character in group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000760 try:
761 index = pattern.groupindex[name]
762 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +0000763 raise IndexError("unknown group name")
Fredrik Lundh90a07912000-06-30 07:50:59 +0000764 a((MARK, index))
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000765 elif c == "0":
766 if s.next in OCTDIGITS:
767 this = this + sget()
768 if s.next in OCTDIGITS:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000769 this = this + sget()
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000770 literal(makechar(int(this[1:], 8) & 0xff))
771 elif c in DIGITS:
772 isoctal = False
773 if s.next in DIGITS:
774 this = this + sget()
Gustavo Niemeyerf5a15992004-09-03 20:15:56 +0000775 if (c in OCTDIGITS and this[2] in OCTDIGITS and
776 s.next in OCTDIGITS):
Gustavo Niemeyera01a2ee2004-09-03 17:06:10 +0000777 this = this + sget()
778 isoctal = True
779 literal(makechar(int(this[1:], 8) & 0xff))
780 if not isoctal:
781 a((MARK, int(this[1:])))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000782 else:
783 try:
Fredrik Lundh59b68652001-09-18 20:55:24 +0000784 this = makechar(ESCAPES[this][1])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000785 except KeyError:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000786 pass
787 literal(this)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000788 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000789 literal(this)
790 # convert template to groups and literals lists
791 i = 0
792 groups = []
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000793 groupsappend = groups.append
794 literals = [None] * len(p)
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000795 for c, s in p:
796 if c is MARK:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000797 groupsappend((i, s))
798 # literal[i] is already None
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000799 else:
Raymond Hettinger968c56a2004-03-26 23:24:00 +0000800 literals[i] = s
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000801 i = i + 1
802 return groups, literals
Andrew M. Kuchling815d5b92000-06-09 14:08:07 +0000803
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000804def expand_template(template, match):
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000805 g = match.group
Fredrik Lundh0640e112000-06-30 13:55:15 +0000806 sep = match.string[:0]
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000807 groups, literals = template
808 literals = literals[:]
809 try:
810 for index, group in groups:
811 literals[index] = s = g(group)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000812 if s is None:
Collin Winterce36ad82007-08-30 01:19:48 +0000813 raise error("unmatched group")
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000814 except IndexError:
Collin Winterce36ad82007-08-30 01:19:48 +0000815 raise error("invalid group reference")
Barry Warsaw8bee7612004-08-25 02:22:30 +0000816 return sep.join(literals)