home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / sre_parse.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2008-10-29  |  19.4 KB  |  919 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''Internal support module for sre'''
  5. import sys
  6. from sre_constants import *
  7.  
  8. def set(seq):
  9.     s = { }
  10.     for elem in seq:
  11.         s[elem] = 1
  12.     
  13.     return s
  14.  
  15. SPECIAL_CHARS = '.\\[{()*+?^$|'
  16. REPEAT_CHARS = '*+?{'
  17. DIGITS = set('0123456789')
  18. OCTDIGITS = set('01234567')
  19. HEXDIGITS = set('0123456789abcdefABCDEF')
  20. WHITESPACE = set(' \t\n\r\x0b\x0c')
  21. ESCAPES = {
  22.     '\\a': (LITERAL, ord('\x07')),
  23.     '\\b': (LITERAL, ord('\x08')),
  24.     '\\f': (LITERAL, ord('\x0c')),
  25.     '\\n': (LITERAL, ord('\n')),
  26.     '\\r': (LITERAL, ord('\r')),
  27.     '\\t': (LITERAL, ord('\t')),
  28.     '\\v': (LITERAL, ord('\x0b')),
  29.     '\\\\': (LITERAL, ord('\\')) }
  30. CATEGORIES = {
  31.     '\\A': (AT, AT_BEGINNING_STRING),
  32.     '\\b': (AT, AT_BOUNDARY),
  33.     '\\B': (AT, AT_NON_BOUNDARY),
  34.     '\\d': (IN, [
  35.         (CATEGORY, CATEGORY_DIGIT)]),
  36.     '\\D': (IN, [
  37.         (CATEGORY, CATEGORY_NOT_DIGIT)]),
  38.     '\\s': (IN, [
  39.         (CATEGORY, CATEGORY_SPACE)]),
  40.     '\\S': (IN, [
  41.         (CATEGORY, CATEGORY_NOT_SPACE)]),
  42.     '\\w': (IN, [
  43.         (CATEGORY, CATEGORY_WORD)]),
  44.     '\\W': (IN, [
  45.         (CATEGORY, CATEGORY_NOT_WORD)]),
  46.     '\\Z': (AT, AT_END_STRING) }
  47. FLAGS = {
  48.     'i': SRE_FLAG_IGNORECASE,
  49.     'L': SRE_FLAG_LOCALE,
  50.     'm': SRE_FLAG_MULTILINE,
  51.     's': SRE_FLAG_DOTALL,
  52.     'x': SRE_FLAG_VERBOSE,
  53.     't': SRE_FLAG_TEMPLATE,
  54.     'u': SRE_FLAG_UNICODE }
  55.  
  56. class Pattern:
  57.     
  58.     def __init__(self):
  59.         self.flags = 0
  60.         self.open = []
  61.         self.groups = 1
  62.         self.groupdict = { }
  63.  
  64.     
  65.     def opengroup(self, name = None):
  66.         gid = self.groups
  67.         self.groups = gid + 1
  68.         if name is not None:
  69.             ogid = self.groupdict.get(name, None)
  70.             if ogid is not None:
  71.                 raise error, 'redefinition of group name %s as group %d; was group %d' % (repr(name), gid, ogid)
  72.             
  73.             self.groupdict[name] = gid
  74.         
  75.         self.open.append(gid)
  76.         return gid
  77.  
  78.     
  79.     def closegroup(self, gid):
  80.         self.open.remove(gid)
  81.  
  82.     
  83.     def checkgroup(self, gid):
  84.         if gid < self.groups:
  85.             pass
  86.         return gid not in self.open
  87.  
  88.  
  89.  
  90. class SubPattern:
  91.     
  92.     def __init__(self, pattern, data = None):
  93.         self.pattern = pattern
  94.         if data is None:
  95.             data = []
  96.         
  97.         self.data = data
  98.         self.width = None
  99.  
  100.     
  101.     def dump(self, level = 0):
  102.         nl = 1
  103.         seqtypes = (type(()), type([]))
  104.         for op, av in self.data:
  105.             print level * '  ' + op,
  106.             nl = 0
  107.             if op == 'in':
  108.                 print 
  109.                 nl = 1
  110.                 for op, a in av:
  111.                     print (level + 1) * '  ' + op, a
  112.                 
  113.             elif op == 'branch':
  114.                 print 
  115.                 nl = 1
  116.                 i = 0
  117.                 for a in av[1]:
  118.                     if i > 0:
  119.                         print level * '  ' + 'or'
  120.                     
  121.                     a.dump(level + 1)
  122.                     nl = 1
  123.                     i = i + 1
  124.                 
  125.             elif type(av) in seqtypes:
  126.                 for a in av:
  127.                     if isinstance(a, SubPattern):
  128.                         if not nl:
  129.                             print 
  130.                         
  131.                         a.dump(level + 1)
  132.                         nl = 1
  133.                         continue
  134.                     print a,
  135.                     nl = 0
  136.                 
  137.             else:
  138.                 print av,
  139.                 nl = 0
  140.             if not nl:
  141.                 print 
  142.                 continue
  143.         
  144.  
  145.     
  146.     def __repr__(self):
  147.         return repr(self.data)
  148.  
  149.     
  150.     def __len__(self):
  151.         return len(self.data)
  152.  
  153.     
  154.     def __delitem__(self, index):
  155.         del self.data[index]
  156.  
  157.     
  158.     def __getitem__(self, index):
  159.         return self.data[index]
  160.  
  161.     
  162.     def __setitem__(self, index, code):
  163.         self.data[index] = code
  164.  
  165.     
  166.     def __getslice__(self, start, stop):
  167.         return SubPattern(self.pattern, self.data[start:stop])
  168.  
  169.     
  170.     def insert(self, index, code):
  171.         self.data.insert(index, code)
  172.  
  173.     
  174.     def append(self, code):
  175.         self.data.append(code)
  176.  
  177.     
  178.     def getwidth(self):
  179.         if self.width:
  180.             return self.width
  181.         
  182.         lo = hi = 0x0L
  183.         UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
  184.         REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
  185.         for op, av in self.data:
  186.             if op is BRANCH:
  187.                 i = sys.maxint
  188.                 j = 0
  189.                 for av in av[1]:
  190.                     (l, h) = av.getwidth()
  191.                     i = min(i, l)
  192.                     j = max(j, h)
  193.                 
  194.                 lo = lo + i
  195.                 hi = hi + j
  196.                 continue
  197.             if op is CALL:
  198.                 (i, j) = av.getwidth()
  199.                 lo = lo + i
  200.                 hi = hi + j
  201.                 continue
  202.             if op is SUBPATTERN:
  203.                 (i, j) = av[1].getwidth()
  204.                 lo = lo + i
  205.                 hi = hi + j
  206.                 continue
  207.             if op in REPEATCODES:
  208.                 (i, j) = av[2].getwidth()
  209.                 lo = lo + long(i) * av[0]
  210.                 hi = hi + long(j) * av[1]
  211.                 continue
  212.             if op in UNITCODES:
  213.                 lo = lo + 1
  214.                 hi = hi + 1
  215.                 continue
  216.             if op == SUCCESS:
  217.                 break
  218.                 continue
  219.         
  220.         self.width = (int(min(lo, sys.maxint)), int(min(hi, sys.maxint)))
  221.         return self.width
  222.  
  223.  
  224.  
  225. class Tokenizer:
  226.     
  227.     def __init__(self, string):
  228.         self.string = string
  229.         self.index = 0
  230.         self._Tokenizer__next()
  231.  
  232.     
  233.     def __next(self):
  234.         if self.index >= len(self.string):
  235.             self.next = None
  236.             return None
  237.         
  238.         char = self.string[self.index]
  239.         if char[0] == '\\':
  240.             
  241.             try:
  242.                 c = self.string[self.index + 1]
  243.             except IndexError:
  244.                 raise error, 'bogus escape (end of line)'
  245.  
  246.             char = char + c
  247.         
  248.         self.index = self.index + len(char)
  249.         self.next = char
  250.  
  251.     
  252.     def match(self, char, skip = 1):
  253.         if char == self.next:
  254.             if skip:
  255.                 self._Tokenizer__next()
  256.             
  257.             return 1
  258.         
  259.         return 0
  260.  
  261.     
  262.     def get(self):
  263.         this = self.next
  264.         self._Tokenizer__next()
  265.         return this
  266.  
  267.     
  268.     def tell(self):
  269.         return (self.index, self.next)
  270.  
  271.     
  272.     def seek(self, index):
  273.         (self.index, self.next) = index
  274.  
  275.  
  276.  
  277. def isident(char):
  278.     if char <= char:
  279.         pass
  280.     elif not char <= 'z':
  281.         if char <= char:
  282.             pass
  283.         elif not char <= 'Z':
  284.             pass
  285.     return char == '_'
  286.  
  287.  
  288. def isdigit(char):
  289.     return None if char <= char else char <= '9'
  290.  
  291.  
  292. def isname(name):
  293.     if not isident(name[0]):
  294.         return False
  295.     
  296.     for char in name[1:]:
  297.         if not isident(char) and not isdigit(char):
  298.             return False
  299.             continue
  300.     
  301.     return True
  302.  
  303.  
  304. def _class_escape(source, escape):
  305.     code = ESCAPES.get(escape)
  306.     if code:
  307.         return code
  308.     
  309.     code = CATEGORIES.get(escape)
  310.     if code:
  311.         return code
  312.     
  313.     
  314.     try:
  315.         c = escape[1:2]
  316.         if c == 'x':
  317.             while source.next in HEXDIGITS and len(escape) < 4:
  318.                 escape = escape + source.get()
  319.             escape = escape[2:]
  320.             if len(escape) != 2:
  321.                 raise error, 'bogus escape: %s' % repr('\\' + escape)
  322.             
  323.             return (LITERAL, int(escape, 16) & 255)
  324.         elif c in OCTDIGITS:
  325.             while source.next in OCTDIGITS and len(escape) < 4:
  326.                 escape = escape + source.get()
  327.             escape = escape[1:]
  328.             return (LITERAL, int(escape, 8) & 255)
  329.         elif c in DIGITS:
  330.             raise error, 'bogus escape: %s' % repr(escape)
  331.         
  332.         if len(escape) == 2:
  333.             return (LITERAL, ord(escape[1]))
  334.     except ValueError:
  335.         pass
  336.  
  337.     raise error, 'bogus escape: %s' % repr(escape)
  338.  
  339.  
  340. def _escape(source, escape, state):
  341.     code = CATEGORIES.get(escape)
  342.     if code:
  343.         return code
  344.     
  345.     code = ESCAPES.get(escape)
  346.     if code:
  347.         return code
  348.     
  349.     
  350.     try:
  351.         c = escape[1:2]
  352.         if c == 'x':
  353.             while source.next in HEXDIGITS and len(escape) < 4:
  354.                 escape = escape + source.get()
  355.             if len(escape) != 4:
  356.                 raise ValueError
  357.             
  358.             return (LITERAL, int(escape[2:], 16) & 255)
  359.         elif c == '0':
  360.             while source.next in OCTDIGITS and len(escape) < 4:
  361.                 escape = escape + source.get()
  362.             return (LITERAL, int(escape[1:], 8) & 255)
  363.         elif c in DIGITS:
  364.             if source.next in DIGITS:
  365.                 escape = escape + source.get()
  366.                 if escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and source.next in OCTDIGITS:
  367.                     escape = escape + source.get()
  368.                     return (LITERAL, int(escape[1:], 8) & 255)
  369.                 
  370.             
  371.             group = int(escape[1:])
  372.             if group < state.groups:
  373.                 if not state.checkgroup(group):
  374.                     raise error, 'cannot refer to open group'
  375.                 
  376.                 return (GROUPREF, group)
  377.             
  378.             raise ValueError
  379.         
  380.         if len(escape) == 2:
  381.             return (LITERAL, ord(escape[1]))
  382.     except ValueError:
  383.         pass
  384.  
  385.     raise error, 'bogus escape: %s' % repr(escape)
  386.  
  387.  
  388. def _parse_sub(source, state, nested = 1):
  389.     items = []
  390.     itemsappend = items.append
  391.     sourcematch = source.match
  392.     while None:
  393.         if sourcematch('|'):
  394.             continue
  395.         
  396.         if not nested:
  397.             break
  398.         
  399.         if not (source.next) or sourcematch(')', 0):
  400.             break
  401.             continue
  402.         raise error, 'pattern not properly closed'
  403.         continue
  404.         if len(items) == 1:
  405.             return items[0]
  406.         
  407.     subpattern = SubPattern(state)
  408.     subpatternappend = subpattern.append
  409.     while None:
  410.         prefix = None
  411.         for item in items:
  412.             if not item:
  413.                 break
  414.             
  415.             if prefix is None:
  416.                 prefix = item[0]
  417.                 continue
  418.             if item[0] != prefix:
  419.                 break
  420.                 continue
  421.         else:
  422.             for item in items:
  423.                 del item[0]
  424.             
  425.         break
  426.         continue
  427.         for item in items:
  428.             if len(item) != 1 or item[0][0] != LITERAL:
  429.                 break
  430.                 continue
  431.         else:
  432.             set = []
  433.             setappend = set.append
  434.             for item in items:
  435.                 setappend(item[0])
  436.             
  437.             return subpattern
  438.     subpattern.append((BRANCH, (None, items)))
  439.     return subpattern
  440.  
  441.  
  442. def _parse_sub_cond(source, state, condgroup):
  443.     item_yes = _parse(source, state)
  444.     if source.match('|'):
  445.         item_no = _parse(source, state)
  446.         if source.match('|'):
  447.             raise error, 'conditional backref with more than two branches'
  448.         
  449.     else:
  450.         item_no = None
  451.     if source.next and not source.match(')', 0):
  452.         raise error, 'pattern not properly closed'
  453.     
  454.     subpattern = SubPattern(state)
  455.     subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
  456.     return subpattern
  457.  
  458. _PATTERNENDERS = set('|)')
  459. _ASSERTCHARS = set('=!<')
  460. _LOOKBEHINDASSERTCHARS = set('=!')
  461. _REPEATCODES = set([
  462.     MIN_REPEAT,
  463.     MAX_REPEAT])
  464.  
  465. def _parse(source, state):
  466.     subpattern = SubPattern(state)
  467.     subpatternappend = subpattern.append
  468.     sourceget = source.get
  469.     sourcematch = source.match
  470.     _len = len
  471.     PATTERNENDERS = _PATTERNENDERS
  472.     ASSERTCHARS = _ASSERTCHARS
  473.     LOOKBEHINDASSERTCHARS = _LOOKBEHINDASSERTCHARS
  474.     REPEATCODES = _REPEATCODES
  475.     while source.next in PATTERNENDERS:
  476.         break
  477.     this = sourceget()
  478.     if this is None:
  479.         break
  480.     
  481.     if state.flags & SRE_FLAG_VERBOSE:
  482.         if this in WHITESPACE:
  483.             continue
  484.         
  485.         if this == '#':
  486.             while None:
  487.                 this = sourceget()
  488.                 if this in (None, '\n'):
  489.                     break
  490.                     continue
  491.                 continue
  492.                 continue
  493.         this == '#'
  494.     
  495.     if this and this[0] not in SPECIAL_CHARS:
  496.         subpatternappend((LITERAL, ord(this)))
  497.         continue
  498.     if this == '[':
  499.         set = []
  500.         setappend = set.append
  501.         if sourcematch('^'):
  502.             setappend((NEGATE, None))
  503.         
  504.         start = set[:]
  505.         while None:
  506.             this = sourceget()
  507.             if this == ']' and set != start:
  508.                 break
  509.             elif this and this[0] == '\\':
  510.                 code1 = _class_escape(source, this)
  511.             elif this:
  512.                 code1 = (LITERAL, ord(this))
  513.             else:
  514.                 raise error, 'unexpected end of regular expression'
  515.             if sourcematch('-'):
  516.                 this = sourceget()
  517.                 if this == ']':
  518.                     if code1[0] is IN:
  519.                         code1 = code1[1][0]
  520.                     
  521.                     setappend(code1)
  522.                     setappend((LITERAL, ord('-')))
  523.                     break
  524.                 elif this:
  525.                     if this[0] == '\\':
  526.                         code2 = _class_escape(source, this)
  527.                     else:
  528.                         code2 = (LITERAL, ord(this))
  529.                     if code1[0] != LITERAL or code2[0] != LITERAL:
  530.                         raise error, 'bad character range'
  531.                     
  532.                     lo = code1[1]
  533.                     hi = code2[1]
  534.                     if hi < lo:
  535.                         raise error, 'bad character range'
  536.                     
  537.                     setappend((RANGE, (lo, hi)))
  538.                 else:
  539.                     raise error, 'unexpected end of regular expression'
  540.             if code1[0] is IN:
  541.                 code1 = code1[1][0]
  542.             
  543.             setappend(code1)
  544.             continue
  545.             if _len(set) == 1 and set[0][0] is LITERAL:
  546.                 subpatternappend(set[0])
  547.             elif _len(set) == 2 and set[0][0] is NEGATE and set[1][0] is LITERAL:
  548.                 subpatternappend((NOT_LITERAL, set[1][1]))
  549.             else:
  550.                 subpatternappend((IN, set))
  551.             set[1][0] is LITERAL
  552.             if this and this[0] in REPEAT_CHARS:
  553.                 if this == '?':
  554.                     (min, max) = (0, 1)
  555.                 elif this == '*':
  556.                     min = 0
  557.                     max = MAXREPEAT
  558.                 elif this == '+':
  559.                     min = 1
  560.                     max = MAXREPEAT
  561.                 elif this == '{':
  562.                     if source.next == '}':
  563.                         subpatternappend((LITERAL, ord(this)))
  564.                         continue
  565.                     
  566.                     here = source.tell()
  567.                     min = 0
  568.                     max = MAXREPEAT
  569.                     lo = hi = ''
  570.                     while source.next in DIGITS:
  571.                         lo = lo + source.get()
  572.                     if sourcematch(','):
  573.                         while source.next in DIGITS:
  574.                             hi = hi + sourceget()
  575.                     else:
  576.                         hi = lo
  577.                     if not sourcematch('}'):
  578.                         subpatternappend((LITERAL, ord(this)))
  579.                         source.seek(here)
  580.                         continue
  581.                     
  582.                     if lo:
  583.                         min = int(lo)
  584.                     
  585.                     if hi:
  586.                         max = int(hi)
  587.                     
  588.                     if max < min:
  589.                         raise error, 'bad repeat interval'
  590.                     
  591.                 else:
  592.                     raise error, 'not supported'
  593.                 if subpattern:
  594.                     item = subpattern[-1:]
  595.                 else:
  596.                     item = None
  597.                 if (not item or _len(item) == 1) and item[0][0] == AT:
  598.                     raise error, 'nothing to repeat'
  599.                 
  600.                 if item[0][0] in REPEATCODES:
  601.                     raise error, 'multiple repeat'
  602.                 
  603.                 if sourcematch('?'):
  604.                     subpattern[-1] = (MIN_REPEAT, (min, max, item))
  605.                 else:
  606.                     subpattern[-1] = (MAX_REPEAT, (min, max, item))
  607.     sourcematch('?')
  608.     if this == '.':
  609.         subpatternappend((ANY, None))
  610.         continue
  611.     if this == '(':
  612.         group = 1
  613.         name = None
  614.         condgroup = None
  615.         if sourcematch('?'):
  616.             group = 0
  617.             if sourcematch('P'):
  618.                 if sourcematch('<'):
  619.                     name = ''
  620.                     while None:
  621.                         char = sourceget()
  622.                         if char is None:
  623.                             raise error, 'unterminated name'
  624.                         
  625.                         if char == '>':
  626.                             break
  627.                         
  628.                         name = name + char
  629.                         continue
  630.                         group = 1
  631.                         if not isname(name):
  632.                             raise error, 'bad character in group name'
  633.                         
  634.                 isname(name)
  635.                 if sourcematch('='):
  636.                     name = ''
  637.                     while None:
  638.                         char = sourceget()
  639.                         if char is None:
  640.                             raise error, 'unterminated name'
  641.                         
  642.                         if char == ')':
  643.                             break
  644.                         
  645.                         name = name + char
  646.                         continue
  647.                         if not isname(name):
  648.                             raise error, 'bad character in group name'
  649.                         
  650.                     gid = state.groupdict.get(name)
  651.                     if gid is None:
  652.                         raise error, 'unknown group name'
  653.                     
  654.                     subpatternappend((GROUPREF, gid))
  655.                     continue
  656.                 else:
  657.                     char = sourceget()
  658.                     if char is None:
  659.                         raise error, 'unexpected end of pattern'
  660.                     
  661.                     raise error, 'unknown specifier: ?P%s' % char
  662.             elif sourcematch(':'):
  663.                 group = 2
  664.             elif sourcematch('#'):
  665.                 while source.next is None or source.next == ')':
  666.                     break
  667.                 sourcematch('?')
  668.                 sourceget()
  669.                 continue
  670.                 if not sourcematch(')'):
  671.                     raise error, 'unbalanced parenthesis'
  672.                     continue
  673.                 continue
  674.             elif source.next in ASSERTCHARS:
  675.                 char = sourceget()
  676.                 dir = 1
  677.                 if char == '<':
  678.                     if source.next not in LOOKBEHINDASSERTCHARS:
  679.                         raise error, 'syntax error'
  680.                     
  681.                     dir = -1
  682.                     char = sourceget()
  683.                 
  684.                 p = _parse_sub(source, state)
  685.                 if not sourcematch(')'):
  686.                     raise error, 'unbalanced parenthesis'
  687.                 
  688.                 if char == '=':
  689.                     subpatternappend((ASSERT, (dir, p)))
  690.                     continue
  691.                 subpatternappend((ASSERT_NOT, (dir, p)))
  692.                 continue
  693.             elif sourcematch('('):
  694.                 condname = ''
  695.                 while None:
  696.                     char = sourceget()
  697.                     if char is None:
  698.                         raise error, 'unterminated name'
  699.                     
  700.                     if char == ')':
  701.                         break
  702.                     
  703.                     condname = condname + char
  704.                     continue
  705.                     group = 2
  706.                     if isname(condname):
  707.                         condgroup = state.groupdict.get(condname)
  708.                         if condgroup is None:
  709.                             raise error, 'unknown group name'
  710.                         
  711.                     else:
  712.                         
  713.                         try:
  714.                             condgroup = int(condname)
  715.                         except ValueError:
  716.                             raise error, 'bad character in group name'
  717.                         except:
  718.                             None<EXCEPTION MATCH>ValueError
  719.                         
  720.  
  721.                         None<EXCEPTION MATCH>ValueError
  722.                         if source.next not in FLAGS:
  723.                             raise error, 'unexpected end of pattern'
  724.                         
  725.             while source.next in FLAGS:
  726.                 state.flags = state.flags | FLAGS[sourceget()]
  727.         
  728.         if group:
  729.             if group == 2:
  730.                 group = None
  731.             else:
  732.                 group = state.opengroup(name)
  733.             if condgroup:
  734.                 p = _parse_sub_cond(source, state, condgroup)
  735.             else:
  736.                 p = _parse_sub(source, state)
  737.             if not sourcematch(')'):
  738.                 raise error, 'unbalanced parenthesis'
  739.             
  740.             if group is not None:
  741.                 state.closegroup(group)
  742.             
  743.             subpatternappend((SUBPATTERN, (group, p)))
  744.         else:
  745.             while None:
  746.                 char = sourceget()
  747.                 if char is None:
  748.                     raise error, 'unexpected end of pattern'
  749.                 
  750.                 if char == ')':
  751.                     break
  752.                 
  753.                 raise error, 'unknown extension'
  754.                 continue
  755.                 continue
  756.                 if this == '^':
  757.                     subpatternappend((AT, AT_BEGINNING))
  758.                     continue
  759.                 if this == '$':
  760.                     subpattern.append((AT, AT_END))
  761.                     continue
  762.                 if this and this[0] == '\\':
  763.                     code = _escape(source, this, state)
  764.                     subpatternappend(code)
  765.                     continue
  766.                 raise error, 'parser error'
  767.                 continue
  768.                 return subpattern
  769.  
  770.  
  771. def parse(str, flags = 0, pattern = None):
  772.     source = Tokenizer(str)
  773.     if pattern is None:
  774.         pattern = Pattern()
  775.     
  776.     pattern.flags = flags
  777.     pattern.str = str
  778.     p = _parse_sub(source, pattern, 0)
  779.     tail = source.get()
  780.     if tail == ')':
  781.         raise error, 'unbalanced parenthesis'
  782.     elif tail:
  783.         raise error, 'bogus characters at end of regular expression'
  784.     
  785.     if flags & SRE_FLAG_DEBUG:
  786.         p.dump()
  787.     
  788.     if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
  789.         return parse(str, p.pattern.flags)
  790.     
  791.     return p
  792.  
  793.  
  794. def parse_template(source, pattern):
  795.     s = Tokenizer(source)
  796.     sget = s.get
  797.     p = []
  798.     a = p.append
  799.     
  800.     def literal(literal, p = p, pappend = a):
  801.         if p and p[-1][0] is LITERAL:
  802.             p[-1] = (LITERAL, p[-1][1] + literal)
  803.         else:
  804.             pappend((LITERAL, literal))
  805.  
  806.     sep = source[:0]
  807.     if type(sep) is type(''):
  808.         makechar = chr
  809.     else:
  810.         makechar = unichr
  811.     while None:
  812.         this = sget()
  813.         if this is None:
  814.             break
  815.         
  816.         if this and this[0] == '\\':
  817.             c = this[1:2]
  818.             if c == 'g':
  819.                 name = ''
  820.                 if s.match('<'):
  821.                     while None:
  822.                         char = sget()
  823.                         if char is None:
  824.                             raise error, 'unterminated group name'
  825.                         
  826.                         if char == '>':
  827.                             break
  828.                         
  829.                         name = name + char
  830.                         continue
  831.                 s.match('<')
  832.                 if not name:
  833.                     raise error, 'bad group name'
  834.                 
  835.                 
  836.                 try:
  837.                     index = int(name)
  838.                     if index < 0:
  839.                         raise error, 'negative group number'
  840.                 except ValueError:
  841.                     if not isname(name):
  842.                         raise error, 'bad character in group name'
  843.                     
  844.                     
  845.                     try:
  846.                         index = pattern.groupindex[name]
  847.                     except KeyError:
  848.                         raise IndexError, 'unknown group name'
  849.                     except:
  850.                         None<EXCEPTION MATCH>KeyError
  851.                     
  852.  
  853.                     None<EXCEPTION MATCH>KeyError
  854.  
  855.                 a((MARK, index))
  856.             elif c == '0':
  857.                 if s.next in OCTDIGITS:
  858.                     this = this + sget()
  859.                     if s.next in OCTDIGITS:
  860.                         this = this + sget()
  861.                     
  862.                 
  863.                 literal(makechar(int(this[1:], 8) & 255))
  864.             elif c in DIGITS:
  865.                 isoctal = False
  866.                 if s.next in DIGITS:
  867.                     this = this + sget()
  868.                     if c in OCTDIGITS and this[2] in OCTDIGITS and s.next in OCTDIGITS:
  869.                         this = this + sget()
  870.                         isoctal = True
  871.                         literal(makechar(int(this[1:], 8) & 255))
  872.                     
  873.                 
  874.                 if not isoctal:
  875.                     a((MARK, int(this[1:])))
  876.                 
  877.             else:
  878.                 
  879.                 try:
  880.                     this = makechar(ESCAPES[this][1])
  881.                 except KeyError:
  882.                     pass
  883.  
  884.                 literal(this)
  885.         literal(this)
  886.         continue
  887.         i = 0
  888.         groups = []
  889.         groupsappend = groups.append
  890.         literals = [
  891.             None] * len(p)
  892.         for c, s in p:
  893.             if c is MARK:
  894.                 groupsappend((i, s))
  895.             else:
  896.                 literals[i] = s
  897.             i = i + 1
  898.         
  899.     return (groups, literals)
  900.  
  901.  
  902. def expand_template(template, match):
  903.     g = match.group
  904.     sep = match.string[:0]
  905.     (groups, literals) = template
  906.     literals = literals[:]
  907.     
  908.     try:
  909.         for index, group in groups:
  910.             literals[index] = s = g(group)
  911.             if s is None:
  912.                 raise error, 'unmatched group'
  913.                 continue
  914.     except IndexError:
  915.         raise error, 'invalid group reference'
  916.  
  917.     return sep.join(literals)
  918.  
  919.