append(): Fixing the test for convertability after consultation with
[python/dscho.git] / Lib / sre_parse.py
blob1b52967a586696f8880a8a334b9334f4a57b7861
2 # Secret Labs' Regular Expression Engine
4 # convert re-style regular expression to sre pattern
6 # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
8 # See the sre.py file for information on usage and redistribution.
11 """Internal support module for sre"""
13 # XXX: show string offset and offending character for all errors
15 # this module works under 1.5.2 and later. don't use string methods
16 import string, sys
18 from sre_constants import *
20 SPECIAL_CHARS = ".\\[{()*+?^$|"
21 REPEAT_CHARS = "*+?{"
23 DIGITS = tuple("0123456789")
25 OCTDIGITS = tuple("01234567")
26 HEXDIGITS = tuple("0123456789abcdefABCDEF")
28 WHITESPACE = tuple(" \t\n\r\v\f")
30 ESCAPES = {
31 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")),
38 r"\\": (LITERAL, ord("\\"))
41 CATEGORIES = {
42 r"\A": (AT, AT_BEGINNING_STRING), # start of string
43 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)]),
51 r"\Z": (AT, AT_END_STRING), # end of string
54 FLAGS = {
55 # standard flags
56 "i": SRE_FLAG_IGNORECASE,
57 "L": SRE_FLAG_LOCALE,
58 "m": SRE_FLAG_MULTILINE,
59 "s": SRE_FLAG_DOTALL,
60 "x": SRE_FLAG_VERBOSE,
61 # extensions
62 "t": SRE_FLAG_TEMPLATE,
63 "u": SRE_FLAG_UNICODE,
66 # figure out best way to convert hex/octal numbers to integers
67 try:
68 int("10", 8)
69 atoi = int # 2.0 and later
70 except TypeError:
71 atoi = string.atoi # 1.5.2
73 class Pattern:
74 # master pattern object. keeps track of global attributes
75 def __init__(self):
76 self.flags = 0
77 self.open = []
78 self.groups = 1
79 self.groupdict = {}
80 def opengroup(self, name=None):
81 gid = self.groups
82 self.groups = gid + 1
83 if name is not None:
84 ogid = self.groupdict.get(name, None)
85 if ogid is not None:
86 raise error, ("redefinition of group name %s as group %d; "
87 "was group %d" % (repr(name), gid, ogid))
88 self.groupdict[name] = gid
89 self.open.append(gid)
90 return gid
91 def closegroup(self, gid):
92 self.open.remove(gid)
93 def checkgroup(self, gid):
94 return gid < self.groups and gid not in self.open
96 class SubPattern:
97 # a subpattern, in intermediate form
98 def __init__(self, pattern, data=None):
99 self.pattern = pattern
100 if data is None:
101 data = []
102 self.data = data
103 self.width = None
104 def dump(self, level=0):
105 nl = 1
106 for op, av in self.data:
107 print level*" " + op,; nl = 0
108 if op == "in":
109 # member sublanguage
110 print; nl = 1
111 for op, a in av:
112 print (level+1)*" " + op, a
113 elif op == "branch":
114 print; nl = 1
115 i = 0
116 for a in av[1]:
117 if i > 0:
118 print level*" " + "or"
119 a.dump(level+1); nl = 1
120 i = i + 1
121 elif type(av) in (type(()), type([])):
122 for a in av:
123 if isinstance(a, SubPattern):
124 if not nl: print
125 a.dump(level+1); nl = 1
126 else:
127 print a, ; nl = 0
128 else:
129 print av, ; nl = 0
130 if not nl: print
131 def __repr__(self):
132 return repr(self.data)
133 def __len__(self):
134 return len(self.data)
135 def __delitem__(self, index):
136 del self.data[index]
137 def __getitem__(self, index):
138 return self.data[index]
139 def __setitem__(self, index, code):
140 self.data[index] = code
141 def __getslice__(self, start, stop):
142 return SubPattern(self.pattern, self.data[start:stop])
143 def insert(self, index, code):
144 self.data.insert(index, code)
145 def append(self, code):
146 self.data.append(code)
147 def getwidth(self):
148 # determine the width (min, max) for this subpattern
149 if self.width:
150 return self.width
151 lo = hi = 0L
152 for op, av in self.data:
153 if op is BRANCH:
154 i = sys.maxint
155 j = 0
156 for av in av[1]:
157 l, h = av.getwidth()
158 i = min(i, l)
159 j = max(j, h)
160 lo = lo + i
161 hi = hi + j
162 elif op is CALL:
163 i, j = av.getwidth()
164 lo = lo + i
165 hi = hi + j
166 elif op is SUBPATTERN:
167 i, j = av[1].getwidth()
168 lo = lo + i
169 hi = hi + j
170 elif op in (MIN_REPEAT, MAX_REPEAT):
171 i, j = av[2].getwidth()
172 lo = lo + long(i) * av[0]
173 hi = hi + long(j) * av[1]
174 elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY):
175 lo = lo + 1
176 hi = hi + 1
177 elif op == SUCCESS:
178 break
179 self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint))
180 return self.width
182 class Tokenizer:
183 def __init__(self, string):
184 self.string = string
185 self.index = 0
186 self.__next()
187 def __next(self):
188 if self.index >= len(self.string):
189 self.next = None
190 return
191 char = self.string[self.index]
192 if char[0] == "\\":
193 try:
194 c = self.string[self.index + 1]
195 except IndexError:
196 raise error, "bogus escape (end of line)"
197 char = char + c
198 self.index = self.index + len(char)
199 self.next = char
200 def match(self, char, skip=1):
201 if char == self.next:
202 if skip:
203 self.__next()
204 return 1
205 return 0
206 def get(self):
207 this = self.next
208 self.__next()
209 return this
210 def tell(self):
211 return self.index, self.next
212 def seek(self, index):
213 self.index, self.next = index
215 def isident(char):
216 return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
218 def isdigit(char):
219 return "0" <= char <= "9"
221 def isname(name):
222 # check that group name is a valid string
223 if not isident(name[0]):
224 return False
225 for char in name:
226 if not isident(char) and not isdigit(char):
227 return False
228 return True
230 def _group(escape, groups):
231 # check if the escape string represents a valid group
232 try:
233 gid = atoi(escape[1:])
234 if gid and gid < groups:
235 return gid
236 except ValueError:
237 pass
238 return None # not a valid group
240 def _class_escape(source, escape):
241 # handle escape code inside character class
242 code = ESCAPES.get(escape)
243 if code:
244 return code
245 code = CATEGORIES.get(escape)
246 if code:
247 return code
248 try:
249 if escape[1:2] == "x":
250 # hexadecimal escape (exactly two digits)
251 while source.next in HEXDIGITS and len(escape) < 4:
252 escape = escape + source.get()
253 escape = escape[2:]
254 if len(escape) != 2:
255 raise error, "bogus escape: %s" % repr("\\" + escape)
256 return LITERAL, atoi(escape, 16) & 0xff
257 elif str(escape[1:2]) in OCTDIGITS:
258 # octal escape (up to three digits)
259 while source.next in OCTDIGITS and len(escape) < 5:
260 escape = escape + source.get()
261 escape = escape[1:]
262 return LITERAL, atoi(escape, 8) & 0xff
263 if len(escape) == 2:
264 return LITERAL, ord(escape[1])
265 except ValueError:
266 pass
267 raise error, "bogus escape: %s" % repr(escape)
269 def _escape(source, escape, state):
270 # handle escape code in expression
271 code = CATEGORIES.get(escape)
272 if code:
273 return code
274 code = ESCAPES.get(escape)
275 if code:
276 return code
277 try:
278 if escape[1:2] == "x":
279 # hexadecimal escape
280 while source.next in HEXDIGITS and len(escape) < 4:
281 escape = escape + source.get()
282 if len(escape) != 4:
283 raise ValueError
284 return LITERAL, atoi(escape[2:], 16) & 0xff
285 elif escape[1:2] == "0":
286 # octal escape
287 while source.next in OCTDIGITS and len(escape) < 4:
288 escape = escape + source.get()
289 return LITERAL, atoi(escape[1:], 8) & 0xff
290 elif escape[1:2] in DIGITS:
291 # octal escape *or* decimal group reference (sigh)
292 if source.next in DIGITS:
293 escape = escape + source.get()
294 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
295 source.next in OCTDIGITS):
296 # got three octal digits; this is an octal escape
297 escape = escape + source.get()
298 return LITERAL, atoi(escape[1:], 8) & 0xff
299 # got at least one decimal digit; this is a group reference
300 group = _group(escape, state.groups)
301 if group:
302 if not state.checkgroup(group):
303 raise error, "cannot refer to open group"
304 return GROUPREF, group
305 raise ValueError
306 if len(escape) == 2:
307 return LITERAL, ord(escape[1])
308 except ValueError:
309 pass
310 raise error, "bogus escape: %s" % repr(escape)
312 def _parse_sub(source, state, nested=1):
313 # parse an alternation: a|b|c
315 items = []
316 while 1:
317 items.append(_parse(source, state))
318 if source.match("|"):
319 continue
320 if not nested:
321 break
322 if not source.next or source.match(")", 0):
323 break
324 else:
325 raise error, "pattern not properly closed"
327 if len(items) == 1:
328 return items[0]
330 subpattern = SubPattern(state)
332 # check if all items share a common prefix
333 while 1:
334 prefix = None
335 for item in items:
336 if not item:
337 break
338 if prefix is None:
339 prefix = item[0]
340 elif item[0] != prefix:
341 break
342 else:
343 # all subitems start with a common "prefix".
344 # move it out of the branch
345 for item in items:
346 del item[0]
347 subpattern.append(prefix)
348 continue # check next one
349 break
351 # check if the branch can be replaced by a character set
352 for item in items:
353 if len(item) != 1 or item[0][0] != LITERAL:
354 break
355 else:
356 # we can store this as a character set instead of a
357 # branch (the compiler may optimize this even more)
358 set = []
359 for item in items:
360 set.append(item[0])
361 subpattern.append((IN, set))
362 return subpattern
364 subpattern.append((BRANCH, (None, items)))
365 return subpattern
367 def _parse(source, state):
368 # parse a simple pattern
370 subpattern = SubPattern(state)
372 while 1:
374 if source.next in ("|", ")"):
375 break # end of subpattern
376 this = source.get()
377 if this is None:
378 break # end of pattern
380 if state.flags & SRE_FLAG_VERBOSE:
381 # skip whitespace and comments
382 if this in WHITESPACE:
383 continue
384 if this == "#":
385 while 1:
386 this = source.get()
387 if this in (None, "\n"):
388 break
389 continue
391 if this and this[0] not in SPECIAL_CHARS:
392 subpattern.append((LITERAL, ord(this)))
394 elif this == "[":
395 # character set
396 set = []
397 ## if source.match(":"):
398 ## pass # handle character classes
399 if source.match("^"):
400 set.append((NEGATE, None))
401 # check remaining characters
402 start = set[:]
403 while 1:
404 this = source.get()
405 if this == "]" and set != start:
406 break
407 elif this and this[0] == "\\":
408 code1 = _class_escape(source, this)
409 elif this:
410 code1 = LITERAL, ord(this)
411 else:
412 raise error, "unexpected end of regular expression"
413 if source.match("-"):
414 # potential range
415 this = source.get()
416 if this == "]":
417 if code1[0] is IN:
418 code1 = code1[1][0]
419 set.append(code1)
420 set.append((LITERAL, ord("-")))
421 break
422 else:
423 if this[0] == "\\":
424 code2 = _class_escape(source, this)
425 else:
426 code2 = LITERAL, ord(this)
427 if code1[0] != LITERAL or code2[0] != LITERAL:
428 raise error, "bad character range"
429 lo = code1[1]
430 hi = code2[1]
431 if hi < lo:
432 raise error, "bad character range"
433 set.append((RANGE, (lo, hi)))
434 else:
435 if code1[0] is IN:
436 code1 = code1[1][0]
437 set.append(code1)
439 # XXX: <fl> should move set optimization to compiler!
440 if len(set)==1 and set[0][0] is LITERAL:
441 subpattern.append(set[0]) # optimization
442 elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
443 subpattern.append((NOT_LITERAL, set[1][1])) # optimization
444 else:
445 # XXX: <fl> should add charmap optimization here
446 subpattern.append((IN, set))
448 elif this and this[0] in REPEAT_CHARS:
449 # repeat previous item
450 if this == "?":
451 min, max = 0, 1
452 elif this == "*":
453 min, max = 0, MAXREPEAT
455 elif this == "+":
456 min, max = 1, MAXREPEAT
457 elif this == "{":
458 here = source.tell()
459 min, max = 0, MAXREPEAT
460 lo = hi = ""
461 while source.next in DIGITS:
462 lo = lo + source.get()
463 if source.match(","):
464 while source.next in DIGITS:
465 hi = hi + source.get()
466 else:
467 hi = lo
468 if not source.match("}"):
469 subpattern.append((LITERAL, ord(this)))
470 source.seek(here)
471 continue
472 if lo:
473 min = atoi(lo)
474 if hi:
475 max = atoi(hi)
476 if max < min:
477 raise error, "bad repeat interval"
478 else:
479 raise error, "not supported"
480 # figure out which item to repeat
481 if subpattern:
482 item = subpattern[-1:]
483 else:
484 item = None
485 if not item or (len(item) == 1 and item[0][0] == AT):
486 raise error, "nothing to repeat"
487 if item[0][0] in (MIN_REPEAT, MAX_REPEAT):
488 raise error, "multiple repeat"
489 if source.match("?"):
490 subpattern[-1] = (MIN_REPEAT, (min, max, item))
491 else:
492 subpattern[-1] = (MAX_REPEAT, (min, max, item))
494 elif this == ".":
495 subpattern.append((ANY, None))
497 elif this == "(":
498 group = 1
499 name = None
500 if source.match("?"):
501 group = 0
502 # options
503 if source.match("P"):
504 # python extensions
505 if source.match("<"):
506 # named group: skip forward to end of name
507 name = ""
508 while 1:
509 char = source.get()
510 if char is None:
511 raise error, "unterminated name"
512 if char == ">":
513 break
514 name = name + char
515 group = 1
516 if not isname(name):
517 raise error, "bad character in group name"
518 elif source.match("="):
519 # named backreference
520 name = ""
521 while 1:
522 char = source.get()
523 if char is None:
524 raise error, "unterminated name"
525 if char == ")":
526 break
527 name = name + char
528 if not isname(name):
529 raise error, "bad character in group name"
530 gid = state.groupdict.get(name)
531 if gid is None:
532 raise error, "unknown group name"
533 subpattern.append((GROUPREF, gid))
534 continue
535 else:
536 char = source.get()
537 if char is None:
538 raise error, "unexpected end of pattern"
539 raise error, "unknown specifier: ?P%s" % char
540 elif source.match(":"):
541 # non-capturing group
542 group = 2
543 elif source.match("#"):
544 # comment
545 while 1:
546 if source.next is None or source.next == ")":
547 break
548 source.get()
549 if not source.match(")"):
550 raise error, "unbalanced parenthesis"
551 continue
552 elif source.next in ("=", "!", "<"):
553 # lookahead assertions
554 char = source.get()
555 dir = 1
556 if char == "<":
557 if source.next not in ("=", "!"):
558 raise error, "syntax error"
559 dir = -1 # lookbehind
560 char = source.get()
561 p = _parse_sub(source, state)
562 if not source.match(")"):
563 raise error, "unbalanced parenthesis"
564 if char == "=":
565 subpattern.append((ASSERT, (dir, p)))
566 else:
567 subpattern.append((ASSERT_NOT, (dir, p)))
568 continue
569 else:
570 # flags
571 if not source.next in FLAGS:
572 raise error, "unexpected end of pattern"
573 while source.next in FLAGS:
574 state.flags = state.flags | FLAGS[source.get()]
575 if group:
576 # parse group contents
577 if group == 2:
578 # anonymous group
579 group = None
580 else:
581 group = state.opengroup(name)
582 p = _parse_sub(source, state)
583 if not source.match(")"):
584 raise error, "unbalanced parenthesis"
585 if group is not None:
586 state.closegroup(group)
587 subpattern.append((SUBPATTERN, (group, p)))
588 else:
589 while 1:
590 char = source.get()
591 if char is None:
592 raise error, "unexpected end of pattern"
593 if char == ")":
594 break
595 raise error, "unknown extension"
597 elif this == "^":
598 subpattern.append((AT, AT_BEGINNING))
600 elif this == "$":
601 subpattern.append((AT, AT_END))
603 elif this and this[0] == "\\":
604 code = _escape(source, this, state)
605 subpattern.append(code)
607 else:
608 raise error, "parser error"
610 return subpattern
612 def parse(str, flags=0, pattern=None):
613 # parse 're' pattern into list of (opcode, argument) tuples
615 source = Tokenizer(str)
617 if pattern is None:
618 pattern = Pattern()
619 pattern.flags = flags
620 pattern.str = str
622 p = _parse_sub(source, pattern, 0)
624 tail = source.get()
625 if tail == ")":
626 raise error, "unbalanced parenthesis"
627 elif tail:
628 raise error, "bogus characters at end of regular expression"
630 if flags & SRE_FLAG_DEBUG:
631 p.dump()
633 if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
634 # the VERBOSE flag was switched on inside the pattern. to be
635 # on the safe side, we'll parse the whole thing again...
636 return parse(str, p.pattern.flags)
638 return p
640 def parse_template(source, pattern):
641 # parse 're' replacement string into list of literals and
642 # group references
643 s = Tokenizer(source)
644 p = []
645 a = p.append
646 def literal(literal, p=p):
647 if p and p[-1][0] is LITERAL:
648 p[-1] = LITERAL, p[-1][1] + literal
649 else:
650 p.append((LITERAL, literal))
651 sep = source[:0]
652 if type(sep) is type(""):
653 makechar = chr
654 else:
655 makechar = unichr
656 while 1:
657 this = s.get()
658 if this is None:
659 break # end of replacement string
660 if this and this[0] == "\\":
661 # group
662 if this == "\\g":
663 name = ""
664 if s.match("<"):
665 while 1:
666 char = s.get()
667 if char is None:
668 raise error, "unterminated group name"
669 if char == ">":
670 break
671 name = name + char
672 if not name:
673 raise error, "bad group name"
674 try:
675 index = atoi(name)
676 except ValueError:
677 if not isname(name):
678 raise error, "bad character in group name"
679 try:
680 index = pattern.groupindex[name]
681 except KeyError:
682 raise IndexError, "unknown group name"
683 a((MARK, index))
684 elif len(this) > 1 and this[1] in DIGITS:
685 code = None
686 while 1:
687 group = _group(this, pattern.groups+1)
688 if group:
689 if (s.next not in DIGITS or
690 not _group(this + s.next, pattern.groups+1)):
691 code = MARK, group
692 break
693 elif s.next in OCTDIGITS:
694 this = this + s.get()
695 else:
696 break
697 if not code:
698 this = this[1:]
699 code = LITERAL, makechar(atoi(this[-6:], 8) & 0xff)
700 if code[0] is LITERAL:
701 literal(code[1])
702 else:
703 a(code)
704 else:
705 try:
706 this = makechar(ESCAPES[this][1])
707 except KeyError:
708 pass
709 literal(this)
710 else:
711 literal(this)
712 # convert template to groups and literals lists
713 i = 0
714 groups = []
715 literals = []
716 for c, s in p:
717 if c is MARK:
718 groups.append((i, s))
719 literals.append(None)
720 else:
721 literals.append(s)
722 i = i + 1
723 return groups, literals
725 def expand_template(template, match):
726 g = match.group
727 sep = match.string[:0]
728 groups, literals = template
729 literals = literals[:]
730 try:
731 for index, group in groups:
732 literals[index] = s = g(group)
733 if s is None:
734 raise IndexError
735 except IndexError:
736 raise error, "empty group"
737 return string.join(literals, sep)