home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1420 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  110.0 KB  |  3,573 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''
  5. pyparsing module - Classes and methods to define and execute parsing grammars
  6.  
  7. The pyparsing module is an alternative approach to creating and executing simple grammars,
  8. vs. the traditional lex/yacc approach, or the use of regular expressions.  With pyparsing, you
  9. don\'t need to learn a new syntax for defining grammars or matching expressions - the parsing module
  10. provides a library of classes that you use to construct the grammar directly in Python.
  11.  
  12. Here is a program to parse "Hello, World!" (or any greeting of the form "<salutation>, <addressee>!")::
  13.  
  14.     from pyparsing import Word, alphas
  15.  
  16.     # define grammar of a greeting
  17.     greet = Word( alphas ) + "," + Word( alphas ) + "!"
  18.  
  19.     hello = "Hello, World!"
  20.     print hello, "->", greet.parseString( hello )
  21.  
  22. The program outputs the following::
  23.  
  24.     Hello, World! -> [\'Hello\', \',\', \'World\', \'!\']
  25.  
  26. The Python representation of the grammar is quite readable, owing to the self-explanatory
  27. class names, and the use of \'+\', \'|\' and \'^\' operators.
  28.  
  29. The parsed results returned from parseString() can be accessed as a nested list, a dictionary, or an
  30. object with named attributes.
  31.  
  32. The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
  33.  - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello  ,  World  !", etc.)
  34.  - quoted strings
  35.  - embedded comments
  36. '''
  37. __version__ = '1.5.1'
  38. __versionTime__ = '2 October 2008 00:44'
  39. __author__ = 'Paul McGuire <ptmcg@users.sourceforge.net>'
  40. import string
  41. from weakref import ref as wkref
  42. import copy
  43. import sys
  44. import warnings
  45. import re
  46. import sre_constants
  47. __all__ = [
  48.     'And',
  49.     'CaselessKeyword',
  50.     'CaselessLiteral',
  51.     'CharsNotIn',
  52.     'Combine',
  53.     'Dict',
  54.     'Each',
  55.     'Empty',
  56.     'FollowedBy',
  57.     'Forward',
  58.     'GoToColumn',
  59.     'Group',
  60.     'Keyword',
  61.     'LineEnd',
  62.     'LineStart',
  63.     'Literal',
  64.     'MatchFirst',
  65.     'NoMatch',
  66.     'NotAny',
  67.     'OneOrMore',
  68.     'OnlyOnce',
  69.     'Optional',
  70.     'Or',
  71.     'ParseBaseException',
  72.     'ParseElementEnhance',
  73.     'ParseException',
  74.     'ParseExpression',
  75.     'ParseFatalException',
  76.     'ParseResults',
  77.     'ParseSyntaxException',
  78.     'ParserElement',
  79.     'QuotedString',
  80.     'RecursiveGrammarException',
  81.     'Regex',
  82.     'SkipTo',
  83.     'StringEnd',
  84.     'StringStart',
  85.     'Suppress',
  86.     'Token',
  87.     'TokenConverter',
  88.     'Upcase',
  89.     'White',
  90.     'Word',
  91.     'WordEnd',
  92.     'WordStart',
  93.     'ZeroOrMore',
  94.     'alphanums',
  95.     'alphas',
  96.     'alphas8bit',
  97.     'anyCloseTag',
  98.     'anyOpenTag',
  99.     'cStyleComment',
  100.     'col',
  101.     'commaSeparatedList',
  102.     'commonHTMLEntity',
  103.     'countedArray',
  104.     'cppStyleComment',
  105.     'dblQuotedString',
  106.     'dblSlashComment',
  107.     'delimitedList',
  108.     'dictOf',
  109.     'downcaseTokens',
  110.     'empty',
  111.     'getTokensEndLoc',
  112.     'hexnums',
  113.     'htmlComment',
  114.     'javaStyleComment',
  115.     'keepOriginalText',
  116.     'line',
  117.     'lineEnd',
  118.     'lineStart',
  119.     'lineno',
  120.     'makeHTMLTags',
  121.     'makeXMLTags',
  122.     'matchOnlyAtCol',
  123.     'matchPreviousExpr',
  124.     'matchPreviousLiteral',
  125.     'nestedExpr',
  126.     'nullDebugAction',
  127.     'nums',
  128.     'oneOf',
  129.     'opAssoc',
  130.     'operatorPrecedence',
  131.     'printables',
  132.     'punc8bit',
  133.     'pythonStyleComment',
  134.     'quotedString',
  135.     'removeQuotes',
  136.     'replaceHTMLEntity',
  137.     'replaceWith',
  138.     'restOfLine',
  139.     'sglQuotedString',
  140.     'srange',
  141.     'stringEnd',
  142.     'stringStart',
  143.     'traceParseAction',
  144.     'unicodeString',
  145.     'upcaseTokens',
  146.     'withAttribute',
  147.     'indentedBlock',
  148.     'originalTextFor']
  149. if sys.version_info[0] > 2:
  150.     _PY3K = True
  151.     _MAX_INT = sys.maxsize
  152.     basestring = str
  153. else:
  154.     _PY3K = False
  155.     _MAX_INT = sys.maxint
  156. if not _PY3K:
  157.     
  158.     def _ustr(obj):
  159.         
  160.         try:
  161.             return str(obj)
  162.         except UnicodeEncodeError:
  163.             return unicode(obj)
  164.  
  165.  
  166. else:
  167.     _ustr = str
  168.     unichr = chr
  169.  
  170. def _str2dict(strg):
  171.     return []([ (c, 0) for c in strg ])
  172.  
  173.  
  174. def _xml_escape(data):
  175.     from_symbols = '&><"\''
  176.     to_symbols = [ '&' + s + ';' for s in 'amp gt lt quot apos'.split() ]
  177.     for from_, to_ in zip(from_symbols, to_symbols):
  178.         data = data.replace(from_, to_)
  179.     
  180.     return data
  181.  
  182.  
  183. class _Constants(object):
  184.     pass
  185.  
  186. if not _PY3K:
  187.     alphas = string.lowercase + string.uppercase
  188. else:
  189.     alphas = string.ascii_lowercase + string.ascii_uppercase
  190. nums = string.digits
  191. hexnums = nums + 'ABCDEFabcdef'
  192. alphanums = alphas + nums
  193. _bslash = chr(92)
  194. printables = []([] if c not in string.whitespace else _[1])
  195.  
  196. class ParseBaseException(Exception):
  197.     __slots__ = ('loc', 'msg', 'pstr', 'parserElement')
  198.     
  199.     def __init__(self, pstr, loc = 0, msg = None, elem = None):
  200.         self.loc = loc
  201.         if msg is None:
  202.             self.msg = pstr
  203.             self.pstr = ''
  204.         else:
  205.             self.msg = msg
  206.             self.pstr = pstr
  207.         self.parserElement = elem
  208.  
  209.     
  210.     def __getattr__(self, aname):
  211.         if aname == 'lineno':
  212.             return lineno(self.loc, self.pstr)
  213.         if aname in ('col', 'column'):
  214.             return col(self.loc, self.pstr)
  215.         if aname == 'line':
  216.             return line(self.loc, self.pstr)
  217.         raise AttributeError(aname)
  218.  
  219.     
  220.     def __str__(self):
  221.         return '%s (at char %d), (line:%d, col:%d)' % (self.msg, self.loc, self.lineno, self.column)
  222.  
  223.     
  224.     def __repr__(self):
  225.         return _ustr(self)
  226.  
  227.     
  228.     def markInputline(self, markerString = '>!<'):
  229.         line_str = self.line
  230.         line_column = self.column - 1
  231.         if markerString:
  232.             line_str = ''.join([
  233.                 line_str[:line_column],
  234.                 markerString,
  235.                 line_str[line_column:]])
  236.         
  237.         return line_str.strip()
  238.  
  239.     
  240.     def __dir__(self):
  241.         return 'loc msg pstr parserElement lineno col line markInputLine __str__ __repr__'.split()
  242.  
  243.  
  244.  
  245. class ParseException(ParseBaseException):
  246.     pass
  247.  
  248.  
  249. class ParseFatalException(ParseBaseException):
  250.     pass
  251.  
  252.  
  253. class ParseSyntaxException(ParseFatalException):
  254.     
  255.     def __init__(self, pe):
  256.         super(ParseSyntaxException, self).__init__(pe.pstr, pe.loc, pe.msg, pe.parserElement)
  257.  
  258.  
  259.  
  260. class RecursiveGrammarException(Exception):
  261.     
  262.     def __init__(self, parseElementList):
  263.         self.parseElementTrace = parseElementList
  264.  
  265.     
  266.     def __str__(self):
  267.         return 'RecursiveGrammarException: %s' % self.parseElementTrace
  268.  
  269.  
  270.  
  271. class _ParseResultsWithOffset(object):
  272.     
  273.     def __init__(self, p1, p2):
  274.         self.tup = (p1, p2)
  275.  
  276.     
  277.     def __getitem__(self, i):
  278.         return self.tup[i]
  279.  
  280.     
  281.     def __repr__(self):
  282.         return repr(self.tup)
  283.  
  284.     
  285.     def setOffset(self, i):
  286.         self.tup = (self.tup[0], i)
  287.  
  288.  
  289.  
  290. class ParseResults(object):
  291.     __slots__ = ('__toklist', '__tokdict', '__doinit', '__name', '__parent', '__accumNames', '__weakref__')
  292.     
  293.     def __new__(cls, toklist, name = None, asList = True, modal = True):
  294.         if isinstance(toklist, cls):
  295.             return toklist
  296.         retobj = object.__new__(cls)
  297.         retobj._ParseResults__doinit = True
  298.         return retobj
  299.  
  300.     
  301.     def __init__(self, toklist, name = None, asList = True, modal = True):
  302.         if self._ParseResults__doinit:
  303.             self._ParseResults__doinit = False
  304.             self._ParseResults__name = None
  305.             self._ParseResults__parent = None
  306.             self._ParseResults__accumNames = { }
  307.             if isinstance(toklist, list):
  308.                 self._ParseResults__toklist = toklist[:]
  309.             else:
  310.                 self._ParseResults__toklist = [
  311.                     toklist]
  312.             self._ParseResults__tokdict = dict()
  313.         
  314.         if name:
  315.             if not modal:
  316.                 self._ParseResults__accumNames[name] = 0
  317.             
  318.             if isinstance(name, int):
  319.                 name = _ustr(name)
  320.             
  321.             self._ParseResults__name = name
  322.             if toklist not in (None, '', []):
  323.                 if isinstance(toklist, basestring):
  324.                     toklist = [
  325.                         toklist]
  326.                 
  327.             None if asList else None<EXCEPTION MATCH>(KeyError, TypeError)
  328.         
  329.  
  330.     
  331.     def __getitem__(self, i):
  332.         if isinstance(i, (int, slice)):
  333.             return self._ParseResults__toklist[i]
  334.         if i not in self._ParseResults__accumNames:
  335.             return self._ParseResults__tokdict[i][-1][0]
  336.         return []([ v[0] for v in self._ParseResults__tokdict[i] ])
  337.  
  338.     
  339.     def __setitem__(self, k, v):
  340.         if isinstance(v, _ParseResultsWithOffset):
  341.             self._ParseResults__tokdict[k] = self._ParseResults__tokdict.get(k, list()) + [
  342.                 v]
  343.             sub = v[0]
  344.         elif isinstance(k, int):
  345.             self._ParseResults__toklist[k] = v
  346.             sub = v
  347.         else:
  348.             self._ParseResults__tokdict[k] = self._ParseResults__tokdict.get(k, list()) + [
  349.                 _ParseResultsWithOffset(v, 0)]
  350.             sub = v
  351.         if isinstance(sub, ParseResults):
  352.             sub._ParseResults__parent = wkref(self)
  353.         
  354.  
  355.     
  356.     def __delitem__(self, i):
  357.         if isinstance(i, (int, slice)):
  358.             mylen = len(self._ParseResults__toklist)
  359.             del self._ParseResults__toklist[i]
  360.             if isinstance(i, int):
  361.                 if i < 0:
  362.                     i += mylen
  363.                 
  364.                 i = slice(i, i + 1)
  365.             
  366.             removed = list(range(*i.indices(mylen)))
  367.             removed.reverse()
  368.             for name in self._ParseResults__tokdict:
  369.                 occurrences = self._ParseResults__tokdict[name]
  370.                 for j in removed:
  371.                     for value, position in enumerate(occurrences):
  372.                         occurrences[k] = _ParseResultsWithOffset(value, position - (position > j))
  373.                     
  374.                 
  375.             
  376.         else:
  377.             del self._ParseResults__tokdict[i]
  378.  
  379.     
  380.     def __contains__(self, k):
  381.         return k in self._ParseResults__tokdict
  382.  
  383.     
  384.     def __len__(self):
  385.         return len(self._ParseResults__toklist)
  386.  
  387.     
  388.     def __bool__(self):
  389.         return len(self._ParseResults__toklist) > 0
  390.  
  391.     __nonzero__ = __bool__
  392.     
  393.     def __iter__(self):
  394.         return iter(self._ParseResults__toklist)
  395.  
  396.     
  397.     def __reversed__(self):
  398.         return iter(reversed(self._ParseResults__toklist))
  399.  
  400.     
  401.     def keys(self):
  402.         return self._ParseResults__tokdict.keys()
  403.  
  404.     
  405.     def pop(self, index = -1):
  406.         ret = self[index]
  407.         del self[index]
  408.         return ret
  409.  
  410.     
  411.     def get(self, key, defaultValue = None):
  412.         if key in self:
  413.             return self[key]
  414.         return defaultValue
  415.  
  416.     
  417.     def insert(self, index, insStr):
  418.         self._ParseResults__toklist.insert(index, insStr)
  419.         for name in self._ParseResults__tokdict:
  420.             occurrences = self._ParseResults__tokdict[name]
  421.             for value, position in enumerate(occurrences):
  422.                 occurrences[k] = _ParseResultsWithOffset(value, position + (position > index))
  423.             
  424.         
  425.  
  426.     
  427.     def items(self):
  428.         return [ (k, self[k]) for k in self._ParseResults__tokdict ]
  429.  
  430.     
  431.     def values(self):
  432.         return [ v[-1][0] for v in self._ParseResults__tokdict.values() ]
  433.  
  434.     
  435.     def __getattr__(self, name):
  436.         if name not in self.__slots__:
  437.             if name in self._ParseResults__tokdict:
  438.                 if name not in self._ParseResults__accumNames:
  439.                     return self._ParseResults__tokdict[name][-1][0]
  440.                 return []([ v[0] for v in self._ParseResults__tokdict[name] ])
  441.             name in self._ParseResults__tokdict
  442.             return ''
  443.         name not in self.__slots__
  444.  
  445.     
  446.     def __add__(self, other):
  447.         ret = self.copy()
  448.         ret += other
  449.         return ret
  450.  
  451.     
  452.     def __iadd__(self, other):
  453.         self._ParseResults__toklist += other._ParseResults__toklist
  454.         self._ParseResults__accumNames.update(other._ParseResults__accumNames)
  455.         del other
  456.         return self
  457.  
  458.     
  459.     def __repr__(self):
  460.         return '(%s, %s)' % (repr(self._ParseResults__toklist), repr(self._ParseResults__tokdict))
  461.  
  462.     
  463.     def __str__(self):
  464.         out = '['
  465.         sep = ''
  466.         for i in self._ParseResults__toklist:
  467.             if isinstance(i, ParseResults):
  468.                 out += sep + _ustr(i)
  469.             else:
  470.                 out += sep + repr(i)
  471.             sep = ', '
  472.         
  473.         out += ']'
  474.         return out
  475.  
  476.     
  477.     def _asStringList(self, sep = ''):
  478.         out = []
  479.         for item in self._ParseResults__toklist:
  480.             if out and sep:
  481.                 out.append(sep)
  482.             
  483.             if isinstance(item, ParseResults):
  484.                 out += item._asStringList()
  485.                 continue
  486.             out.append(_ustr(item))
  487.         
  488.         return out
  489.  
  490.     
  491.     def asList(self):
  492.         out = []
  493.         for res in self._ParseResults__toklist:
  494.             if isinstance(res, ParseResults):
  495.                 out.append(res.asList())
  496.                 continue
  497.             out.append(res)
  498.         
  499.         return out
  500.  
  501.     
  502.     def asDict(self):
  503.         return dict(self.items())
  504.  
  505.     
  506.     def copy(self):
  507.         ret = ParseResults(self._ParseResults__toklist)
  508.         ret._ParseResults__tokdict = self._ParseResults__tokdict.copy()
  509.         ret._ParseResults__parent = self._ParseResults__parent
  510.         ret._ParseResults__accumNames.update(self._ParseResults__accumNames)
  511.         ret._ParseResults__name = self._ParseResults__name
  512.         return ret
  513.  
  514.     
  515.     def asXML(self, doctag = None, namedItemsOnly = False, indent = '', formatted = True):
  516.         nl = '\n'
  517.         out = []
  518.         namedItems = []([ (v[1], k) for k, vlist in self._ParseResults__tokdict.items() for v in vlist ])
  519.         nextLevelIndent = indent + '  '
  520.         selfTag = None
  521.         if doctag is not None:
  522.             selfTag = doctag
  523.         elif self._ParseResults__name:
  524.             selfTag = self._ParseResults__name
  525.         
  526.         if not selfTag:
  527.             if namedItemsOnly:
  528.                 return ''
  529.             selfTag = 'ITEM'
  530.         
  531.         out += [
  532.             nl,
  533.             indent,
  534.             '<',
  535.             selfTag,
  536.             '>']
  537.         worklist = self._ParseResults__toklist
  538.         for i, res in enumerate(worklist):
  539.             if isinstance(res, ParseResults):
  540.                 if i in namedItems:
  541.                     if namedItemsOnly:
  542.                         pass
  543.                     out += [
  544.                         res.asXML(namedItems[i], doctag is None, nextLevelIndent, formatted)]
  545.                 elif namedItemsOnly:
  546.                     pass
  547.                 out += [
  548.                     res.asXML(None, doctag is None, nextLevelIndent, formatted)]
  549.                 continue
  550.             resTag = None
  551.             if i in namedItems:
  552.                 resTag = namedItems[i]
  553.             
  554.             if not resTag:
  555.                 if namedItemsOnly:
  556.                     continue
  557.                 else:
  558.                     resTag = 'ITEM'
  559.             
  560.             xmlBodyText = _xml_escape(_ustr(res))
  561.             out += [
  562.                 nl,
  563.                 nextLevelIndent,
  564.                 '<',
  565.                 resTag,
  566.                 '>',
  567.                 xmlBodyText,
  568.                 '</',
  569.                 resTag,
  570.                 '>']
  571.         
  572.         out += [
  573.             nl,
  574.             indent,
  575.             '</',
  576.             selfTag,
  577.             '>']
  578.         return ''.join(out)
  579.  
  580.     
  581.     def __lookup(self, sub):
  582.         for k, vlist in self._ParseResults__tokdict.items():
  583.             for v, loc in vlist:
  584.                 if sub is v:
  585.                     return k
  586.             
  587.         
  588.  
  589.     
  590.     def getName(self):
  591.         if self._ParseResults__name:
  592.             return self._ParseResults__name
  593.         if self._ParseResults__parent:
  594.             par = self._ParseResults__parent()
  595.             if par:
  596.                 return par._ParseResults__lookup(self)
  597.             return None
  598.         self._ParseResults__parent
  599.         if len(self) == 1 and len(self._ParseResults__tokdict) == 1 and self._ParseResults__tokdict.values()[0][0][1] in (0, -1):
  600.             return self._ParseResults__tokdict.keys()[0]
  601.         return None
  602.  
  603.     
  604.     def dump(self, indent = '', depth = 0):
  605.         out = []
  606.         out.append(indent + _ustr(self.asList()))
  607.         keys = self.items()
  608.         keys.sort()
  609.         for k, v in keys:
  610.             if out:
  611.                 out.append('\n')
  612.             
  613.             out.append('%s%s- %s: ' % (indent, '  ' * depth, k))
  614.             if isinstance(v, ParseResults):
  615.                 if v.keys():
  616.                     out.append(v.dump(indent, depth + 1))
  617.                 else:
  618.                     out.append(_ustr(v))
  619.             v.keys()
  620.             out.append(_ustr(v))
  621.         
  622.         return ''.join(out)
  623.  
  624.     
  625.     def __getstate__(self):
  626.         if not self._ParseResults__parent is not None or self._ParseResults__parent():
  627.             pass
  628.         return (self._ParseResults__toklist, (self._ParseResults__tokdict.copy(), None, self._ParseResults__accumNames, self._ParseResults__name))
  629.  
  630.     
  631.     def __setstate__(self, state):
  632.         self._ParseResults__toklist = state[0]
  633.         (self._ParseResults__tokdict, par, inAccumNames, self._ParseResults__name) = state[1]
  634.         self._ParseResults__accumNames = { }
  635.         self._ParseResults__accumNames.update(inAccumNames)
  636.         if par is not None:
  637.             self._ParseResults__parent = wkref(par)
  638.         else:
  639.             self._ParseResults__parent = None
  640.  
  641.     
  642.     def __dir__(self):
  643.         return dir(super(ParseResults, self)) + self.keys()
  644.  
  645.  
  646.  
  647. def col(loc, strg):
  648.     if not loc < len(strg) or strg[loc] == '\n' or 1:
  649.         pass
  650.     return loc - strg.rfind('\n', 0, loc)
  651.  
  652.  
  653. def lineno(loc, strg):
  654.     return strg.count('\n', 0, loc) + 1
  655.  
  656.  
  657. def line(loc, strg):
  658.     lastCR = strg.rfind('\n', 0, loc)
  659.     nextCR = strg.find('\n', loc)
  660.     if nextCR > 0:
  661.         return strg[lastCR + 1:nextCR]
  662.     return strg[lastCR + 1:]
  663.  
  664.  
  665. def _defaultStartDebugAction(instring, loc, expr):
  666.     print 'Match ' + _ustr(expr) + ' at loc ' + _ustr(loc) + '(%d,%d)' % (lineno(loc, instring), col(loc, instring))
  667.  
  668.  
  669. def _defaultSuccessDebugAction(instring, startloc, endloc, expr, toks):
  670.     print 'Matched ' + _ustr(expr) + ' -> ' + str(toks.asList())
  671.  
  672.  
  673. def _defaultExceptionDebugAction(instring, loc, expr, exc):
  674.     print 'Exception raised:' + _ustr(exc)
  675.  
  676.  
  677. def nullDebugAction(*args):
  678.     pass
  679.  
  680.  
  681. class ParserElement(object):
  682.     DEFAULT_WHITE_CHARS = ' \n\t\r'
  683.     
  684.     def setDefaultWhitespaceChars(chars):
  685.         ParserElement.DEFAULT_WHITE_CHARS = chars
  686.  
  687.     setDefaultWhitespaceChars = staticmethod(setDefaultWhitespaceChars)
  688.     
  689.     def __init__(self, savelist = False):
  690.         self.parseAction = list()
  691.         self.failAction = None
  692.         self.strRepr = None
  693.         self.resultsName = None
  694.         self.saveAsList = savelist
  695.         self.skipWhitespace = True
  696.         self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
  697.         self.copyDefaultWhiteChars = True
  698.         self.mayReturnEmpty = False
  699.         self.keepTabs = False
  700.         self.ignoreExprs = list()
  701.         self.debug = False
  702.         self.streamlined = False
  703.         self.mayIndexError = True
  704.         self.errmsg = ''
  705.         self.modalResults = True
  706.         self.debugActions = (None, None, None)
  707.         self.re = None
  708.         self.callPreparse = True
  709.         self.callDuringTry = False
  710.  
  711.     
  712.     def copy(self):
  713.         cpy = copy.copy(self)
  714.         cpy.parseAction = self.parseAction[:]
  715.         cpy.ignoreExprs = self.ignoreExprs[:]
  716.         if self.copyDefaultWhiteChars:
  717.             cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
  718.         
  719.         return cpy
  720.  
  721.     
  722.     def setName(self, name):
  723.         self.name = name
  724.         self.errmsg = 'Expected ' + self.name
  725.         if hasattr(self, 'exception'):
  726.             self.exception.msg = self.errmsg
  727.         
  728.         return self
  729.  
  730.     
  731.     def setResultsName(self, name, listAllMatches = False):
  732.         newself = self.copy()
  733.         newself.resultsName = name
  734.         newself.modalResults = not listAllMatches
  735.         return newself
  736.  
  737.     
  738.     def setBreak(self, breakFlag = True):
  739.         if breakFlag:
  740.             _parseMethod = self._parse
  741.             
  742.             def breaker(instring, loc, doActions = True, callPreParse = (True,)):
  743.                 import pdb
  744.                 pdb.set_trace()
  745.                 return _parseMethod(instring, loc, doActions, callPreParse)
  746.  
  747.             breaker._originalParseMethod = _parseMethod
  748.             self._parse = breaker
  749.         elif hasattr(self._parse, '_originalParseMethod'):
  750.             self._parse = self._parse._originalParseMethod
  751.         
  752.         return self
  753.  
  754.     
  755.     def _normalizeParseActionArgs(f):
  756.         STAR_ARGS = 4
  757.         
  758.         try:
  759.             restore = None
  760.             if isinstance(f, type):
  761.                 restore = f
  762.                 f = f.__init__
  763.             
  764.             if not _PY3K:
  765.                 codeObj = f.func_code
  766.             else:
  767.                 codeObj = f.code
  768.             if codeObj.co_flags & STAR_ARGS:
  769.                 return f
  770.             numargs = codeObj.co_argcount
  771.             if not _PY3K:
  772.                 if hasattr(f, 'im_self'):
  773.                     numargs -= 1
  774.                 
  775.             elif hasattr(f, '__self__'):
  776.                 numargs -= 1
  777.             
  778.             if restore:
  779.                 f = restore
  780.         except AttributeError:
  781.             
  782.             try:
  783.                 if not _PY3K:
  784.                     call_im_func_code = f.__call__.im_func.func_code
  785.                 else:
  786.                     call_im_func_code = f.__code__
  787.                 if call_im_func_code.co_flags & STAR_ARGS:
  788.                     return f
  789.                 numargs = call_im_func_code.co_argcount
  790.                 if not _PY3K:
  791.                     if hasattr(f.__call__, 'im_self'):
  792.                         numargs -= 1
  793.                     
  794.                 elif hasattr(f.__call__, '__self__'):
  795.                     numargs -= 0
  796.             except AttributeError:
  797.                 if not _PY3K:
  798.                     call_func_code = f.__call__.func_code
  799.                 else:
  800.                     call_func_code = f.__call__.__code__
  801.                 if call_func_code.co_flags & STAR_ARGS:
  802.                     return f
  803.                 numargs = call_func_code.co_argcount
  804.                 if not _PY3K:
  805.                     if hasattr(f.__call__, 'im_self'):
  806.                         numargs -= 1
  807.                     
  808.                 elif hasattr(f.__call__, '__self__'):
  809.                     numargs -= 1
  810.                 
  811.             except:
  812.                 _PY3K
  813.             
  814.  
  815.             call_func_code.co_flags & STAR_ARGS
  816.  
  817.         if numargs == 3:
  818.             return f
  819.         if numargs > 3:
  820.             
  821.             def tmp(s, l, t):
  822.                 return f(f.__call__.__self__, s, l, t)
  823.  
  824.         
  825.         if numargs == 2:
  826.             
  827.             def tmp(s, l, t):
  828.                 return f(l, t)
  829.  
  830.         elif numargs == 1:
  831.             
  832.             def tmp(s, l, t):
  833.                 return f(t)
  834.  
  835.         else:
  836.             
  837.             def tmp(s, l, t):
  838.                 return f()
  839.  
  840.         
  841.         try:
  842.             tmp.__name__ = f.__name__
  843.         except (AttributeError, TypeError):
  844.             (None,)
  845.             (None,)
  846.         except:
  847.             (None,)
  848.  
  849.         
  850.         try:
  851.             tmp.__doc__ = f.__doc__
  852.         except (AttributeError, TypeError):
  853.             (None,)
  854.             (None,)
  855.         except:
  856.             (None,)
  857.  
  858.         
  859.         try:
  860.             tmp.__dict__.update(f.__dict__)
  861.         except (AttributeError, TypeError):
  862.             (None,)
  863.             (None,)
  864.         except:
  865.             (None,)
  866.  
  867.         return tmp
  868.  
  869.     _normalizeParseActionArgs = staticmethod(_normalizeParseActionArgs)
  870.     
  871.     def setParseAction(self, *fns, **kwargs):
  872.         self.parseAction = list(map(self._normalizeParseActionArgs, list(fns)))
  873.         if 'callDuringTry' in kwargs:
  874.             pass
  875.         self.callDuringTry = kwargs['callDuringTry']
  876.         return self
  877.  
  878.     
  879.     def addParseAction(self, *fns, **kwargs):
  880.         self.parseAction += list(map(self._normalizeParseActionArgs, list(fns)))
  881.         if self.callDuringTry and 'callDuringTry' in kwargs:
  882.             pass
  883.         self.callDuringTry = kwargs['callDuringTry']
  884.         return self
  885.  
  886.     
  887.     def setFailAction(self, fn):
  888.         self.failAction = fn
  889.         return self
  890.  
  891.     
  892.     def _skipIgnorables(self, instring, loc):
  893.         exprsFound = True
  894.         while exprsFound:
  895.             exprsFound = False
  896.             for e in self.ignoreExprs:
  897.                 
  898.                 try:
  899.                     while None:
  900.                         (loc, dummy) = e._parse(instring, loc)
  901.                         exprsFound = True
  902.                     continue
  903.                     except ParseException:
  904.                         continue
  905.                     
  906.                 continue
  907.                 return loc
  908.  
  909.  
  910.     
  911.     def preParse(self, instring, loc):
  912.         if self.ignoreExprs:
  913.             loc = self._skipIgnorables(instring, loc)
  914.         
  915.         if self.skipWhitespace:
  916.             wt = self.whiteChars
  917.             instrlen = len(instring)
  918.             while loc < instrlen and instring[loc] in wt:
  919.                 loc += 1
  920.         
  921.         return loc
  922.  
  923.     
  924.     def parseImpl(self, instring, loc, doActions = True):
  925.         return (loc, [])
  926.  
  927.     
  928.     def postParse(self, instring, loc, tokenlist):
  929.         return tokenlist
  930.  
  931.     
  932.     def _parseNoCache(self, instring, loc, doActions = True, callPreParse = True):
  933.         debugging = self.debug
  934.         if debugging or self.failAction:
  935.             if self.debugActions[0]:
  936.                 self.debugActions[0](instring, loc, self)
  937.             
  938.             if callPreParse and self.callPreparse:
  939.                 preloc = self.preParse(instring, loc)
  940.             else:
  941.                 preloc = loc
  942.             tokensStart = loc
  943.             
  944.             try:
  945.                 
  946.                 try:
  947.                     (loc, tokens) = self.parseImpl(instring, preloc, doActions)
  948.                 except IndexError:
  949.                     raise ParseException(instring, len(instring), self.errmsg, self)
  950.  
  951.             except ParseBaseException:
  952.                 err = None
  953.                 if self.debugActions[2]:
  954.                     self.debugActions[2](instring, tokensStart, self, err)
  955.                 
  956.                 if self.failAction:
  957.                     self.failAction(instring, tokensStart, self, err)
  958.                 
  959.                 raise 
  960.             except:
  961.                 None<EXCEPTION MATCH>ParseBaseException
  962.             
  963.  
  964.         None<EXCEPTION MATCH>ParseBaseException
  965.         if callPreParse and self.callPreparse:
  966.             preloc = self.preParse(instring, loc)
  967.         else:
  968.             preloc = loc
  969.         tokensStart = loc
  970.         if self.mayIndexError or loc >= len(instring):
  971.             
  972.             try:
  973.                 (loc, tokens) = self.parseImpl(instring, preloc, doActions)
  974.             except IndexError:
  975.                 raise ParseException(instring, len(instring), self.errmsg, self)
  976.             except:
  977.                 None<EXCEPTION MATCH>IndexError
  978.             
  979.  
  980.         None<EXCEPTION MATCH>IndexError
  981.         (loc, tokens) = self.parseImpl(instring, preloc, doActions)
  982.         tokens = self.postParse(instring, loc, tokens)
  983.         retTokens = ParseResults(tokens, self.resultsName, asList = self.saveAsList, modal = self.modalResults)
  984.         if self.parseAction:
  985.             if doActions or self.callDuringTry:
  986.                 if debugging:
  987.                     
  988.                     try:
  989.                         for fn in self.parseAction:
  990.                             tokens = fn(instring, tokensStart, retTokens)
  991.                             if tokens is not None:
  992.                                 if self.saveAsList:
  993.                                     pass
  994.                                 retTokens = ParseResults(tokens, self.resultsName, asList = isinstance(tokens, (ParseResults, list)), modal = self.modalResults)
  995.                                 continue
  996.                     except ParseBaseException:
  997.                         err = None
  998.                         if self.debugActions[2]:
  999.                             self.debugActions[2](instring, tokensStart, self, err)
  1000.                         
  1001.                         raise 
  1002.                     except:
  1003.                         None<EXCEPTION MATCH>ParseBaseException
  1004.                     
  1005.  
  1006.                 None<EXCEPTION MATCH>ParseBaseException
  1007.                 for fn in self.parseAction:
  1008.                     tokens = fn(instring, tokensStart, retTokens)
  1009.                     if tokens is not None:
  1010.                         if self.saveAsList:
  1011.                             pass
  1012.                         retTokens = ParseResults(tokens, self.resultsName, asList = isinstance(tokens, (ParseResults, list)), modal = self.modalResults)
  1013.                         continue
  1014.                 
  1015.             
  1016.         if debugging:
  1017.             if self.debugActions[1]:
  1018.                 self.debugActions[1](instring, tokensStart, loc, self, retTokens)
  1019.             
  1020.         
  1021.         return (loc, retTokens)
  1022.  
  1023.     
  1024.     def tryParse(self, instring, loc):
  1025.         
  1026.         try:
  1027.             return self._parse(instring, loc, doActions = False)[0]
  1028.         except ParseFatalException:
  1029.             raise ParseException(instring, loc, self.errmsg, self)
  1030.  
  1031.  
  1032.     
  1033.     def _parseCache(self, instring, loc, doActions = True, callPreParse = True):
  1034.         lookup = (self, instring, loc, callPreParse, doActions)
  1035.         if lookup in ParserElement._exprArgCache:
  1036.             value = ParserElement._exprArgCache[lookup]
  1037.             if isinstance(value, Exception):
  1038.                 raise value
  1039.             isinstance(value, Exception)
  1040.             return value
  1041.         
  1042.         try:
  1043.             value = self._parseNoCache(instring, loc, doActions, callPreParse)
  1044.             ParserElement._exprArgCache[lookup] = (value[0], value[1].copy())
  1045.             return value
  1046.         except ParseBaseException:
  1047.             lookup in ParserElement._exprArgCache
  1048.             pe = lookup in ParserElement._exprArgCache
  1049.             ParserElement._exprArgCache[lookup] = pe
  1050.             raise 
  1051.         except:
  1052.             lookup in ParserElement._exprArgCache
  1053.  
  1054.  
  1055.     _parse = _parseNoCache
  1056.     _exprArgCache = { }
  1057.     
  1058.     def resetCache():
  1059.         ParserElement._exprArgCache.clear()
  1060.  
  1061.     resetCache = staticmethod(resetCache)
  1062.     _packratEnabled = False
  1063.     
  1064.     def enablePackrat():
  1065.         if not ParserElement._packratEnabled:
  1066.             ParserElement._packratEnabled = True
  1067.             ParserElement._parse = ParserElement._parseCache
  1068.         
  1069.  
  1070.     enablePackrat = staticmethod(enablePackrat)
  1071.     
  1072.     def parseString(self, instring, parseAll = False):
  1073.         ParserElement.resetCache()
  1074.         if not self.streamlined:
  1075.             self.streamline()
  1076.         
  1077.         for e in self.ignoreExprs:
  1078.             e.streamline()
  1079.         
  1080.         if not self.keepTabs:
  1081.             instring = instring.expandtabs()
  1082.         
  1083.         (loc, tokens) = self._parse(instring, 0)
  1084.         if parseAll:
  1085.             loc = self.preParse(instring, loc)
  1086.             StringEnd()._parse(instring, loc)
  1087.         
  1088.         return tokens
  1089.  
  1090.     
  1091.     def scanString(self, instring, maxMatches = _MAX_INT):
  1092.         if not self.streamlined:
  1093.             self.streamline()
  1094.         
  1095.         for e in self.ignoreExprs:
  1096.             e.streamline()
  1097.         
  1098.         if not self.keepTabs:
  1099.             instring = _ustr(instring).expandtabs()
  1100.         
  1101.         instrlen = len(instring)
  1102.         loc = 0
  1103.         preparseFn = self.preParse
  1104.         parseFn = self._parse
  1105.         ParserElement.resetCache()
  1106.         matches = 0
  1107.         while loc <= instrlen and matches < maxMatches:
  1108.             
  1109.             try:
  1110.                 preloc = preparseFn(instring, loc)
  1111.                 (nextLoc, tokens) = parseFn(instring, preloc, callPreParse = False)
  1112.             except ParseException:
  1113.                 loc = preloc + 1
  1114.                 continue
  1115.  
  1116.             matches += 1
  1117.             yield (tokens, preloc, nextLoc)
  1118.             loc = nextLoc
  1119.  
  1120.     
  1121.     def transformString(self, instring):
  1122.         out = []
  1123.         lastE = 0
  1124.         self.keepTabs = True
  1125.         for t, s, e in self.scanString(instring):
  1126.             out.append(instring[lastE:s])
  1127.             if t:
  1128.                 if isinstance(t, ParseResults):
  1129.                     out += t.asList()
  1130.                 elif isinstance(t, list):
  1131.                     out += t
  1132.                 else:
  1133.                     out.append(t)
  1134.             
  1135.             lastE = e
  1136.         
  1137.         out.append(instring[lastE:])
  1138.         return ''.join(map(_ustr, out))
  1139.  
  1140.     
  1141.     def searchString(self, instring, maxMatches = _MAX_INT):
  1142.         return []([ t for t, s, e in self.scanString(instring, maxMatches) ])
  1143.  
  1144.     
  1145.     def __add__(self, other):
  1146.         if isinstance(other, basestring):
  1147.             other = Literal(other)
  1148.         
  1149.         if not isinstance(other, ParserElement):
  1150.             warnings.warn('Cannot combine element of type %s with ParserElement' % type(other), SyntaxWarning, stacklevel = 2)
  1151.             return None
  1152.         return And([
  1153.             self,
  1154.             other])
  1155.  
  1156.     
  1157.     def __radd__(self, other):
  1158.         if isinstance(other, basestring):
  1159.             other = Literal(other)
  1160.         
  1161.         if not isinstance(other, ParserElement):
  1162.             warnings.warn('Cannot combine element of type %s with ParserElement' % type(other), SyntaxWarning, stacklevel = 2)
  1163.             return None
  1164.         return other + self
  1165.  
  1166.     
  1167.     def __sub__(self, other):
  1168.         if isinstance(other, basestring):
  1169.             other = Literal(other)
  1170.         
  1171.         if not isinstance(other, ParserElement):
  1172.             warnings.warn('Cannot combine element of type %s with ParserElement' % type(other), SyntaxWarning, stacklevel = 2)
  1173.             return None
  1174.         return And([
  1175.             self,
  1176.             And._ErrorStop(),
  1177.             other])
  1178.  
  1179.     
  1180.     def __rsub__(self, other):
  1181.         if isinstance(other, basestring):
  1182.             other = Literal(other)
  1183.         
  1184.         if not isinstance(other, ParserElement):
  1185.             warnings.warn('Cannot combine element of type %s with ParserElement' % type(other), SyntaxWarning, stacklevel = 2)
  1186.             return None
  1187.         return other - self
  1188.  
  1189.     
  1190.     def __mul__(self, other):
  1191.         if isinstance(other, int):
  1192.             minElements = other
  1193.             optElements = 0
  1194.         elif isinstance(other, tuple):
  1195.             other = other + (None, None)[:2]
  1196.             if other[0] is None:
  1197.                 other = (0, other[1])
  1198.             
  1199.             if isinstance(other[0], int) and other[1] is None:
  1200.                 if other[0] == 0:
  1201.                     return ZeroOrMore(self)
  1202.                 if other[0] == 1:
  1203.                     return OneOrMore(self)
  1204.                 return self * other[0] + ZeroOrMore(self)
  1205.             other[1] is None
  1206.             if isinstance(other[0], int) and isinstance(other[1], int):
  1207.                 (minElements, optElements) = other
  1208.                 optElements -= minElements
  1209.             else:
  1210.                 raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]), type(other[1]))
  1211.         isinstance(other[1], int)
  1212.         raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
  1213.         if minElements < 0:
  1214.             raise ValueError('cannot multiply ParserElement by negative value')
  1215.         minElements < 0
  1216.         if optElements < 0:
  1217.             raise ValueError('second tuple value must be greater or equal to first tuple value')
  1218.         optElements < 0
  1219.         if optElements == optElements:
  1220.             pass
  1221.         elif optElements == 0:
  1222.             raise ValueError('cannot multiply ParserElement by 0 or (0,0)')
  1223.         
  1224.         if optElements:
  1225.             
  1226.             def makeOptionalList(n):
  1227.                 if n > 1:
  1228.                     return Optional(self + makeOptionalList(n - 1))
  1229.                 return Optional(self)
  1230.  
  1231.             if minElements:
  1232.                 if minElements == 1:
  1233.                     ret = self + makeOptionalList(optElements)
  1234.                 else:
  1235.                     ret = And([
  1236.                         self] * minElements) + makeOptionalList(optElements)
  1237.             else:
  1238.                 ret = makeOptionalList(optElements)
  1239.         elif minElements == 1:
  1240.             ret = self
  1241.         else:
  1242.             ret = And([
  1243.                 self] * minElements)
  1244.         return ret
  1245.  
  1246.     
  1247.     def __rmul__(self, other):
  1248.         return self.__mul__(other)
  1249.  
  1250.     
  1251.     def __or__(self, other):
  1252.         if isinstance(other, basestring):
  1253.             other = Literal(other)
  1254.         
  1255.         if not isinstance(other, ParserElement):
  1256.             warnings.warn('Cannot combine element of type %s with ParserElement' % type(other), SyntaxWarning, stacklevel = 2)
  1257.             return None
  1258.         return MatchFirst([
  1259.             self,
  1260.             other])
  1261.  
  1262.     
  1263.     def __ror__(self, other):
  1264.         if isinstance(other, basestring):
  1265.             other = Literal(other)
  1266.         
  1267.         if not isinstance(other, ParserElement):
  1268.             warnings.warn('Cannot combine element of type %s with ParserElement' % type(other), SyntaxWarning, stacklevel = 2)
  1269.             return None
  1270.         return other | self
  1271.  
  1272.     
  1273.     def __xor__(self, other):
  1274.         if isinstance(other, basestring):
  1275.             other = Literal(other)
  1276.         
  1277.         if not isinstance(other, ParserElement):
  1278.             warnings.warn('Cannot combine element of type %s with ParserElement' % type(other), SyntaxWarning, stacklevel = 2)
  1279.             return None
  1280.         return Or([
  1281.             self,
  1282.             other])
  1283.  
  1284.     
  1285.     def __rxor__(self, other):
  1286.         if isinstance(other, basestring):
  1287.             other = Literal(other)
  1288.         
  1289.         if not isinstance(other, ParserElement):
  1290.             warnings.warn('Cannot combine element of type %s with ParserElement' % type(other), SyntaxWarning, stacklevel = 2)
  1291.             return None
  1292.         return other ^ self
  1293.  
  1294.     
  1295.     def __and__(self, other):
  1296.         if isinstance(other, basestring):
  1297.             other = Literal(other)
  1298.         
  1299.         if not isinstance(other, ParserElement):
  1300.             warnings.warn('Cannot combine element of type %s with ParserElement' % type(other), SyntaxWarning, stacklevel = 2)
  1301.             return None
  1302.         return Each([
  1303.             self,
  1304.             other])
  1305.  
  1306.     
  1307.     def __rand__(self, other):
  1308.         if isinstance(other, basestring):
  1309.             other = Literal(other)
  1310.         
  1311.         if not isinstance(other, ParserElement):
  1312.             warnings.warn('Cannot combine element of type %s with ParserElement' % type(other), SyntaxWarning, stacklevel = 2)
  1313.             return None
  1314.         return other & self
  1315.  
  1316.     
  1317.     def __invert__(self):
  1318.         return NotAny(self)
  1319.  
  1320.     
  1321.     def __call__(self, name):
  1322.         return self.setResultsName(name)
  1323.  
  1324.     
  1325.     def suppress(self):
  1326.         return Suppress(self)
  1327.  
  1328.     
  1329.     def leaveWhitespace(self):
  1330.         self.skipWhitespace = False
  1331.         return self
  1332.  
  1333.     
  1334.     def setWhitespaceChars(self, chars):
  1335.         self.skipWhitespace = True
  1336.         self.whiteChars = chars
  1337.         self.copyDefaultWhiteChars = False
  1338.         return self
  1339.  
  1340.     
  1341.     def parseWithTabs(self):
  1342.         self.keepTabs = True
  1343.         return self
  1344.  
  1345.     
  1346.     def ignore(self, other):
  1347.         if isinstance(other, Suppress):
  1348.             if other not in self.ignoreExprs:
  1349.                 self.ignoreExprs.append(other)
  1350.             
  1351.         else:
  1352.             self.ignoreExprs.append(Suppress(other))
  1353.         return self
  1354.  
  1355.     
  1356.     def setDebugActions(self, startAction, successAction, exceptionAction):
  1357.         if not startAction:
  1358.             pass
  1359.         if not successAction:
  1360.             pass
  1361.         if not exceptionAction:
  1362.             pass
  1363.         self.debugActions = (_defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction)
  1364.         self.debug = True
  1365.         return self
  1366.  
  1367.     
  1368.     def setDebug(self, flag = True):
  1369.         if flag:
  1370.             self.setDebugActions(_defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction)
  1371.         else:
  1372.             self.debug = False
  1373.         return self
  1374.  
  1375.     
  1376.     def __str__(self):
  1377.         return self.name
  1378.  
  1379.     
  1380.     def __repr__(self):
  1381.         return _ustr(self)
  1382.  
  1383.     
  1384.     def streamline(self):
  1385.         self.streamlined = True
  1386.         self.strRepr = None
  1387.         return self
  1388.  
  1389.     
  1390.     def checkRecursion(self, parseElementList):
  1391.         pass
  1392.  
  1393.     
  1394.     def validate(self, validateTrace = []):
  1395.         self.checkRecursion([])
  1396.  
  1397.     
  1398.     def parseFile(self, file_or_filename, parseAll = False):
  1399.         
  1400.         try:
  1401.             file_contents = file_or_filename.read()
  1402.         except AttributeError:
  1403.             f = open(file_or_filename, 'rb')
  1404.             file_contents = f.read()
  1405.             f.close()
  1406.  
  1407.         return self.parseString(file_contents, parseAll)
  1408.  
  1409.     
  1410.     def getException(self):
  1411.         return ParseException('', 0, self.errmsg, self)
  1412.  
  1413.     
  1414.     def __getattr__(self, aname):
  1415.         if aname == 'myException':
  1416.             self.myException = ret = self.getException()
  1417.             return ret
  1418.         raise AttributeError('no such attribute ' + aname)
  1419.  
  1420.     
  1421.     def __eq__(self, other):
  1422.         if isinstance(other, basestring):
  1423.             
  1424.             try:
  1425.                 (self + StringEnd()).parseString(_ustr(other))
  1426.                 return True
  1427.             except ParseBaseException:
  1428.                 return False
  1429.             
  1430.  
  1431.         None<EXCEPTION MATCH>ParseBaseException
  1432.         return super(ParserElement, self) == other
  1433.  
  1434.     
  1435.     def __ne__(self, other):
  1436.         return not (self == other)
  1437.  
  1438.     
  1439.     def __hash__(self):
  1440.         return hash(id(self))
  1441.  
  1442.     
  1443.     def __req__(self, other):
  1444.         return self == other
  1445.  
  1446.     
  1447.     def __rne__(self, other):
  1448.         return not (self == other)
  1449.  
  1450.  
  1451.  
  1452. class Token(ParserElement):
  1453.     
  1454.     def __init__(self):
  1455.         super(Token, self).__init__(savelist = False)
  1456.  
  1457.     
  1458.     def setName(self, name):
  1459.         s = super(Token, self).setName(name)
  1460.         self.errmsg = 'Expected ' + self.name
  1461.         return s
  1462.  
  1463.  
  1464.  
  1465. class Empty(Token):
  1466.     
  1467.     def __init__(self):
  1468.         super(Empty, self).__init__()
  1469.         self.name = 'Empty'
  1470.         self.mayReturnEmpty = True
  1471.         self.mayIndexError = False
  1472.  
  1473.  
  1474.  
  1475. class NoMatch(Token):
  1476.     
  1477.     def __init__(self):
  1478.         super(NoMatch, self).__init__()
  1479.         self.name = 'NoMatch'
  1480.         self.mayReturnEmpty = True
  1481.         self.mayIndexError = False
  1482.         self.errmsg = 'Unmatchable token'
  1483.  
  1484.     
  1485.     def parseImpl(self, instring, loc, doActions = True):
  1486.         exc = self.myException
  1487.         exc.loc = loc
  1488.         exc.pstr = instring
  1489.         raise exc
  1490.  
  1491.  
  1492.  
  1493. class Literal(Token):
  1494.     
  1495.     def __init__(self, matchString):
  1496.         super(Literal, self).__init__()
  1497.         self.match = matchString
  1498.         self.matchLen = len(matchString)
  1499.         
  1500.         try:
  1501.             self.firstMatchChar = matchString[0]
  1502.         except IndexError:
  1503.             warnings.warn('null string passed to Literal; use Empty() instead', SyntaxWarning, stacklevel = 2)
  1504.             self.__class__ = Empty
  1505.  
  1506.         self.name = '"%s"' % _ustr(self.match)
  1507.         self.errmsg = 'Expected ' + self.name
  1508.         self.mayReturnEmpty = False
  1509.         self.mayIndexError = False
  1510.  
  1511.     
  1512.     def parseImpl(self, instring, loc, doActions = True):
  1513.         if instring[loc] == self.firstMatchChar:
  1514.             if self.matchLen == 1 or instring.startswith(self.match, loc):
  1515.                 return (loc + self.matchLen, self.match)
  1516.             exc = self.myException
  1517.             exc.loc = loc
  1518.             exc.pstr = instring
  1519.             raise exc
  1520.         return instring[loc] == self.firstMatchChar
  1521.  
  1522.  
  1523. _L = Literal
  1524.  
  1525. class Keyword(Token):
  1526.     DEFAULT_KEYWORD_CHARS = alphanums + '_$'
  1527.     
  1528.     def __init__(self, matchString, identChars = DEFAULT_KEYWORD_CHARS, caseless = False):
  1529.         super(Keyword, self).__init__()
  1530.         self.match = matchString
  1531.         self.matchLen = len(matchString)
  1532.         
  1533.         try:
  1534.             self.firstMatchChar = matchString[0]
  1535.         except IndexError:
  1536.             warnings.warn('null string passed to Keyword; use Empty() instead', SyntaxWarning, stacklevel = 2)
  1537.  
  1538.         self.name = '"%s"' % self.match
  1539.         self.errmsg = 'Expected ' + self.name
  1540.         self.mayReturnEmpty = False
  1541.         self.mayIndexError = False
  1542.         self.caseless = caseless
  1543.         if caseless:
  1544.             self.caselessmatch = matchString.upper()
  1545.             identChars = identChars.upper()
  1546.         
  1547.         self.identChars = _str2dict(identChars)
  1548.  
  1549.     
  1550.     def parseImpl(self, instring, loc, doActions = True):
  1551.         if self.caseless:
  1552.             if instring[loc:loc + self.matchLen].upper() == self.caselessmatch:
  1553.                 if loc >= len(instring) - self.matchLen or instring[loc + self.matchLen].upper() not in self.identChars:
  1554.                     if loc == 0 or instring[loc - 1].upper() not in self.identChars:
  1555.                         return (loc + self.matchLen, self.match)
  1556.                 elif instring[loc] == self.firstMatchChar:
  1557.                     if self.matchLen == 1 or instring.startswith(self.match, loc):
  1558.                         if loc >= len(instring) - self.matchLen or instring[loc + self.matchLen] not in self.identChars:
  1559.                             if loc == 0 or instring[loc - 1] not in self.identChars:
  1560.                                 return (loc + self.matchLen, self.match)
  1561.                             exc = self.myException
  1562.                             exc.loc = loc
  1563.                             exc.pstr = instring
  1564.                             raise exc
  1565.                         return instring[loc + self.matchLen] not in self.identChars
  1566.  
  1567.     
  1568.     def copy(self):
  1569.         c = super(Keyword, self).copy()
  1570.         c.identChars = Keyword.DEFAULT_KEYWORD_CHARS
  1571.         return c
  1572.  
  1573.     
  1574.     def setDefaultKeywordChars(chars):
  1575.         Keyword.DEFAULT_KEYWORD_CHARS = chars
  1576.  
  1577.     setDefaultKeywordChars = staticmethod(setDefaultKeywordChars)
  1578.  
  1579.  
  1580. class CaselessLiteral(Literal):
  1581.     
  1582.     def __init__(self, matchString):
  1583.         super(CaselessLiteral, self).__init__(matchString.upper())
  1584.         self.returnString = matchString
  1585.         self.name = "'%s'" % self.returnString
  1586.         self.errmsg = 'Expected ' + self.name
  1587.  
  1588.     
  1589.     def parseImpl(self, instring, loc, doActions = True):
  1590.         if instring[loc:loc + self.matchLen].upper() == self.match:
  1591.             return (loc + self.matchLen, self.returnString)
  1592.         exc = self.myException
  1593.         exc.loc = loc
  1594.         exc.pstr = instring
  1595.         raise exc
  1596.  
  1597.  
  1598.  
  1599. class CaselessKeyword(Keyword):
  1600.     
  1601.     def __init__(self, matchString, identChars = Keyword.DEFAULT_KEYWORD_CHARS):
  1602.         super(CaselessKeyword, self).__init__(matchString, identChars, caseless = True)
  1603.  
  1604.     
  1605.     def parseImpl(self, instring, loc, doActions = True):
  1606.         if instring[loc:loc + self.matchLen].upper() == self.caselessmatch:
  1607.             if loc >= len(instring) - self.matchLen or instring[loc + self.matchLen].upper() not in self.identChars:
  1608.                 return (loc + self.matchLen, self.match)
  1609.             exc = self.myException
  1610.             exc.loc = loc
  1611.             exc.pstr = instring
  1612.             raise exc
  1613.         return instring[loc:loc + self.matchLen].upper() == self.caselessmatch
  1614.  
  1615.  
  1616.  
  1617. class Word(Token):
  1618.     
  1619.     def __init__(self, initChars, bodyChars = None, min = 1, max = 0, exact = 0, asKeyword = False):
  1620.         super(Word, self).__init__()
  1621.         self.initCharsOrig = initChars
  1622.         self.initChars = _str2dict(initChars)
  1623.         if bodyChars:
  1624.             self.bodyCharsOrig = bodyChars
  1625.             self.bodyChars = _str2dict(bodyChars)
  1626.         else:
  1627.             self.bodyCharsOrig = initChars
  1628.             self.bodyChars = _str2dict(initChars)
  1629.         self.maxSpecified = max > 0
  1630.         if min < 1:
  1631.             raise ValueError('cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted')
  1632.         min < 1
  1633.         self.minLen = min
  1634.         if max > 0:
  1635.             self.maxLen = max
  1636.         else:
  1637.             self.maxLen = _MAX_INT
  1638.         if exact > 0:
  1639.             self.maxLen = exact
  1640.             self.minLen = exact
  1641.         
  1642.         self.name = _ustr(self)
  1643.         self.errmsg = 'Expected ' + self.name
  1644.         self.mayIndexError = False
  1645.         self.asKeyword = asKeyword
  1646.         if ' ' not in self.initCharsOrig + self.bodyCharsOrig and min == 1 and max == 0 and exact == 0:
  1647.             if self.bodyCharsOrig == self.initCharsOrig:
  1648.                 self.reString = '[%s]+' % _escapeRegexRangeChars(self.initCharsOrig)
  1649.             elif len(self.bodyCharsOrig) == 1:
  1650.                 self.reString = '%s[%s]*' % (re.escape(self.initCharsOrig), _escapeRegexRangeChars(self.bodyCharsOrig))
  1651.             else:
  1652.                 self.reString = '[%s][%s]*' % (_escapeRegexRangeChars(self.initCharsOrig), _escapeRegexRangeChars(self.bodyCharsOrig))
  1653.             if self.asKeyword:
  1654.                 self.reString = '\\b' + self.reString + '\\b'
  1655.             
  1656.             
  1657.             try:
  1658.                 self.re = re.compile(self.reString)
  1659.             self.re = None
  1660.  
  1661.         
  1662.  
  1663.     
  1664.     def parseImpl(self, instring, loc, doActions = True):
  1665.         if self.re:
  1666.             result = self.re.match(instring, loc)
  1667.             if not result:
  1668.                 exc = self.myException
  1669.                 exc.loc = loc
  1670.                 exc.pstr = instring
  1671.                 raise exc
  1672.             result
  1673.             loc = result.end()
  1674.             return (loc, result.group())
  1675.         if instring[loc] not in self.initChars:
  1676.             exc = self.myException
  1677.             exc.loc = loc
  1678.             exc.pstr = instring
  1679.             raise exc
  1680.         instring[loc] not in self.initChars
  1681.         start = loc
  1682.         loc += 1
  1683.         instrlen = len(instring)
  1684.         bodychars = self.bodyChars
  1685.         maxloc = start + self.maxLen
  1686.         maxloc = min(maxloc, instrlen)
  1687.         while loc < maxloc and instring[loc] in bodychars:
  1688.             loc += 1
  1689.             continue
  1690.             self.re
  1691.         throwException = False
  1692.         if loc - start < self.minLen:
  1693.             throwException = True
  1694.         
  1695.         if self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
  1696.             throwException = True
  1697.         
  1698.         if self.asKeyword:
  1699.             if (start > 0 or instring[start - 1] in bodychars or loc < instrlen) and instring[loc] in bodychars:
  1700.                 throwException = True
  1701.             
  1702.         
  1703.         if throwException:
  1704.             exc = self.myException
  1705.             exc.loc = loc
  1706.             exc.pstr = instring
  1707.             raise exc
  1708.         throwException
  1709.         return (loc, instring[start:loc])
  1710.  
  1711.     
  1712.     def __str__(self):
  1713.         
  1714.         try:
  1715.             return super(Word, self).__str__()
  1716.         except:
  1717.             pass
  1718.  
  1719.         if self.strRepr is None:
  1720.             
  1721.             def charsAsStr(s):
  1722.                 if len(s) > 4:
  1723.                     return s[:4] + '...'
  1724.                 return s
  1725.  
  1726.             if self.initCharsOrig != self.bodyCharsOrig:
  1727.                 self.strRepr = 'W:(%s,%s)' % (charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig))
  1728.             else:
  1729.                 self.strRepr = 'W:(%s)' % charsAsStr(self.initCharsOrig)
  1730.         
  1731.         return self.strRepr
  1732.  
  1733.  
  1734.  
  1735. class Regex(Token):
  1736.     
  1737.     def __init__(self, pattern, flags = 0):
  1738.         super(Regex, self).__init__()
  1739.         if len(pattern) == 0:
  1740.             warnings.warn('null string passed to Regex; use Empty() instead', SyntaxWarning, stacklevel = 2)
  1741.         
  1742.         self.pattern = pattern
  1743.         self.flags = flags
  1744.         
  1745.         try:
  1746.             self.re = re.compile(self.pattern, self.flags)
  1747.             self.reString = self.pattern
  1748.         except sre_constants.error:
  1749.             warnings.warn('invalid pattern (%s) passed to Regex' % pattern, SyntaxWarning, stacklevel = 2)
  1750.             raise 
  1751.  
  1752.         self.name = _ustr(self)
  1753.         self.errmsg = 'Expected ' + self.name
  1754.         self.mayIndexError = False
  1755.         self.mayReturnEmpty = True
  1756.  
  1757.     
  1758.     def parseImpl(self, instring, loc, doActions = True):
  1759.         result = self.re.match(instring, loc)
  1760.         if not result:
  1761.             exc = self.myException
  1762.             exc.loc = loc
  1763.             exc.pstr = instring
  1764.             raise exc
  1765.         result
  1766.         loc = result.end()
  1767.         d = result.groupdict()
  1768.         ret = ParseResults(result.group())
  1769.         if d:
  1770.             for k in d:
  1771.                 ret[k] = d[k]
  1772.             
  1773.         
  1774.         return (loc, ret)
  1775.  
  1776.     
  1777.     def __str__(self):
  1778.         
  1779.         try:
  1780.             return super(Regex, self).__str__()
  1781.         except:
  1782.             pass
  1783.  
  1784.         if self.strRepr is None:
  1785.             self.strRepr = 'Re:(%s)' % repr(self.pattern)
  1786.         
  1787.         return self.strRepr
  1788.  
  1789.  
  1790.  
  1791. class QuotedString(Token):
  1792.     
  1793.     def __init__(self, quoteChar, escChar = None, escQuote = None, multiline = False, unquoteResults = True, endQuoteChar = None):
  1794.         super(QuotedString, self).__init__()
  1795.         quoteChar = quoteChar.strip()
  1796.         if len(quoteChar) == 0:
  1797.             warnings.warn('quoteChar cannot be the empty string', SyntaxWarning, stacklevel = 2)
  1798.             raise SyntaxError()
  1799.         len(quoteChar) == 0
  1800.         if endQuoteChar is None:
  1801.             endQuoteChar = quoteChar
  1802.         else:
  1803.             endQuoteChar = endQuoteChar.strip()
  1804.             if len(endQuoteChar) == 0:
  1805.                 warnings.warn('endQuoteChar cannot be the empty string', SyntaxWarning, stacklevel = 2)
  1806.                 raise SyntaxError()
  1807.             len(endQuoteChar) == 0
  1808.         self.quoteChar = quoteChar
  1809.         self.quoteCharLen = len(quoteChar)
  1810.         self.firstQuoteChar = quoteChar[0]
  1811.         self.endQuoteChar = endQuoteChar
  1812.         self.endQuoteCharLen = len(endQuoteChar)
  1813.         self.escChar = escChar
  1814.         self.escQuote = escQuote
  1815.         self.unquoteResults = unquoteResults
  1816.         if multiline:
  1817.             self.flags = re.MULTILINE | re.DOTALL
  1818.             if not escChar is not None or _escapeRegexRangeChars(escChar):
  1819.                 pass
  1820.             self.pattern = '%s(?:[^%s%s]' % (re.escape(self.quoteChar), _escapeRegexRangeChars(self.endQuoteChar[0]), '')
  1821.         else:
  1822.             self.flags = 0
  1823.             if not escChar is not None or _escapeRegexRangeChars(escChar):
  1824.                 pass
  1825.             self.pattern = '%s(?:[^%s\\n\\r%s]' % (re.escape(self.quoteChar), _escapeRegexRangeChars(self.endQuoteChar[0]), '')
  1826.         self.pattern += ')*%s' % re.escape(self.endQuoteChar)
  1827.         
  1828.         try:
  1829.             self.re = re.compile(self.pattern, self.flags)
  1830.             self.reString = self.pattern
  1831.         except sre_constants.error:
  1832.             self
  1833.             self
  1834.             None if escChar else None if escQuote else self if len(self.endQuoteChar) > 1 else self
  1835.             warnings.warn('invalid pattern (%s) passed to Regex' % self.pattern, SyntaxWarning, stacklevel = 2)
  1836.             raise 
  1837.         except:
  1838.             self
  1839.  
  1840.         self.name = _ustr(self)
  1841.         self.errmsg = 'Expected ' + self.name
  1842.         self.mayIndexError = False
  1843.         self.mayReturnEmpty = True
  1844.  
  1845.     
  1846.     def parseImpl(self, instring, loc, doActions = True):
  1847.         if not instring[loc] == self.firstQuoteChar or self.re.match(instring, loc):
  1848.             pass
  1849.         result = None
  1850.         if not result:
  1851.             exc = self.myException
  1852.             exc.loc = loc
  1853.             exc.pstr = instring
  1854.             raise exc
  1855.         result
  1856.         loc = result.end()
  1857.         ret = result.group()
  1858.         if self.unquoteResults:
  1859.             ret = ret[self.quoteCharLen:-(self.endQuoteCharLen)]
  1860.             if isinstance(ret, basestring):
  1861.                 if self.escChar:
  1862.                     ret = re.sub(self.escCharReplacePattern, '\\g<1>', ret)
  1863.                 
  1864.                 if self.escQuote:
  1865.                     ret = ret.replace(self.escQuote, self.endQuoteChar)
  1866.                 
  1867.             
  1868.         
  1869.         return (loc, ret)
  1870.  
  1871.     
  1872.     def __str__(self):
  1873.         
  1874.         try:
  1875.             return super(QuotedString, self).__str__()
  1876.         except:
  1877.             pass
  1878.  
  1879.         if self.strRepr is None:
  1880.             self.strRepr = 'quoted string, starting with %s ending with %s' % (self.quoteChar, self.endQuoteChar)
  1881.         
  1882.         return self.strRepr
  1883.  
  1884.  
  1885.  
  1886. class CharsNotIn(Token):
  1887.     
  1888.     def __init__(self, notChars, min = 1, max = 0, exact = 0):
  1889.         super(CharsNotIn, self).__init__()
  1890.         self.skipWhitespace = False
  1891.         self.notChars = notChars
  1892.         if min < 1:
  1893.             raise ValueError('cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted')
  1894.         min < 1
  1895.         self.minLen = min
  1896.         if max > 0:
  1897.             self.maxLen = max
  1898.         else:
  1899.             self.maxLen = _MAX_INT
  1900.         if exact > 0:
  1901.             self.maxLen = exact
  1902.             self.minLen = exact
  1903.         
  1904.         self.name = _ustr(self)
  1905.         self.errmsg = 'Expected ' + self.name
  1906.         self.mayReturnEmpty = self.minLen == 0
  1907.         self.mayIndexError = False
  1908.  
  1909.     
  1910.     def parseImpl(self, instring, loc, doActions = True):
  1911.         if instring[loc] in self.notChars:
  1912.             exc = self.myException
  1913.             exc.loc = loc
  1914.             exc.pstr = instring
  1915.             raise exc
  1916.         instring[loc] in self.notChars
  1917.         start = loc
  1918.         loc += 1
  1919.         notchars = self.notChars
  1920.         maxlen = min(start + self.maxLen, len(instring))
  1921.         while loc < maxlen and instring[loc] not in notchars:
  1922.             loc += 1
  1923.         if loc - start < self.minLen:
  1924.             exc = self.myException
  1925.             exc.loc = loc
  1926.             exc.pstr = instring
  1927.             raise exc
  1928.         loc - start < self.minLen
  1929.         return (loc, instring[start:loc])
  1930.  
  1931.     
  1932.     def __str__(self):
  1933.         
  1934.         try:
  1935.             return super(CharsNotIn, self).__str__()
  1936.         except:
  1937.             pass
  1938.  
  1939.         if self.strRepr is None:
  1940.             if len(self.notChars) > 4:
  1941.                 self.strRepr = '!W:(%s...)' % self.notChars[:4]
  1942.             else:
  1943.                 self.strRepr = '!W:(%s)' % self.notChars
  1944.         
  1945.         return self.strRepr
  1946.  
  1947.  
  1948.  
  1949. class White(Token):
  1950.     whiteStrs = {
  1951.         ' ': '<SPC>',
  1952.         '\t': '<TAB>',
  1953.         '\n': '<LF>',
  1954.         '\r': '<CR>',
  1955.         '\x0c': '<FF>' }
  1956.     
  1957.     def __init__(self, ws = ' \t\r\n', min = 1, max = 0, exact = 0):
  1958.         super(White, self).__init__()
  1959.         self.matchWhite = ws
  1960.         []([](_[1]))
  1961.         self.name = []([ White.whiteStrs[c] for c in self.matchWhite ])
  1962.         self.mayReturnEmpty = True
  1963.         self.errmsg = 'Expected ' + self.name
  1964.         self.minLen = min
  1965.  
  1966.     
  1967.     def parseImpl(self, instring, loc, doActions = True):
  1968.         if instring[loc] not in self.matchWhite:
  1969.             exc = self.myException
  1970.             exc.loc = loc
  1971.             exc.pstr = instring
  1972.             raise exc
  1973.         instring[loc] not in self.matchWhite
  1974.         start = loc
  1975.         loc += 1
  1976.         maxloc = start + self.maxLen
  1977.         maxloc = min(maxloc, len(instring))
  1978.         while loc < maxloc and instring[loc] in self.matchWhite:
  1979.             loc += 1
  1980.         if loc - start < self.minLen:
  1981.             exc = self.myException
  1982.             exc.loc = loc
  1983.             exc.pstr = instring
  1984.             raise exc
  1985.         loc - start < self.minLen
  1986.         return (loc, instring[start:loc])
  1987.  
  1988.  
  1989.  
  1990. class _PositionToken(Token):
  1991.     
  1992.     def __init__(self):
  1993.         super(_PositionToken, self).__init__()
  1994.         self.name = self.__class__.__name__
  1995.         self.mayReturnEmpty = True
  1996.         self.mayIndexError = False
  1997.  
  1998.  
  1999.  
  2000. class GoToColumn(_PositionToken):
  2001.     
  2002.     def __init__(self, colno):
  2003.         super(GoToColumn, self).__init__()
  2004.         self.col = colno
  2005.  
  2006.     
  2007.     def preParse(self, instring, loc):
  2008.         if col(loc, instring) != self.col:
  2009.             instrlen = len(instring)
  2010.             if self.ignoreExprs:
  2011.                 loc = self._skipIgnorables(instring, loc)
  2012.             
  2013.             while loc < instrlen and instring[loc].isspace() and col(loc, instring) != self.col:
  2014.                 loc += 1
  2015.         
  2016.         return loc
  2017.  
  2018.     
  2019.     def parseImpl(self, instring, loc, doActions = True):
  2020.         thiscol = col(loc, instring)
  2021.         if thiscol > self.col:
  2022.             raise ParseException(instring, loc, 'Text not in expected column', self)
  2023.         thiscol > self.col
  2024.         newloc = loc + self.col - thiscol
  2025.         ret = instring[loc:newloc]
  2026.         return (newloc, ret)
  2027.  
  2028.  
  2029.  
  2030. class LineStart(_PositionToken):
  2031.     
  2032.     def __init__(self):
  2033.         super(LineStart, self).__init__()
  2034.         self.setWhitespaceChars(ParserElement.DEFAULT_WHITE_CHARS.replace('\n', ''))
  2035.         self.errmsg = 'Expected start of line'
  2036.  
  2037.     
  2038.     def preParse(self, instring, loc):
  2039.         preloc = super(LineStart, self).preParse(instring, loc)
  2040.         if instring[preloc] == '\n':
  2041.             loc += 1
  2042.         
  2043.         return loc
  2044.  
  2045.     
  2046.     def parseImpl(self, instring, loc, doActions = True):
  2047.         if not loc == 0 and loc == self.preParse(instring, 0) or instring[loc - 1] == '\n':
  2048.             exc = self.myException
  2049.             exc.loc = loc
  2050.             exc.pstr = instring
  2051.             raise exc
  2052.         instring[loc - 1] == '\n'
  2053.         return (loc, [])
  2054.  
  2055.  
  2056.  
  2057. class LineEnd(_PositionToken):
  2058.     
  2059.     def __init__(self):
  2060.         super(LineEnd, self).__init__()
  2061.         self.setWhitespaceChars(ParserElement.DEFAULT_WHITE_CHARS.replace('\n', ''))
  2062.         self.errmsg = 'Expected end of line'
  2063.  
  2064.     
  2065.     def parseImpl(self, instring, loc, doActions = True):
  2066.         if loc < len(instring):
  2067.             if instring[loc] == '\n':
  2068.                 return (loc + 1, '\n')
  2069.             exc = self.myException
  2070.             exc.loc = loc
  2071.             exc.pstr = instring
  2072.             raise exc
  2073.         loc < len(instring)
  2074.         if loc == len(instring):
  2075.             return (loc + 1, [])
  2076.         exc = self.myException
  2077.         exc.loc = loc
  2078.         exc.pstr = instring
  2079.         raise exc
  2080.  
  2081.  
  2082.  
  2083. class StringStart(_PositionToken):
  2084.     
  2085.     def __init__(self):
  2086.         super(StringStart, self).__init__()
  2087.         self.errmsg = 'Expected start of text'
  2088.  
  2089.     
  2090.     def parseImpl(self, instring, loc, doActions = True):
  2091.         if loc != 0:
  2092.             if loc != self.preParse(instring, 0):
  2093.                 exc = self.myException
  2094.                 exc.loc = loc
  2095.                 exc.pstr = instring
  2096.                 raise exc
  2097.             loc != self.preParse(instring, 0)
  2098.         
  2099.         return (loc, [])
  2100.  
  2101.  
  2102.  
  2103. class StringEnd(_PositionToken):
  2104.     
  2105.     def __init__(self):
  2106.         super(StringEnd, self).__init__()
  2107.         self.errmsg = 'Expected end of text'
  2108.  
  2109.     
  2110.     def parseImpl(self, instring, loc, doActions = True):
  2111.         if loc < len(instring):
  2112.             exc = self.myException
  2113.             exc.loc = loc
  2114.             exc.pstr = instring
  2115.             raise exc
  2116.         loc < len(instring)
  2117.         if loc == len(instring):
  2118.             return (loc + 1, [])
  2119.         if loc > len(instring):
  2120.             return (loc, [])
  2121.         exc = self.myException
  2122.         exc.loc = loc
  2123.         exc.pstr = instring
  2124.         raise exc
  2125.  
  2126.  
  2127.  
  2128. class WordStart(_PositionToken):
  2129.     
  2130.     def __init__(self, wordChars = printables):
  2131.         super(WordStart, self).__init__()
  2132.         self.wordChars = _str2dict(wordChars)
  2133.         self.errmsg = 'Not at the start of a word'
  2134.  
  2135.     
  2136.     def parseImpl(self, instring, loc, doActions = True):
  2137.         if loc != 0:
  2138.             if instring[loc - 1] in self.wordChars or instring[loc] not in self.wordChars:
  2139.                 exc = self.myException
  2140.                 exc.loc = loc
  2141.                 exc.pstr = instring
  2142.                 raise exc
  2143.             instring[loc] not in self.wordChars
  2144.         
  2145.         return (loc, [])
  2146.  
  2147.  
  2148.  
  2149. class WordEnd(_PositionToken):
  2150.     
  2151.     def __init__(self, wordChars = printables):
  2152.         super(WordEnd, self).__init__()
  2153.         self.wordChars = _str2dict(wordChars)
  2154.         self.skipWhitespace = False
  2155.         self.errmsg = 'Not at the end of a word'
  2156.  
  2157.     
  2158.     def parseImpl(self, instring, loc, doActions = True):
  2159.         instrlen = len(instring)
  2160.         if instrlen > 0 and loc < instrlen:
  2161.             if instring[loc] in self.wordChars or instring[loc - 1] not in self.wordChars:
  2162.                 exc = self.myException
  2163.                 exc.loc = loc
  2164.                 exc.pstr = instring
  2165.                 raise exc
  2166.             instring[loc - 1] not in self.wordChars
  2167.         
  2168.         return (loc, [])
  2169.  
  2170.  
  2171.  
  2172. class ParseExpression(ParserElement):
  2173.     
  2174.     def __init__(self, exprs, savelist = False):
  2175.         super(ParseExpression, self).__init__(savelist)
  2176.         if isinstance(exprs, list):
  2177.             self.exprs = exprs
  2178.         elif isinstance(exprs, basestring):
  2179.             self.exprs = [
  2180.                 Literal(exprs)]
  2181.         else:
  2182.             self.exprs = [
  2183.                 exprs]
  2184.         self.callPreparse = False
  2185.  
  2186.     
  2187.     def __getitem__(self, i):
  2188.         return self.exprs[i]
  2189.  
  2190.     
  2191.     def append(self, other):
  2192.         self.exprs.append(other)
  2193.         self.strRepr = None
  2194.         return self
  2195.  
  2196.     
  2197.     def leaveWhitespace(self):
  2198.         self.skipWhitespace = False
  2199.         self.exprs = [ e.copy() for e in self.exprs ]
  2200.         for e in self.exprs:
  2201.             e.leaveWhitespace()
  2202.         
  2203.         return self
  2204.  
  2205.     
  2206.     def ignore(self, other):
  2207.         if isinstance(other, Suppress):
  2208.             if other not in self.ignoreExprs:
  2209.                 super(ParseExpression, self).ignore(other)
  2210.                 for e in self.exprs:
  2211.                     e.ignore(self.ignoreExprs[-1])
  2212.                 
  2213.             
  2214.         else:
  2215.             super(ParseExpression, self).ignore(other)
  2216.             for e in self.exprs:
  2217.                 e.ignore(self.ignoreExprs[-1])
  2218.             
  2219.         return self
  2220.  
  2221.     
  2222.     def __str__(self):
  2223.         
  2224.         try:
  2225.             return super(ParseExpression, self).__str__()
  2226.         except:
  2227.             pass
  2228.  
  2229.         if self.strRepr is None:
  2230.             self.strRepr = '%s:(%s)' % (self.__class__.__name__, _ustr(self.exprs))
  2231.         
  2232.         return self.strRepr
  2233.  
  2234.     
  2235.     def streamline(self):
  2236.         super(ParseExpression, self).streamline()
  2237.         for e in self.exprs:
  2238.             e.streamline()
  2239.         
  2240.         if len(self.exprs) == 2:
  2241.             other = self.exprs[0]
  2242.             other = self.exprs[-1]
  2243.             if isinstance(other, self.__class__) and not (other.parseAction) and other.resultsName is None and not (other.debug):
  2244.                 self.exprs = self.exprs[:-1] + other.exprs[:]
  2245.                 self.strRepr = None
  2246.                 self.mayReturnEmpty |= other.mayReturnEmpty
  2247.                 self.mayIndexError |= other.mayIndexError
  2248.             
  2249.         
  2250.         return self
  2251.  
  2252.     
  2253.     def setResultsName(self, name, listAllMatches = False):
  2254.         ret = super(ParseExpression, self).setResultsName(name, listAllMatches)
  2255.         return ret
  2256.  
  2257.     
  2258.     def validate(self, validateTrace = []):
  2259.         tmp = validateTrace[:] + [
  2260.             self]
  2261.         for e in self.exprs:
  2262.             e.validate(tmp)
  2263.         
  2264.         self.checkRecursion([])
  2265.  
  2266.  
  2267.  
  2268. class And(ParseExpression):
  2269.     
  2270.     class _ErrorStop(Empty):
  2271.         
  2272.         def __init__(self, *args, **kwargs):
  2273.             super(Empty, self).__init__(*args, **kwargs)
  2274.             self.leaveWhitespace()
  2275.  
  2276.  
  2277.     
  2278.     def __init__(self, exprs, savelist = True):
  2279.         super(And, self).__init__(exprs, savelist)
  2280.         self.mayReturnEmpty = True
  2281.         for e in self.exprs:
  2282.             if not e.mayReturnEmpty:
  2283.                 self.mayReturnEmpty = False
  2284.                 break
  2285.                 continue
  2286.         
  2287.         self.setWhitespaceChars(exprs[0].whiteChars)
  2288.         self.skipWhitespace = exprs[0].skipWhitespace
  2289.         self.callPreparse = True
  2290.  
  2291.     
  2292.     def parseImpl(self, instring, loc, doActions = True):
  2293.         (loc, resultlist) = self.exprs[0]._parse(instring, loc, doActions, callPreParse = False)
  2294.         errorStop = False
  2295.         for e in self.exprs[1:]:
  2296.             if isinstance(e, And._ErrorStop):
  2297.                 errorStop = True
  2298.                 continue
  2299.             
  2300.             if errorStop:
  2301.                 
  2302.                 try:
  2303.                     (loc, exprtokens) = e._parse(instring, loc, doActions)
  2304.                 except ParseSyntaxException:
  2305.                     raise 
  2306.                 except ParseBaseException:
  2307.                     pe = None
  2308.                     raise ParseSyntaxException(pe)
  2309.                 except IndexError:
  2310.                     ie = None
  2311.                     raise ParseSyntaxException(ParseException(instring, len(instring), self.errmsg, self))
  2312.                 except:
  2313.                     None<EXCEPTION MATCH>ParseSyntaxException
  2314.                 
  2315.  
  2316.             None<EXCEPTION MATCH>ParseSyntaxException
  2317.             (loc, exprtokens) = e._parse(instring, loc, doActions)
  2318.             if exprtokens or exprtokens.keys():
  2319.                 resultlist += exprtokens
  2320.                 continue
  2321.         
  2322.         return (loc, resultlist)
  2323.  
  2324.     
  2325.     def __iadd__(self, other):
  2326.         if isinstance(other, basestring):
  2327.             other = Literal(other)
  2328.         
  2329.         return self.append(other)
  2330.  
  2331.     
  2332.     def checkRecursion(self, parseElementList):
  2333.         subRecCheckList = parseElementList[:] + [
  2334.             self]
  2335.         for e in self.exprs:
  2336.             e.checkRecursion(subRecCheckList)
  2337.             if not e.mayReturnEmpty:
  2338.                 break
  2339.                 continue
  2340.         
  2341.  
  2342.     
  2343.     def __str__(self):
  2344.         if hasattr(self, 'name'):
  2345.             return self.name
  2346.         return self.strRepr
  2347.  
  2348.  
  2349.  
  2350. class Or(ParseExpression):
  2351.     
  2352.     def __init__(self, exprs, savelist = False):
  2353.         super(Or, self).__init__(exprs, savelist)
  2354.         self.mayReturnEmpty = False
  2355.         for e in self.exprs:
  2356.             if e.mayReturnEmpty:
  2357.                 self.mayReturnEmpty = True
  2358.                 break
  2359.                 continue
  2360.         
  2361.  
  2362.     
  2363.     def parseImpl(self, instring, loc, doActions = True):
  2364.         maxExcLoc = -1
  2365.         maxMatchLoc = -1
  2366.         maxException = None
  2367.         for e in self.exprs:
  2368.             
  2369.             try:
  2370.                 loc2 = e.tryParse(instring, loc)
  2371.             except ParseException:
  2372.                 err = None
  2373.                 if err.loc > maxExcLoc:
  2374.                     maxException = err
  2375.                     maxExcLoc = err.loc
  2376.                 
  2377.                 err.loc > maxExcLoc
  2378.                 except IndexError:
  2379.                     if len(instring) > maxExcLoc:
  2380.                         maxException = ParseException(instring, len(instring), e.errmsg, self)
  2381.                         maxExcLoc = len(instring)
  2382.                     
  2383.                     len(instring) > maxExcLoc
  2384.                 elif loc2 > maxMatchLoc:
  2385.                     maxMatchLoc = loc2
  2386.                     maxMatchExp = e
  2387.                     continue
  2388.  
  2389.         
  2390.         if maxMatchLoc < 0:
  2391.             if maxException is not None:
  2392.                 raise maxException
  2393.             maxException is not None
  2394.             raise ParseException(instring, loc, 'no defined alternatives to match', self)
  2395.         maxMatchLoc < 0
  2396.         return maxMatchExp._parse(instring, loc, doActions)
  2397.  
  2398.     
  2399.     def __ixor__(self, other):
  2400.         if isinstance(other, basestring):
  2401.             other = Literal(other)
  2402.         
  2403.         return self.append(other)
  2404.  
  2405.     
  2406.     def __str__(self):
  2407.         if hasattr(self, 'name'):
  2408.             return self.name
  2409.         return self.strRepr
  2410.  
  2411.     
  2412.     def checkRecursion(self, parseElementList):
  2413.         subRecCheckList = parseElementList[:] + [
  2414.             self]
  2415.         for e in self.exprs:
  2416.             e.checkRecursion(subRecCheckList)
  2417.         
  2418.  
  2419.  
  2420.  
  2421. class MatchFirst(ParseExpression):
  2422.     
  2423.     def __init__(self, exprs, savelist = False):
  2424.         super(MatchFirst, self).__init__(exprs, savelist)
  2425.         if exprs:
  2426.             self.mayReturnEmpty = False
  2427.             for e in self.exprs:
  2428.                 if e.mayReturnEmpty:
  2429.                     self.mayReturnEmpty = True
  2430.                     break
  2431.                     continue
  2432.             
  2433.         else:
  2434.             self.mayReturnEmpty = True
  2435.  
  2436.     
  2437.     def parseImpl(self, instring, loc, doActions = True):
  2438.         maxExcLoc = -1
  2439.         maxException = None
  2440.         for e in self.exprs:
  2441.             
  2442.             try:
  2443.                 ret = e._parse(instring, loc, doActions)
  2444.                 return ret
  2445.             continue
  2446.             except ParseException:
  2447.                 err = None
  2448.                 if err.loc > maxExcLoc:
  2449.                     maxException = err
  2450.                     maxExcLoc = err.loc
  2451.                 
  2452.                 err.loc > maxExcLoc
  2453.                 except IndexError:
  2454.                     if len(instring) > maxExcLoc:
  2455.                         maxException = ParseException(instring, len(instring), e.errmsg, self)
  2456.                         maxExcLoc = len(instring)
  2457.                     
  2458.                     len(instring) > maxExcLoc
  2459.                 
  2460.             if maxException is not None:
  2461.                 raise maxException
  2462.             raise ParseException(instring, loc, 'no defined alternatives to match', self)
  2463.             return None
  2464.  
  2465.  
  2466.     
  2467.     def __ior__(self, other):
  2468.         if isinstance(other, basestring):
  2469.             other = Literal(other)
  2470.         
  2471.         return self.append(other)
  2472.  
  2473.     
  2474.     def __str__(self):
  2475.         if hasattr(self, 'name'):
  2476.             return self.name
  2477.         return self.strRepr
  2478.  
  2479.     
  2480.     def checkRecursion(self, parseElementList):
  2481.         subRecCheckList = parseElementList[:] + [
  2482.             self]
  2483.         for e in self.exprs:
  2484.             e.checkRecursion(subRecCheckList)
  2485.         
  2486.  
  2487.  
  2488.  
  2489. class Each(ParseExpression):
  2490.     
  2491.     def __init__(self, exprs, savelist = True):
  2492.         super(Each, self).__init__(exprs, savelist)
  2493.         self.mayReturnEmpty = True
  2494.         for e in self.exprs:
  2495.             if not e.mayReturnEmpty:
  2496.                 self.mayReturnEmpty = False
  2497.                 break
  2498.                 continue
  2499.         
  2500.         self.skipWhitespace = True
  2501.         self.initExprGroups = True
  2502.  
  2503.     
  2504.     def parseImpl(self, instring, loc, doActions = True):
  2505.         tmpLoc = loc
  2506.         tmpReqd = self.required[:]
  2507.         tmpOpt = self.optionals[:]
  2508.         matchOrder = []
  2509.         keepMatching = True
  2510.         while keepMatching:
  2511.             tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired
  2512.             failed = []
  2513.             for e in tmpExprs:
  2514.                 
  2515.                 try:
  2516.                     tmpLoc = e.tryParse(instring, tmpLoc)
  2517.                 except ParseException:
  2518.                     [] if self.initExprGroups else []
  2519.                     [] if self.initExprGroups else []
  2520.                     []
  2521.                     failed.append(e)
  2522.                     continue
  2523.                     []
  2524.  
  2525.                 matchOrder.append(e)
  2526.                 if e in tmpReqd:
  2527.                     tmpReqd.remove(e)
  2528.                     continue
  2529.                 [] if self.initExprGroups else []
  2530.                 if e in tmpOpt:
  2531.                     tmpOpt.remove(e)
  2532.                     continue
  2533.                 []
  2534.             
  2535.             if len(failed) == len(tmpExprs):
  2536.                 keepMatching = False
  2537.                 continue
  2538.             []
  2539.             continue
  2540.             []
  2541.         if tmpReqd:
  2542.             missing = []([ _ustr(e) for e in tmpReqd ])
  2543.             raise ParseException(instring, loc, 'Missing one or more required elements (%s)' % missing)
  2544.         tmpReqd
  2545.         [] += _[6]
  2546.         resultlist = []
  2547.         for e in matchOrder:
  2548.             (loc, results) = e._parse(instring, loc, doActions)
  2549.             resultlist.append(results)
  2550.         
  2551.         finalResults = ParseResults([])
  2552.         for r in resultlist:
  2553.             dups = { }
  2554.             for k in r.keys():
  2555.                 if k in finalResults.keys():
  2556.                     tmp = ParseResults(finalResults[k])
  2557.                     tmp += ParseResults(r[k])
  2558.                     dups[k] = tmp
  2559.                     continue
  2560.                 []
  2561.             
  2562.             finalResults += ParseResults(r)
  2563.             for k, v in dups.items():
  2564.                 finalResults[k] = v
  2565.             
  2566.         
  2567.         return (loc, finalResults)
  2568.  
  2569.     
  2570.     def __str__(self):
  2571.         if hasattr(self, 'name'):
  2572.             return self.name
  2573.         return self.strRepr
  2574.  
  2575.     
  2576.     def checkRecursion(self, parseElementList):
  2577.         subRecCheckList = parseElementList[:] + [
  2578.             self]
  2579.         for e in self.exprs:
  2580.             e.checkRecursion(subRecCheckList)
  2581.         
  2582.  
  2583.  
  2584.  
  2585. class ParseElementEnhance(ParserElement):
  2586.     
  2587.     def __init__(self, expr, savelist = False):
  2588.         super(ParseElementEnhance, self).__init__(savelist)
  2589.         if isinstance(expr, basestring):
  2590.             expr = Literal(expr)
  2591.         
  2592.         self.expr = expr
  2593.         self.strRepr = None
  2594.         if expr is not None:
  2595.             self.mayIndexError = expr.mayIndexError
  2596.             self.mayReturnEmpty = expr.mayReturnEmpty
  2597.             self.setWhitespaceChars(expr.whiteChars)
  2598.             self.skipWhitespace = expr.skipWhitespace
  2599.             self.saveAsList = expr.saveAsList
  2600.             self.callPreparse = expr.callPreparse
  2601.             self.ignoreExprs.extend(expr.ignoreExprs)
  2602.         
  2603.  
  2604.     
  2605.     def parseImpl(self, instring, loc, doActions = True):
  2606.         if self.expr is not None:
  2607.             return self.expr._parse(instring, loc, doActions, callPreParse = False)
  2608.         raise ParseException('', loc, self.errmsg, self)
  2609.  
  2610.     
  2611.     def leaveWhitespace(self):
  2612.         self.skipWhitespace = False
  2613.         self.expr = self.expr.copy()
  2614.         if self.expr is not None:
  2615.             self.expr.leaveWhitespace()
  2616.         
  2617.         return self
  2618.  
  2619.     
  2620.     def ignore(self, other):
  2621.         if isinstance(other, Suppress):
  2622.             if other not in self.ignoreExprs:
  2623.                 super(ParseElementEnhance, self).ignore(other)
  2624.                 if self.expr is not None:
  2625.                     self.expr.ignore(self.ignoreExprs[-1])
  2626.                 
  2627.             
  2628.         else:
  2629.             super(ParseElementEnhance, self).ignore(other)
  2630.             if self.expr is not None:
  2631.                 self.expr.ignore(self.ignoreExprs[-1])
  2632.             
  2633.         return self
  2634.  
  2635.     
  2636.     def streamline(self):
  2637.         super(ParseElementEnhance, self).streamline()
  2638.         if self.expr is not None:
  2639.             self.expr.streamline()
  2640.         
  2641.         return self
  2642.  
  2643.     
  2644.     def checkRecursion(self, parseElementList):
  2645.         if self in parseElementList:
  2646.             raise RecursiveGrammarException(parseElementList + [
  2647.                 self])
  2648.         self in parseElementList
  2649.         subRecCheckList = parseElementList[:] + [
  2650.             self]
  2651.         if self.expr is not None:
  2652.             self.expr.checkRecursion(subRecCheckList)
  2653.         
  2654.  
  2655.     
  2656.     def validate(self, validateTrace = []):
  2657.         tmp = validateTrace[:] + [
  2658.             self]
  2659.         if self.expr is not None:
  2660.             self.expr.validate(tmp)
  2661.         
  2662.         self.checkRecursion([])
  2663.  
  2664.     
  2665.     def __str__(self):
  2666.         
  2667.         try:
  2668.             return super(ParseElementEnhance, self).__str__()
  2669.         except:
  2670.             pass
  2671.  
  2672.         if self.strRepr is None and self.expr is not None:
  2673.             self.strRepr = '%s:(%s)' % (self.__class__.__name__, _ustr(self.expr))
  2674.         
  2675.         return self.strRepr
  2676.  
  2677.  
  2678.  
  2679. class FollowedBy(ParseElementEnhance):
  2680.     
  2681.     def __init__(self, expr):
  2682.         super(FollowedBy, self).__init__(expr)
  2683.         self.mayReturnEmpty = True
  2684.  
  2685.     
  2686.     def parseImpl(self, instring, loc, doActions = True):
  2687.         self.expr.tryParse(instring, loc)
  2688.         return (loc, [])
  2689.  
  2690.  
  2691.  
  2692. class NotAny(ParseElementEnhance):
  2693.     
  2694.     def __init__(self, expr):
  2695.         super(NotAny, self).__init__(expr)
  2696.         self.skipWhitespace = False
  2697.         self.mayReturnEmpty = True
  2698.         self.errmsg = 'Found unwanted token, ' + _ustr(self.expr)
  2699.  
  2700.     
  2701.     def parseImpl(self, instring, loc, doActions = True):
  2702.         
  2703.         try:
  2704.             self.expr.tryParse(instring, loc)
  2705.         except (ParseException, IndexError):
  2706.             pass
  2707.  
  2708.         exc = self.myException
  2709.         exc.loc = loc
  2710.         exc.pstr = instring
  2711.         raise exc
  2712.         return (loc, [])
  2713.  
  2714.     
  2715.     def __str__(self):
  2716.         if hasattr(self, 'name'):
  2717.             return self.name
  2718.         if self.strRepr is None:
  2719.             self.strRepr = '~{' + _ustr(self.expr) + '}'
  2720.         
  2721.         return self.strRepr
  2722.  
  2723.  
  2724.  
  2725. class ZeroOrMore(ParseElementEnhance):
  2726.     
  2727.     def __init__(self, expr):
  2728.         super(ZeroOrMore, self).__init__(expr)
  2729.         self.mayReturnEmpty = True
  2730.  
  2731.     
  2732.     def parseImpl(self, instring, loc, doActions = True):
  2733.         tokens = []
  2734.         
  2735.         try:
  2736.             (loc, tokens) = self.expr._parse(instring, loc, doActions, callPreParse = False)
  2737.             hasIgnoreExprs = len(self.ignoreExprs) > 0
  2738.             while hasIgnoreExprs:
  2739.                 preloc = self._skipIgnorables(instring, loc)
  2740.             preloc = loc
  2741.             (loc, tmptokens) = self.expr._parse(instring, preloc, doActions)
  2742.             if tmptokens or tmptokens.keys():
  2743.                 tokens += tmptokens
  2744.                 continue
  2745.         except (ParseException, IndexError):
  2746.             pass
  2747.  
  2748.         return (loc, tokens)
  2749.  
  2750.     
  2751.     def __str__(self):
  2752.         if hasattr(self, 'name'):
  2753.             return self.name
  2754.         if self.strRepr is None:
  2755.             self.strRepr = '[' + _ustr(self.expr) + ']...'
  2756.         
  2757.         return self.strRepr
  2758.  
  2759.     
  2760.     def setResultsName(self, name, listAllMatches = False):
  2761.         ret = super(ZeroOrMore, self).setResultsName(name, listAllMatches)
  2762.         ret.saveAsList = True
  2763.         return ret
  2764.  
  2765.  
  2766.  
  2767. class OneOrMore(ParseElementEnhance):
  2768.     
  2769.     def parseImpl(self, instring, loc, doActions = True):
  2770.         (loc, tokens) = self.expr._parse(instring, loc, doActions, callPreParse = False)
  2771.         
  2772.         try:
  2773.             hasIgnoreExprs = len(self.ignoreExprs) > 0
  2774.             while hasIgnoreExprs:
  2775.                 preloc = self._skipIgnorables(instring, loc)
  2776.             preloc = loc
  2777.             (loc, tmptokens) = self.expr._parse(instring, preloc, doActions)
  2778.             if tmptokens or tmptokens.keys():
  2779.                 tokens += tmptokens
  2780.                 continue
  2781.         except (ParseException, IndexError):
  2782.             pass
  2783.  
  2784.         return (loc, tokens)
  2785.  
  2786.     
  2787.     def __str__(self):
  2788.         if hasattr(self, 'name'):
  2789.             return self.name
  2790.         if self.strRepr is None:
  2791.             self.strRepr = '{' + _ustr(self.expr) + '}...'
  2792.         
  2793.         return self.strRepr
  2794.  
  2795.     
  2796.     def setResultsName(self, name, listAllMatches = False):
  2797.         ret = super(OneOrMore, self).setResultsName(name, listAllMatches)
  2798.         ret.saveAsList = True
  2799.         return ret
  2800.  
  2801.  
  2802.  
  2803. class _NullToken(object):
  2804.     
  2805.     def __bool__(self):
  2806.         return False
  2807.  
  2808.     __nonzero__ = __bool__
  2809.     
  2810.     def __str__(self):
  2811.         return ''
  2812.  
  2813.  
  2814. _optionalNotMatched = _NullToken()
  2815.  
  2816. class Optional(ParseElementEnhance):
  2817.     
  2818.     def __init__(self, exprs, default = _optionalNotMatched):
  2819.         super(Optional, self).__init__(exprs, savelist = False)
  2820.         self.defaultValue = default
  2821.         self.mayReturnEmpty = True
  2822.  
  2823.     
  2824.     def parseImpl(self, instring, loc, doActions = True):
  2825.         
  2826.         try:
  2827.             (loc, tokens) = self.expr._parse(instring, loc, doActions, callPreParse = False)
  2828.         except (ParseException, IndexError):
  2829.             if self.defaultValue is not _optionalNotMatched:
  2830.                 if self.expr.resultsName:
  2831.                     tokens = ParseResults([
  2832.                         self.defaultValue])
  2833.                     tokens[self.expr.resultsName] = self.defaultValue
  2834.                 else:
  2835.                     tokens = [
  2836.                         self.defaultValue]
  2837.             else:
  2838.                 tokens = []
  2839.         except:
  2840.             self.defaultValue is not _optionalNotMatched
  2841.  
  2842.         return (loc, tokens)
  2843.  
  2844.     
  2845.     def __str__(self):
  2846.         if hasattr(self, 'name'):
  2847.             return self.name
  2848.         if self.strRepr is None:
  2849.             self.strRepr = '[' + _ustr(self.expr) + ']'
  2850.         
  2851.         return self.strRepr
  2852.  
  2853.  
  2854.  
  2855. class SkipTo(ParseElementEnhance):
  2856.     
  2857.     def __init__(self, other, include = False, ignore = None, failOn = None):
  2858.         super(SkipTo, self).__init__(other)
  2859.         if ignore is not None:
  2860.             self.expr = self.expr.copy()
  2861.             self.expr.ignore(ignore)
  2862.         
  2863.         self.mayReturnEmpty = True
  2864.         self.mayIndexError = False
  2865.         self.includeMatch = include
  2866.         self.asList = False
  2867.         if failOn is not None and isinstance(failOn, basestring):
  2868.             self.failOn = Literal(failOn)
  2869.         else:
  2870.             self.failOn = failOn
  2871.         self.errmsg = 'No match found for ' + _ustr(self.expr)
  2872.  
  2873.     
  2874.     def parseImpl(self, instring, loc, doActions = True):
  2875.         startLoc = loc
  2876.         instrlen = len(instring)
  2877.         expr = self.expr
  2878.         failParse = False
  2879.         while loc <= instrlen:
  2880.             
  2881.             try:
  2882.                 if self.failOn:
  2883.                     failParse = True
  2884.                     self.failOn.tryParse(instring, loc)
  2885.                     failParse = False
  2886.                 
  2887.                 loc = expr._skipIgnorables(instring, loc)
  2888.                 expr._parse(instring, loc, doActions = False, callPreParse = False)
  2889.                 skipText = instring[startLoc:loc]
  2890.                 if self.includeMatch:
  2891.                     (loc, mat) = expr._parse(instring, loc, doActions, callPreParse = False)
  2892.                     if mat:
  2893.                         skipRes = ParseResults(skipText)
  2894.                         skipRes += mat
  2895.                         return (loc, [
  2896.                             skipRes])
  2897.                     return (loc, [
  2898.                         skipText])
  2899.                 self.includeMatch
  2900.                 return (loc, [
  2901.                     skipText])
  2902.             continue
  2903.             except (ParseException, IndexError):
  2904.                 if failParse:
  2905.                     raise 
  2906.                 failParse
  2907.                 loc += 1
  2908.                 continue
  2909.             
  2910.  
  2911.             None<EXCEPTION MATCH>(ParseException, IndexError)
  2912.         exc = self.myException
  2913.         exc.loc = loc
  2914.         exc.pstr = instring
  2915.         raise exc
  2916.  
  2917.  
  2918.  
  2919. class Forward(ParseElementEnhance):
  2920.     
  2921.     def __init__(self, other = None):
  2922.         super(Forward, self).__init__(other, savelist = False)
  2923.  
  2924.     
  2925.     def __lshift__(self, other):
  2926.         if isinstance(other, basestring):
  2927.             other = Literal(other)
  2928.         
  2929.         self.expr = other
  2930.         self.mayReturnEmpty = other.mayReturnEmpty
  2931.         self.strRepr = None
  2932.         self.mayIndexError = self.expr.mayIndexError
  2933.         self.mayReturnEmpty = self.expr.mayReturnEmpty
  2934.         self.setWhitespaceChars(self.expr.whiteChars)
  2935.         self.skipWhitespace = self.expr.skipWhitespace
  2936.         self.saveAsList = self.expr.saveAsList
  2937.         self.ignoreExprs.extend(self.expr.ignoreExprs)
  2938.  
  2939.     
  2940.     def leaveWhitespace(self):
  2941.         self.skipWhitespace = False
  2942.         return self
  2943.  
  2944.     
  2945.     def streamline(self):
  2946.         if not self.streamlined:
  2947.             self.streamlined = True
  2948.             if self.expr is not None:
  2949.                 self.expr.streamline()
  2950.             
  2951.         
  2952.         return self
  2953.  
  2954.     
  2955.     def validate(self, validateTrace = []):
  2956.         if self not in validateTrace:
  2957.             tmp = validateTrace[:] + [
  2958.                 self]
  2959.             if self.expr is not None:
  2960.                 self.expr.validate(tmp)
  2961.             
  2962.         
  2963.         self.checkRecursion([])
  2964.  
  2965.     
  2966.     def __str__(self):
  2967.         if hasattr(self, 'name'):
  2968.             return self.name
  2969.         self._revertClass = self.__class__
  2970.         self.__class__ = _ForwardNoRecurse
  2971.         
  2972.         try:
  2973.             if self.expr is not None:
  2974.                 retString = _ustr(self.expr)
  2975.             else:
  2976.                 retString = 'None'
  2977.         finally:
  2978.             self.__class__ = self._revertClass
  2979.  
  2980.         return self.__class__.__name__ + ': ' + retString
  2981.  
  2982.     
  2983.     def copy(self):
  2984.         if self.expr is not None:
  2985.             return super(Forward, self).copy()
  2986.         ret = Forward()
  2987.         ret << self
  2988.         return ret
  2989.  
  2990.  
  2991.  
  2992. class _ForwardNoRecurse(Forward):
  2993.     
  2994.     def __str__(self):
  2995.         return '...'
  2996.  
  2997.  
  2998.  
  2999. class TokenConverter(ParseElementEnhance):
  3000.     
  3001.     def __init__(self, expr, savelist = False):
  3002.         super(TokenConverter, self).__init__(expr)
  3003.         self.saveAsList = False
  3004.  
  3005.  
  3006.  
  3007. class Upcase(TokenConverter):
  3008.     
  3009.     def __init__(self, *args):
  3010.         super(Upcase, self).__init__(*args)
  3011.         warnings.warn('Upcase class is deprecated, use upcaseTokens parse action instead', DeprecationWarning, stacklevel = 2)
  3012.  
  3013.     
  3014.     def postParse(self, instring, loc, tokenlist):
  3015.         return list(map(string.upper, tokenlist))
  3016.  
  3017.  
  3018.  
  3019. class Combine(TokenConverter):
  3020.     
  3021.     def __init__(self, expr, joinString = '', adjacent = True):
  3022.         super(Combine, self).__init__(expr)
  3023.         if adjacent:
  3024.             self.leaveWhitespace()
  3025.         
  3026.         self.adjacent = adjacent
  3027.         self.skipWhitespace = True
  3028.         self.joinString = joinString
  3029.  
  3030.     
  3031.     def ignore(self, other):
  3032.         if self.adjacent:
  3033.             ParserElement.ignore(self, other)
  3034.         else:
  3035.             super(Combine, self).ignore(other)
  3036.         return self
  3037.  
  3038.     
  3039.     def postParse(self, instring, loc, tokenlist):
  3040.         retToks = tokenlist.copy()
  3041.         del retToks[:]
  3042.         retToks += ParseResults([
  3043.             ''.join(tokenlist._asStringList(self.joinString))], modal = self.modalResults)
  3044.         if self.resultsName and len(retToks.keys()) > 0:
  3045.             return [
  3046.                 retToks]
  3047.         return retToks
  3048.  
  3049.  
  3050.  
  3051. class Group(TokenConverter):
  3052.     
  3053.     def __init__(self, expr):
  3054.         super(Group, self).__init__(expr)
  3055.         self.saveAsList = True
  3056.  
  3057.     
  3058.     def postParse(self, instring, loc, tokenlist):
  3059.         return [
  3060.             tokenlist]
  3061.  
  3062.  
  3063.  
  3064. class Dict(TokenConverter):
  3065.     
  3066.     def __init__(self, exprs):
  3067.         super(Dict, self).__init__(exprs)
  3068.         self.saveAsList = True
  3069.  
  3070.     
  3071.     def postParse(self, instring, loc, tokenlist):
  3072.         for i, tok in enumerate(tokenlist):
  3073.             if len(tok) == 0:
  3074.                 continue
  3075.             
  3076.             ikey = tok[0]
  3077.             if isinstance(ikey, int):
  3078.                 ikey = _ustr(tok[0]).strip()
  3079.             
  3080.             if len(tok) == 1:
  3081.                 tokenlist[ikey] = _ParseResultsWithOffset('', i)
  3082.                 continue
  3083.             if len(tok) == 2 and not isinstance(tok[1], ParseResults):
  3084.                 tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i)
  3085.                 continue
  3086.             dictvalue = tok.copy()
  3087.             del dictvalue[0]
  3088.             if (len(dictvalue) != 1 or isinstance(dictvalue, ParseResults)) and dictvalue.keys():
  3089.                 tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i)
  3090.                 continue
  3091.             tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i)
  3092.         
  3093.         if self.resultsName:
  3094.             return [
  3095.                 tokenlist]
  3096.         return tokenlist
  3097.  
  3098.  
  3099.  
  3100. class Suppress(TokenConverter):
  3101.     
  3102.     def postParse(self, instring, loc, tokenlist):
  3103.         return []
  3104.  
  3105.     
  3106.     def suppress(self):
  3107.         return self
  3108.  
  3109.  
  3110.  
  3111. class OnlyOnce(object):
  3112.     
  3113.     def __init__(self, methodCall):
  3114.         self.callable = ParserElement._normalizeParseActionArgs(methodCall)
  3115.         self.called = False
  3116.  
  3117.     
  3118.     def __call__(self, s, l, t):
  3119.         if not self.called:
  3120.             results = self.callable(s, l, t)
  3121.             self.called = True
  3122.             return results
  3123.         raise ParseException(s, l, '')
  3124.  
  3125.     
  3126.     def reset(self):
  3127.         self.called = False
  3128.  
  3129.  
  3130.  
  3131. def traceParseAction(f):
  3132.     f = ParserElement._normalizeParseActionArgs(f)
  3133.     
  3134.     def z(*paArgs):
  3135.         thisFunc = f.func_name
  3136.         (s, l, t) = paArgs[-3:]
  3137.         if len(paArgs) > 3:
  3138.             thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
  3139.         
  3140.         sys.stderr.write(">>entering %s(line: '%s', %d, %s)\n" % (thisFunc, line(l, s), l, t))
  3141.         
  3142.         try:
  3143.             ret = f(*paArgs)
  3144.         except Exception:
  3145.             exc = None
  3146.             sys.stderr.write('<<leaving %s (exception: %s)\n' % (thisFunc, exc))
  3147.             raise 
  3148.  
  3149.         sys.stderr.write('<<leaving %s (ret: %s)\n' % (thisFunc, ret))
  3150.         return ret
  3151.  
  3152.     
  3153.     try:
  3154.         z.__name__ = f.__name__
  3155.     except AttributeError:
  3156.         (None,)
  3157.         (None,)
  3158.     except:
  3159.         (None,)
  3160.  
  3161.     return z
  3162.  
  3163.  
  3164. def delimitedList(expr, delim = ',', combine = False):
  3165.     dlName = _ustr(expr) + ' [' + _ustr(delim) + ' ' + _ustr(expr) + ']...'
  3166.     if combine:
  3167.         return Combine(expr + ZeroOrMore(delim + expr)).setName(dlName)
  3168.     return (expr + ZeroOrMore(Suppress(delim) + expr)).setName(dlName)
  3169.  
  3170.  
  3171. def countedArray(expr):
  3172.     arrayExpr = Forward()
  3173.     
  3174.     def countFieldParseAction(s, l, t):
  3175.         n = int(t[0])
  3176.         if not n or Group(And([
  3177.             expr] * n)):
  3178.             pass
  3179.         arrayExpr << Group(empty)
  3180.         return []
  3181.  
  3182.     return Word(nums).setName('arrayLen').setParseAction(countFieldParseAction, callDuringTry = True) + arrayExpr
  3183.  
  3184.  
  3185. def _flatten(L):
  3186.     if type(L) is not list:
  3187.         return [
  3188.             L]
  3189.     if L == []:
  3190.         return L
  3191.     return _flatten(L[0]) + _flatten(L[1:])
  3192.  
  3193.  
  3194. def matchPreviousLiteral(expr):
  3195.     rep = Forward()
  3196.     
  3197.     def copyTokenToRepeater(s, l, t):
  3198.         pass
  3199.  
  3200.     expr.addParseAction(copyTokenToRepeater, callDuringTry = True)
  3201.     return rep
  3202.  
  3203.  
  3204. def matchPreviousExpr(expr):
  3205.     rep = Forward()
  3206.     e2 = expr.copy()
  3207.     rep << e2
  3208.     
  3209.     def copyTokenToRepeater(s, l, t):
  3210.         matchTokens = _flatten(t.asList())
  3211.         
  3212.         def mustMatchTheseTokens(s, l, t):
  3213.             theseTokens = _flatten(t.asList())
  3214.             if theseTokens != matchTokens:
  3215.                 raise ParseException('', 0, '')
  3216.             theseTokens != matchTokens
  3217.  
  3218.         rep.setParseAction(mustMatchTheseTokens, callDuringTry = True)
  3219.  
  3220.     expr.addParseAction(copyTokenToRepeater, callDuringTry = True)
  3221.     return rep
  3222.  
  3223.  
  3224. def _escapeRegexRangeChars(s):
  3225.     for c in '\\^-]':
  3226.         s = s.replace(c, _bslash + c)
  3227.     
  3228.     s = s.replace('\n', '\\n')
  3229.     s = s.replace('\t', '\\t')
  3230.     return _ustr(s)
  3231.  
  3232.  
  3233. def oneOf(strs, caseless = False, useRegex = True):
  3234.     if caseless:
  3235.         
  3236.         isequal = lambda a, b: a.upper() == b.upper()
  3237.         
  3238.         masks = lambda a, b: b.upper().startswith(a.upper())
  3239.         parseElementClass = CaselessLiteral
  3240.     else:
  3241.         
  3242.         isequal = lambda a, b: a == b
  3243.         
  3244.         masks = lambda a, b: b.startswith(a)
  3245.         parseElementClass = Literal
  3246.     if isinstance(strs, (list, tuple)):
  3247.         symbols = strs[:]
  3248.     elif isinstance(strs, basestring):
  3249.         symbols = strs.split()
  3250.     else:
  3251.         warnings.warn('Invalid argument to oneOf, expected string or list', SyntaxWarning, stacklevel = 2)
  3252.     i = 0
  3253.     while i < len(symbols) - 1:
  3254.         cur = symbols[i]
  3255.         for j, other in enumerate(symbols[i + 1:]):
  3256.             if isequal(other, cur):
  3257.                 del symbols[i + j + 1]
  3258.                 break
  3259.                 continue
  3260.             if masks(cur, other):
  3261.                 del symbols[i + j + 1]
  3262.                 symbols.insert(i, other)
  3263.                 cur = other
  3264.                 break
  3265.                 continue
  3266.         else:
  3267.             i += 1
  3268.     if not caseless and useRegex:
  3269.         
  3270.         try:
  3271.             if len(symbols) == len(''.join(symbols)):
  3272.                 return ''.join([] % []([ _escapeRegexRangeChars(sym) for sym in symbols ]))
  3273.             return []([]([ re.escape(sym) for sym in symbols ]))
  3274.         warnings.warn('Exception creating Regex for oneOf, building MatchFirst', SyntaxWarning, stacklevel = 2)
  3275.  
  3276.     
  3277.     return []([ parseElementClass(sym) for sym in symbols ])
  3278.  
  3279.  
  3280. def dictOf(key, value):
  3281.     return Dict(ZeroOrMore(Group(key + value)))
  3282.  
  3283.  
  3284. def originalTextFor(expr, asString = True):
  3285.     locMarker = Empty().setParseAction((lambda s, loc, t: loc))
  3286.     matchExpr = locMarker('_original_start') + expr + locMarker('_original_end')
  3287.     if asString:
  3288.         
  3289.         extractText = lambda s, l, t: s[t._original_start:t._original_end]
  3290.     else:
  3291.         
  3292.         def extractText(s, l, t):
  3293.             del t[:]
  3294.             t.insert(0, s[t._original_start:t._original_end])
  3295.             del t['_original_start']
  3296.             del t['_original_end']
  3297.  
  3298.     matchExpr.setParseAction(extractText)
  3299.     return matchExpr
  3300.  
  3301. empty = Empty().setName('empty')
  3302. lineStart = LineStart().setName('lineStart')
  3303. lineEnd = LineEnd().setName('lineEnd')
  3304. stringStart = StringStart().setName('stringStart')
  3305. stringEnd = StringEnd().setName('stringEnd')
  3306. _escapedPunc = Word(_bslash, '\\[]-*.$+^?()~ ', exact = 2).setParseAction((lambda s, l, t: t[0][1]))
  3307. _printables_less_backslash = []([] if c not in '\\]' else _[2])
  3308. _escapedHexChar = Combine(Suppress(_bslash + '0x') + Word(hexnums)).setParseAction((lambda s, l, t: unichr(int(t[0], 16))))
  3309. _escapedOctChar = Combine(Suppress(_bslash) + Word('0', '01234567')).setParseAction((lambda s, l, t: unichr(int(t[0], 8))))
  3310. _singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | Word(_printables_less_backslash, exact = 1)
  3311. _charRange = Group(_singleChar + Suppress('-') + _singleChar)
  3312. _reBracketExpr = Literal('[') + Optional('^').setResultsName('negate') + Group(OneOrMore(_charRange | _singleChar)).setResultsName('body') + ']'
  3313.  
  3314. _expanded = lambda p: if not isinstance(p, ParseResults) or []([ unichr(c) for c in range(ord(p[0]), ord(p[1]) + 1) ]):
  3315. passp
  3316.  
  3317. def srange(s):
  3318.     
  3319.     try:
  3320.         return []([ _expanded(part) for part in _reBracketExpr.parseString(s).body ])
  3321.     except:
  3322.         return ''
  3323.  
  3324.  
  3325.  
  3326. def matchOnlyAtCol(n):
  3327.     
  3328.     def verifyCol(strg, locn, toks):
  3329.         if col(locn, strg) != n:
  3330.             raise ParseException(strg, locn, 'matched token not at column %d' % n)
  3331.         col(locn, strg) != n
  3332.  
  3333.     return verifyCol
  3334.  
  3335.  
  3336. def replaceWith(replStr):
  3337.     
  3338.     def _replFunc(*args):
  3339.         return [
  3340.             replStr]
  3341.  
  3342.     return _replFunc
  3343.  
  3344.  
  3345. def removeQuotes(s, l, t):
  3346.     return t[0][1:-1]
  3347.  
  3348.  
  3349. def upcaseTokens(s, l, t):
  3350.     return [ tt.upper() for tt in map(_ustr, t) ]
  3351.  
  3352.  
  3353. def downcaseTokens(s, l, t):
  3354.     return [ tt.lower() for tt in map(_ustr, t) ]
  3355.  
  3356.  
  3357. def keepOriginalText(s, startLoc, t):
  3358.     
  3359.     try:
  3360.         endloc = getTokensEndLoc()
  3361.     except ParseException:
  3362.         raise ParseFatalException('incorrect usage of keepOriginalText - may only be called as a parse action')
  3363.  
  3364.     del t[:]
  3365.     t += ParseResults(s[startLoc:endloc])
  3366.     return t
  3367.  
  3368.  
  3369. def getTokensEndLoc():
  3370.     import inspect
  3371.     fstack = inspect.stack()
  3372.     
  3373.     try:
  3374.         for f in fstack[2:]:
  3375.             if f[3] == '_parseNoCache':
  3376.                 endloc = f[0].f_locals['loc']
  3377.                 return endloc
  3378.         else:
  3379.             raise ParseFatalException('incorrect usage of getTokensEndLoc - may only be called from within a parse action')
  3380.         del fstack
  3381.         return None
  3382.  
  3383.  
  3384.  
  3385. def _makeTags(tagStr, xml):
  3386.     if isinstance(tagStr, basestring):
  3387.         resname = tagStr
  3388.         tagStr = Keyword(tagStr, caseless = not xml)
  3389.     else:
  3390.         resname = tagStr.name
  3391.     tagAttrName = Word(alphas, alphanums + '_-:')
  3392.     closeTag = Combine(_L('</') + tagStr + '>')
  3393.     openTag = openTag.setResultsName('start' + ''.join(resname.replace(':', ' ').title().split())).setName('<%s>' % tagStr)
  3394.     closeTag = closeTag.setResultsName('end' + ''.join(resname.replace(':', ' ').title().split())).setName('</%s>' % tagStr)
  3395.     return (openTag, closeTag)
  3396.  
  3397.  
  3398. def makeHTMLTags(tagStr):
  3399.     return _makeTags(tagStr, False)
  3400.  
  3401.  
  3402. def makeXMLTags(tagStr):
  3403.     return _makeTags(tagStr, True)
  3404.  
  3405.  
  3406. def withAttribute(*args, **attrDict):
  3407.     if args:
  3408.         attrs = args[:]
  3409.     else:
  3410.         attrs = attrDict.items()
  3411.     attrs = [ (k, v) for k, v in attrs ]
  3412.     
  3413.     def pa(s, l, tokens):
  3414.         for attrName, attrValue in attrs:
  3415.             if attrName not in tokens:
  3416.                 raise ParseException(s, l, 'no matching attribute ' + attrName)
  3417.             attrName not in tokens
  3418.             if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue:
  3419.                 raise ParseException(s, l, "attribute '%s' has value '%s', must be '%s'" % (attrName, tokens[attrName], attrValue))
  3420.             tokens[attrName] != attrValue
  3421.         
  3422.  
  3423.     return pa
  3424.  
  3425. withAttribute.ANY_VALUE = object()
  3426. opAssoc = _Constants()
  3427. opAssoc.LEFT = object()
  3428. opAssoc.RIGHT = object()
  3429.  
  3430. def operatorPrecedence(baseExpr, opList):
  3431.     ret = Forward()
  3432.     lastExpr = baseExpr | Suppress('(') + ret + Suppress(')')
  3433.     for i, operDef in enumerate(opList):
  3434.         (opExpr, arity, rightLeftAssoc, pa) = operDef + (None,)[:4]
  3435.         if arity == 3:
  3436.             if opExpr is None or len(opExpr) != 2:
  3437.                 raise ValueError('if numterms=3, opExpr must be a tuple or list of two expressions')
  3438.             len(opExpr) != 2
  3439.             (opExpr1, opExpr2) = opExpr
  3440.         
  3441.         thisExpr = Forward()
  3442.         if rightLeftAssoc == opAssoc.LEFT:
  3443.             if arity == 1:
  3444.                 matchExpr = FollowedBy(lastExpr + opExpr) + Group(lastExpr + OneOrMore(opExpr))
  3445.             elif arity == 2:
  3446.                 if opExpr is not None:
  3447.                     matchExpr = FollowedBy(lastExpr + opExpr + lastExpr) + Group(lastExpr + OneOrMore(opExpr + lastExpr))
  3448.                 else:
  3449.                     matchExpr = FollowedBy(lastExpr + lastExpr) + Group(lastExpr + OneOrMore(lastExpr))
  3450.             elif arity == 3:
  3451.                 matchExpr = FollowedBy(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) + Group(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr)
  3452.             else:
  3453.                 raise ValueError('operator must be unary (1), binary (2), or ternary (3)')
  3454.         arity == 1
  3455.         if rightLeftAssoc == opAssoc.RIGHT:
  3456.             if arity == 1:
  3457.                 if not isinstance(opExpr, Optional):
  3458.                     opExpr = Optional(opExpr)
  3459.                 
  3460.                 matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group(opExpr + thisExpr)
  3461.             elif arity == 2:
  3462.                 if opExpr is not None:
  3463.                     matchExpr = FollowedBy(lastExpr + opExpr + thisExpr) + Group(lastExpr + OneOrMore(opExpr + thisExpr))
  3464.                 else:
  3465.                     matchExpr = FollowedBy(lastExpr + thisExpr) + Group(lastExpr + OneOrMore(thisExpr))
  3466.             elif arity == 3:
  3467.                 matchExpr = FollowedBy(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + Group(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr)
  3468.             else:
  3469.                 raise ValueError('operator must be unary (1), binary (2), or ternary (3)')
  3470.         arity == 1
  3471.         raise ValueError('operator must indicate right or left associativity')
  3472.         if pa:
  3473.             matchExpr.setParseAction(pa)
  3474.         
  3475.         thisExpr << (matchExpr | lastExpr)
  3476.         lastExpr = thisExpr
  3477.     
  3478.     ret << lastExpr
  3479.     return ret
  3480.  
  3481. dblQuotedString = Regex('"(?:[^"\\n\\r\\\\]|(?:"")|(?:\\\\x[0-9a-fA-F]+)|(?:\\\\.))*"').setName('string enclosed in double quotes')
  3482. sglQuotedString = Regex("'(?:[^'\\n\\r\\\\]|(?:'')|(?:\\\\x[0-9a-fA-F]+)|(?:\\\\.))*'").setName('string enclosed in single quotes')
  3483. quotedString = Regex('(?:"(?:[^"\\n\\r\\\\]|(?:"")|(?:\\\\x[0-9a-fA-F]+)|(?:\\\\.))*")|(?:\'(?:[^\'\\n\\r\\\\]|(?:\'\')|(?:\\\\x[0-9a-fA-F]+)|(?:\\\\.))*\')').setName('quotedString using single or double quotes')
  3484. unicodeString = Combine(_L('u') + quotedString.copy())
  3485.  
  3486. def nestedExpr(opener = '(', closer = ')', content = None, ignoreExpr = quotedString):
  3487.     if opener == closer:
  3488.         raise ValueError('opening and closing strings cannot be the same')
  3489.     opener == closer
  3490.     if content is None:
  3491.         if isinstance(opener, basestring) and isinstance(closer, basestring):
  3492.             if len(opener) == 1 and len(closer) == 1:
  3493.                 if ignoreExpr is not None:
  3494.                     content = Combine(OneOrMore(~ignoreExpr + CharsNotIn(opener + closer + ParserElement.DEFAULT_WHITE_CHARS, exact = 1))).setParseAction((lambda t: t[0].strip()))
  3495.                 else:
  3496.                     content = empty + CharsNotIn(opener + closer + ParserElement.DEFAULT_WHITE_CHARS).setParseAction((lambda t: t[0].strip()))
  3497.             elif ignoreExpr is not None:
  3498.                 content = Combine(OneOrMore(~ignoreExpr + ~Literal(opener) + ~Literal(closer) + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact = 1))).setParseAction((lambda t: t[0].strip()))
  3499.             else:
  3500.                 content = Combine(OneOrMore(~Literal(opener) + ~Literal(closer) + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact = 1))).setParseAction((lambda t: t[0].strip()))
  3501.         else:
  3502.             raise ValueError('opening and closing arguments must be strings if no content expression is given')
  3503.     isinstance(closer, basestring)
  3504.     ret = Forward()
  3505.     if ignoreExpr is not None:
  3506.         ret << Group(Suppress(opener) + ZeroOrMore(ignoreExpr | ret | content) + Suppress(closer))
  3507.     else:
  3508.         ret << Group(Suppress(opener) + ZeroOrMore(ret | content) + Suppress(closer))
  3509.     return ret
  3510.  
  3511.  
  3512. def indentedBlock(blockStatementExpr, indentStack, indent = True):
  3513.     
  3514.     def checkPeerIndent(s, l, t):
  3515.         if l >= len(s):
  3516.             return None
  3517.         curCol = col(l, s)
  3518.         if curCol != indentStack[-1]:
  3519.             if curCol > indentStack[-1]:
  3520.                 raise ParseFatalException(s, l, 'illegal nesting')
  3521.             curCol > indentStack[-1]
  3522.             raise ParseException(s, l, 'not a peer entry')
  3523.         curCol != indentStack[-1]
  3524.  
  3525.     
  3526.     def checkSubIndent(s, l, t):
  3527.         curCol = col(l, s)
  3528.         if curCol > indentStack[-1]:
  3529.             indentStack.append(curCol)
  3530.         else:
  3531.             raise ParseException(s, l, 'not a subentry')
  3532.         return curCol > indentStack[-1]
  3533.  
  3534.     
  3535.     def checkUnindent(s, l, t):
  3536.         if l >= len(s):
  3537.             return None
  3538.         curCol = col(l, s)
  3539.         if not indentStack and curCol < indentStack[-1] and curCol <= indentStack[-2]:
  3540.             raise ParseException(s, l, 'not an unindent')
  3541.         curCol <= indentStack[-2]
  3542.         indentStack.pop()
  3543.  
  3544.     NL = OneOrMore(LineEnd().setWhitespaceChars('\t ').suppress())
  3545.     INDENT = Empty() + Empty().setParseAction(checkSubIndent)
  3546.     PEER = Empty().setParseAction(checkPeerIndent)
  3547.     UNDENT = Empty().setParseAction(checkUnindent)
  3548.     if indent:
  3549.         smExpr = Group(Optional(NL) + FollowedBy(blockStatementExpr) + INDENT + OneOrMore(PEER + Group(blockStatementExpr) + Optional(NL)) + UNDENT)
  3550.     else:
  3551.         smExpr = Group(Optional(NL) + OneOrMore(PEER + Group(blockStatementExpr) + Optional(NL)))
  3552.     blockStatementExpr.ignore(_bslash + LineEnd())
  3553.     return smExpr
  3554.  
  3555. alphas8bit = srange('[\\0xc0-\\0xd6\\0xd8-\\0xf6\\0xf8-\\0xff]')
  3556. punc8bit = srange('[\\0xa1-\\0xbf\\0xd7\\0xf7]')
  3557. (anyOpenTag, anyCloseTag) = makeHTMLTags(Word(alphas, alphanums + '_:'))
  3558. commonHTMLEntity = Combine(_L('&') + oneOf('gt lt amp nbsp quot').setResultsName('entity') + ';')
  3559. _htmlEntityMap = dict(zip('gt lt amp nbsp quot'.split(), '><& "'))
  3560.  
  3561. replaceHTMLEntity = lambda t: if not t.entity in _htmlEntityMap or _htmlEntityMap[t.entity]:
  3562. pass
  3563. cStyleComment = Regex('/\\*(?:[^*]*\\*+)+?/').setName('C style comment')
  3564. htmlComment = Regex('<!--[\\s\\S]*?-->')
  3565. restOfLine = Regex('.*').leaveWhitespace()
  3566. dblSlashComment = Regex('\\/\\/(\\\\\\n|.)*').setName('// comment')
  3567. cppStyleComment = Regex('/(?:\\*(?:[^*]*\\*+)+?/|/[^\\n]*(?:\\n[^\\n]*)*?(?:(?<!\\\\)|\\Z))').setName('C++ style comment')
  3568. javaStyleComment = cppStyleComment
  3569. pythonStyleComment = Regex('#.*').setName('Python style comment')
  3570. _noncomma = []([] if c != ',' else _[3])
  3571. _commasepitem = Combine(OneOrMore(Word(_noncomma) + Optional(Word(' \t') + ~Literal(',') + ~LineEnd()))).streamline().setName('commaItem')
  3572. commaSeparatedList = delimitedList(Optional(quotedString | _commasepitem, default = '')).setName('commaSeparatedList')
  3573.