PageRenderTime 75ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/matplotlib/pyparsing_py3.py

https://github.com/tomflannaghan/matplotlib
Python | 3682 lines | 3622 code | 13 blank | 47 comment | 41 complexity | 46a6f273ce4d626a176d7e1c2699c6aa MD5 | raw file
Possible License(s): MIT, GPL-3.0, BSD-3-Clause
  1. # module pyparsing.py
  2. #
  3. # Copyright (c) 2003-2010 Paul T. McGuire
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining
  6. # a copy of this software and associated documentation files (the
  7. # "Software"), to deal in the Software without restriction, including
  8. # without limitation the rights to use, copy, modify, merge, publish,
  9. # distribute, sublicense, and/or sell copies of the Software, and to
  10. # permit persons to whom the Software is furnished to do so, subject to
  11. # the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be
  14. # included in all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  19. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  20. # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  21. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  22. # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. #
  24. #from __future__ import generators
  25. __doc__ = \
  26. """
  27. pyparsing module - Classes and methods to define and execute parsing grammars
  28. The pyparsing module is an alternative approach to creating and executing simple grammars,
  29. vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you
  30. don't need to learn a new syntax for defining grammars or matching expressions - the parsing module
  31. provides a library of classes that you use to construct the grammar directly in Python.
  32. Here is a program to parse "Hello, World!" (or any greeting of the form C{"<salutation>, <addressee>!"})::
  33. from pyparsing import Word, alphas
  34. # define grammar of a greeting
  35. greet = Word( alphas ) + "," + Word( alphas ) + "!"
  36. hello = "Hello, World!"
  37. print hello, "->", greet.parseString( hello )
  38. The program outputs the following::
  39. Hello, World! -> ['Hello', ',', 'World', '!']
  40. The Python representation of the grammar is quite readable, owing to the self-explanatory
  41. class names, and the use of '+', '|' and '^' operators.
  42. The parsed results returned from C{parseString()} can be accessed as a nested list, a dictionary, or an
  43. object with named attributes.
  44. The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
  45. - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.)
  46. - quoted strings
  47. - embedded comments
  48. """
  49. __version__ = "1.5.5"
  50. __versionTime__ = "12 Aug 2010 03:56"
  51. __author__ = "Paul McGuire <ptmcg@users.sourceforge.net>"
  52. import string
  53. from weakref import ref as wkref
  54. import copy
  55. import sys
  56. import warnings
  57. import re
  58. import sre_constants
  59. import collections
  60. #~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
  61. __all__ = [
  62. 'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty',
  63. 'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal',
  64. 'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or',
  65. 'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException',
  66. 'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException',
  67. 'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter', 'Upcase',
  68. 'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore',
  69. 'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col',
  70. 'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString',
  71. 'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'getTokensEndLoc', 'hexnums',
  72. 'htmlComment', 'javaStyleComment', 'keepOriginalText', 'line', 'lineEnd', 'lineStart', 'lineno',
  73. 'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral',
  74. 'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables',
  75. 'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity',
  76. 'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd',
  77. 'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute',
  78. 'indentedBlock', 'originalTextFor',
  79. ]
  80. """
  81. Detect if we are running version 3.X and make appropriate changes
  82. Robert A. Clark
  83. """
  84. _PY3K = sys.version_info[0] > 2
  85. if _PY3K:
  86. _MAX_INT = sys.maxsize
  87. basestring = str
  88. unichr = chr
  89. _ustr = str
  90. alphas = string.ascii_lowercase + string.ascii_uppercase
  91. else:
  92. _MAX_INT = sys.maxint
  93. range = xrange
  94. set = lambda s : dict( [(c,0) for c in s] )
  95. alphas = string.lowercase + string.uppercase
  96. def _ustr(obj):
  97. """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
  98. str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
  99. then < returns the unicode object | encodes it with the default encoding | ... >.
  100. """
  101. if isinstance(obj,unicode):
  102. return obj
  103. try:
  104. # If this works, then _ustr(obj) has the same behaviour as str(obj), so
  105. # it won't break any existing code.
  106. return str(obj)
  107. except UnicodeEncodeError:
  108. # The Python docs (http://docs.python.org/ref/customization.html#l2h-182)
  109. # state that "The return value must be a string object". However, does a
  110. # unicode object (being a subclass of basestring) count as a "string
  111. # object"?
  112. # If so, then return a unicode object:
  113. return unicode(obj)
  114. # Else encode it... but how? There are many choices... :)
  115. # Replace unprintables with escape codes?
  116. #return unicode(obj).encode(sys.getdefaultencoding(), 'backslashreplace_errors')
  117. # Replace unprintables with question marks?
  118. #return unicode(obj).encode(sys.getdefaultencoding(), 'replace')
  119. # ...
  120. # build list of single arg builtins, tolerant of Python version, that can be used as parse actions
  121. singleArgBuiltins = []
  122. import builtins
  123. for fname in "sum len enumerate sorted reversed list tuple set any all".split():
  124. try:
  125. singleArgBuiltins.append(getattr(builtins,fname))
  126. except AttributeError:
  127. continue
  128. def _xml_escape(data):
  129. """Escape &, <, >, ", ', etc. in a string of data."""
  130. # ampersand must be replaced first
  131. for from_,to_ in zip('&><"\'', "amp gt lt quot apos".split()):
  132. data = data.replace(from_, '&'+to_+';')
  133. return data
  134. class _Constants(object):
  135. pass
  136. nums = string.digits
  137. hexnums = nums + "ABCDEFabcdef"
  138. alphanums = alphas + nums
  139. _bslash = chr(92)
  140. printables = "".join( [ c for c in string.printable if c not in string.whitespace ] )
  141. class ParseBaseException(Exception):
  142. """base exception class for all parsing runtime exceptions"""
  143. # Performance tuning: we construct a *lot* of these, so keep this
  144. # constructor as small and fast as possible
  145. def __init__( self, pstr, loc=0, msg=None, elem=None ):
  146. self.loc = loc
  147. if msg is None:
  148. self.msg = pstr
  149. self.pstr = ""
  150. else:
  151. self.msg = msg
  152. self.pstr = pstr
  153. self.parserElement = elem
  154. def __getattr__( self, aname ):
  155. """supported attributes by name are:
  156. - lineno - returns the line number of the exception text
  157. - col - returns the column number of the exception text
  158. - line - returns the line containing the exception text
  159. """
  160. if( aname == "lineno" ):
  161. return lineno( self.loc, self.pstr )
  162. elif( aname in ("col", "column") ):
  163. return col( self.loc, self.pstr )
  164. elif( aname == "line" ):
  165. return line( self.loc, self.pstr )
  166. else:
  167. raise AttributeError(aname)
  168. def __str__( self ):
  169. return "%s (at char %d), (line:%d, col:%d)" % \
  170. ( self.msg, self.loc, self.lineno, self.column )
  171. def __repr__( self ):
  172. return _ustr(self)
  173. def markInputline( self, markerString = ">!<" ):
  174. """Extracts the exception line from the input string, and marks
  175. the location of the exception with a special symbol.
  176. """
  177. line_str = self.line
  178. line_column = self.column - 1
  179. if markerString:
  180. line_str = "".join( [line_str[:line_column],
  181. markerString, line_str[line_column:]])
  182. return line_str.strip()
  183. def __dir__(self):
  184. return "loc msg pstr parserElement lineno col line " \
  185. "markInputLine __str__ __repr__".split()
  186. class ParseException(ParseBaseException):
  187. """exception thrown when parse expressions don't match class;
  188. supported attributes by name are:
  189. - lineno - returns the line number of the exception text
  190. - col - returns the column number of the exception text
  191. - line - returns the line containing the exception text
  192. """
  193. pass
  194. class ParseFatalException(ParseBaseException):
  195. """user-throwable exception thrown when inconsistent parse content
  196. is found; stops all parsing immediately"""
  197. pass
  198. class ParseSyntaxException(ParseFatalException):
  199. """just like C{ParseFatalException}, but thrown internally when an
  200. C{ErrorStop} ('-' operator) indicates that parsing is to stop immediately because
  201. an unbacktrackable syntax error has been found"""
  202. def __init__(self, pe):
  203. super(ParseSyntaxException, self).__init__(
  204. pe.pstr, pe.loc, pe.msg, pe.parserElement)
  205. #~ class ReparseException(ParseBaseException):
  206. #~ """Experimental class - parse actions can raise this exception to cause
  207. #~ pyparsing to reparse the input string:
  208. #~ - with a modified input string, and/or
  209. #~ - with a modified start location
  210. #~ Set the values of the ReparseException in the constructor, and raise the
  211. #~ exception in a parse action to cause pyparsing to use the new string/location.
  212. #~ Setting the values as None causes no change to be made.
  213. #~ """
  214. #~ def __init_( self, newstring, restartLoc ):
  215. #~ self.newParseText = newstring
  216. #~ self.reparseLoc = restartLoc
  217. class RecursiveGrammarException(Exception):
  218. """exception thrown by C{validate()} if the grammar could be improperly recursive"""
  219. def __init__( self, parseElementList ):
  220. self.parseElementTrace = parseElementList
  221. def __str__( self ):
  222. return "RecursiveGrammarException: %s" % self.parseElementTrace
  223. class _ParseResultsWithOffset(object):
  224. def __init__(self,p1,p2):
  225. self.tup = (p1,p2)
  226. def __getitem__(self,i):
  227. return self.tup[i]
  228. def __repr__(self):
  229. return repr(self.tup)
  230. def setOffset(self,i):
  231. self.tup = (self.tup[0],i)
  232. class ParseResults(object):
  233. """Structured parse results, to provide multiple means of access to the parsed data:
  234. - as a list (C{len(results)})
  235. - by list index (C{results[0], results[1]}, etc.)
  236. - by attribute (C{results.<resultsName>})
  237. """
  238. #~ __slots__ = ( "__toklist", "__tokdict", "__doinit", "__name", "__parent", "__accumNames", "__weakref__" )
  239. def __new__(cls, toklist, name=None, asList=True, modal=True ):
  240. if isinstance(toklist, cls):
  241. return toklist
  242. retobj = object.__new__(cls)
  243. retobj.__doinit = True
  244. return retobj
  245. # Performance tuning: we construct a *lot* of these, so keep this
  246. # constructor as small and fast as possible
  247. def __init__( self, toklist, name=None, asList=True, modal=True ):
  248. if self.__doinit:
  249. self.__doinit = False
  250. self.__name = None
  251. self.__parent = None
  252. self.__accumNames = {}
  253. if isinstance(toklist, list):
  254. self.__toklist = toklist[:]
  255. else:
  256. self.__toklist = [toklist]
  257. self.__tokdict = dict()
  258. if name is not None and name:
  259. if not modal:
  260. self.__accumNames[name] = 0
  261. if isinstance(name,int):
  262. name = _ustr(name) # will always return a str, but use _ustr for consistency
  263. self.__name = name
  264. if not toklist in (None,'',[]):
  265. if isinstance(toklist,basestring):
  266. toklist = [ toklist ]
  267. if asList:
  268. if isinstance(toklist,ParseResults):
  269. self[name] = _ParseResultsWithOffset(toklist.copy(),0)
  270. else:
  271. self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]),0)
  272. self[name].__name = name
  273. else:
  274. try:
  275. self[name] = toklist[0]
  276. except (KeyError,TypeError,IndexError):
  277. self[name] = toklist
  278. def __getitem__( self, i ):
  279. if isinstance( i, (int,slice) ):
  280. return self.__toklist[i]
  281. else:
  282. if i not in self.__accumNames:
  283. return self.__tokdict[i][-1][0]
  284. else:
  285. return ParseResults([ v[0] for v in self.__tokdict[i] ])
  286. def __setitem__( self, k, v ):
  287. if isinstance(v,_ParseResultsWithOffset):
  288. self.__tokdict[k] = self.__tokdict.get(k,list()) + [v]
  289. sub = v[0]
  290. elif isinstance(k,int):
  291. self.__toklist[k] = v
  292. sub = v
  293. else:
  294. self.__tokdict[k] = self.__tokdict.get(k,list()) + [_ParseResultsWithOffset(v,0)]
  295. sub = v
  296. if isinstance(sub,ParseResults):
  297. sub.__parent = wkref(self)
  298. def __delitem__( self, i ):
  299. if isinstance(i,(int,slice)):
  300. mylen = len( self.__toklist )
  301. del self.__toklist[i]
  302. # convert int to slice
  303. if isinstance(i, int):
  304. if i < 0:
  305. i += mylen
  306. i = slice(i, i+1)
  307. # get removed indices
  308. removed = list(range(*i.indices(mylen)))
  309. removed.reverse()
  310. # fixup indices in token dictionary
  311. for name in self.__tokdict:
  312. occurrences = self.__tokdict[name]
  313. for j in removed:
  314. for k, (value, position) in enumerate(occurrences):
  315. occurrences[k] = _ParseResultsWithOffset(value, position - (position > j))
  316. else:
  317. del self.__tokdict[i]
  318. def __contains__( self, k ):
  319. return k in self.__tokdict
  320. def __len__( self ): return len( self.__toklist )
  321. def __bool__(self): return len( self.__toklist ) > 0
  322. __nonzero__ = __bool__
  323. def __iter__( self ): return iter( self.__toklist )
  324. def __reversed__( self ): return iter( reversed(self.__toklist) )
  325. def keys( self ):
  326. """Returns all named result keys."""
  327. return self.__tokdict.keys()
  328. def pop( self, index=-1 ):
  329. """Removes and returns item at specified index (default=last).
  330. Will work with either numeric indices or dict-key indicies."""
  331. ret = self[index]
  332. del self[index]
  333. return ret
  334. def get(self, key, defaultValue=None):
  335. """Returns named result matching the given key, or if there is no
  336. such name, then returns the given C{defaultValue} or C{None} if no
  337. C{defaultValue} is specified."""
  338. if key in self:
  339. return self[key]
  340. else:
  341. return defaultValue
  342. def insert( self, index, insStr ):
  343. """Inserts new element at location index in the list of parsed tokens."""
  344. self.__toklist.insert(index, insStr)
  345. # fixup indices in token dictionary
  346. for name in self.__tokdict:
  347. occurrences = self.__tokdict[name]
  348. for k, (value, position) in enumerate(occurrences):
  349. occurrences[k] = _ParseResultsWithOffset(value, position + (position > index))
  350. def items( self ):
  351. """Returns all named result keys and values as a list of tuples."""
  352. return [(k,self[k]) for k in self.__tokdict]
  353. def values( self ):
  354. """Returns all named result values."""
  355. return [ v[-1][0] for v in self.__tokdict.values() ]
  356. def __getattr__( self, name ):
  357. if True: #name not in self.__slots__:
  358. if name in self.__tokdict:
  359. if name not in self.__accumNames:
  360. return self.__tokdict[name][-1][0]
  361. else:
  362. return ParseResults([ v[0] for v in self.__tokdict[name] ])
  363. else:
  364. return ""
  365. return None
  366. def __add__( self, other ):
  367. ret = self.copy()
  368. ret += other
  369. return ret
  370. def __iadd__( self, other ):
  371. if other.__tokdict:
  372. offset = len(self.__toklist)
  373. addoffset = ( lambda a: (a<0 and offset) or (a+offset) )
  374. otheritems = other.__tokdict.items()
  375. otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) )
  376. for (k,vlist) in otheritems for v in vlist]
  377. for k,v in otherdictitems:
  378. self[k] = v
  379. if isinstance(v[0],ParseResults):
  380. v[0].__parent = wkref(self)
  381. self.__toklist += other.__toklist
  382. self.__accumNames.update( other.__accumNames )
  383. return self
  384. def __radd__(self, other):
  385. if isinstance(other,int) and other == 0:
  386. return self.copy()
  387. def __repr__( self ):
  388. return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) )
  389. def __str__( self ):
  390. out = "["
  391. sep = ""
  392. for i in self.__toklist:
  393. if isinstance(i, ParseResults):
  394. out += sep + _ustr(i)
  395. else:
  396. out += sep + repr(i)
  397. sep = ", "
  398. out += "]"
  399. return out
  400. def _asStringList( self, sep='' ):
  401. out = []
  402. for item in self.__toklist:
  403. if out and sep:
  404. out.append(sep)
  405. if isinstance( item, ParseResults ):
  406. out += item._asStringList()
  407. else:
  408. out.append( _ustr(item) )
  409. return out
  410. def asList( self ):
  411. """Returns the parse results as a nested list of matching tokens, all converted to strings."""
  412. out = []
  413. for res in self.__toklist:
  414. if isinstance(res,ParseResults):
  415. out.append( res.asList() )
  416. else:
  417. out.append( res )
  418. return out
  419. def asDict( self ):
  420. """Returns the named parse results as dictionary."""
  421. return dict( self.items() )
  422. def copy( self ):
  423. """Returns a new copy of a C{ParseResults} object."""
  424. ret = ParseResults( self.__toklist )
  425. ret.__tokdict = self.__tokdict.copy()
  426. ret.__parent = self.__parent
  427. ret.__accumNames.update( self.__accumNames )
  428. ret.__name = self.__name
  429. return ret
  430. def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
  431. """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names."""
  432. nl = "\n"
  433. out = []
  434. namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items()
  435. for v in vlist ] )
  436. nextLevelIndent = indent + " "
  437. # collapse out indents if formatting is not desired
  438. if not formatted:
  439. indent = ""
  440. nextLevelIndent = ""
  441. nl = ""
  442. selfTag = None
  443. if doctag is not None:
  444. selfTag = doctag
  445. else:
  446. if self.__name:
  447. selfTag = self.__name
  448. if not selfTag:
  449. if namedItemsOnly:
  450. return ""
  451. else:
  452. selfTag = "ITEM"
  453. out += [ nl, indent, "<", selfTag, ">" ]
  454. worklist = self.__toklist
  455. for i,res in enumerate(worklist):
  456. if isinstance(res,ParseResults):
  457. if i in namedItems:
  458. out += [ res.asXML(namedItems[i],
  459. namedItemsOnly and doctag is None,
  460. nextLevelIndent,
  461. formatted)]
  462. else:
  463. out += [ res.asXML(None,
  464. namedItemsOnly and doctag is None,
  465. nextLevelIndent,
  466. formatted)]
  467. else:
  468. # individual token, see if there is a name for it
  469. resTag = None
  470. if i in namedItems:
  471. resTag = namedItems[i]
  472. if not resTag:
  473. if namedItemsOnly:
  474. continue
  475. else:
  476. resTag = "ITEM"
  477. xmlBodyText = _xml_escape(_ustr(res))
  478. out += [ nl, nextLevelIndent, "<", resTag, ">",
  479. xmlBodyText,
  480. "</", resTag, ">" ]
  481. out += [ nl, indent, "</", selfTag, ">" ]
  482. return "".join(out)
  483. def __lookup(self,sub):
  484. for k,vlist in self.__tokdict.items():
  485. for v,loc in vlist:
  486. if sub is v:
  487. return k
  488. return None
  489. def getName(self):
  490. """Returns the results name for this token expression."""
  491. if self.__name:
  492. return self.__name
  493. elif self.__parent:
  494. par = self.__parent()
  495. if par:
  496. return par.__lookup(self)
  497. else:
  498. return None
  499. elif (len(self) == 1 and
  500. len(self.__tokdict) == 1 and
  501. self.__tokdict.values()[0][0][1] in (0,-1)):
  502. return self.__tokdict.keys()[0]
  503. else:
  504. return None
  505. def dump(self,indent='',depth=0):
  506. """Diagnostic method for listing out the contents of a C{ParseResults}.
  507. Accepts an optional C{indent} argument so that this string can be embedded
  508. in a nested display of other data."""
  509. out = []
  510. out.append( indent+_ustr(self.asList()) )
  511. keys = self.items()
  512. keys.sort()
  513. for k,v in keys:
  514. if out:
  515. out.append('\n')
  516. out.append( "%s%s- %s: " % (indent,(' '*depth), k) )
  517. if isinstance(v,ParseResults):
  518. if v.keys():
  519. out.append( v.dump(indent,depth+1) )
  520. else:
  521. out.append(_ustr(v))
  522. else:
  523. out.append(_ustr(v))
  524. return "".join(out)
  525. # add support for pickle protocol
  526. def __getstate__(self):
  527. return ( self.__toklist,
  528. ( self.__tokdict.copy(),
  529. self.__parent is not None and self.__parent() or None,
  530. self.__accumNames,
  531. self.__name ) )
  532. def __setstate__(self,state):
  533. self.__toklist = state[0]
  534. self.__tokdict, \
  535. par, \
  536. inAccumNames, \
  537. self.__name = state[1]
  538. self.__accumNames = {}
  539. self.__accumNames.update(inAccumNames)
  540. if par is not None:
  541. self.__parent = wkref(par)
  542. else:
  543. self.__parent = None
  544. def __dir__(self):
  545. return dir(super(ParseResults,self)) + self.keys()
  546. collections.MutableMapping.register(ParseResults)
  547. def col (loc,strg):
  548. """Returns current column within a string, counting newlines as line separators.
  549. The first column is number 1.
  550. Note: the default parsing behavior is to expand tabs in the input string
  551. before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
  552. on parsing strings containing <TAB>s, and suggested methods to maintain a
  553. consistent view of the parsed string, the parse location, and line and column
  554. positions within the parsed string.
  555. """
  556. return (loc<len(strg) and strg[loc] == '\n') and 1 or loc - strg.rfind("\n", 0, loc)
  557. def lineno(loc,strg):
  558. """Returns current line number within a string, counting newlines as line separators.
  559. The first line is number 1.
  560. Note: the default parsing behavior is to expand tabs in the input string
  561. before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
  562. on parsing strings containing <TAB>s, and suggested methods to maintain a
  563. consistent view of the parsed string, the parse location, and line and column
  564. positions within the parsed string.
  565. """
  566. return strg.count("\n",0,loc) + 1
  567. def line( loc, strg ):
  568. """Returns the line of text containing loc within a string, counting newlines as line separators.
  569. """
  570. lastCR = strg.rfind("\n", 0, loc)
  571. nextCR = strg.find("\n", loc)
  572. if nextCR >= 0:
  573. return strg[lastCR+1:nextCR]
  574. else:
  575. return strg[lastCR+1:]
  576. def _defaultStartDebugAction( instring, loc, expr ):
  577. print ("Match " + _ustr(expr) + " at loc " + _ustr(loc) + "(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
  578. def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ):
  579. print ("Matched " + _ustr(expr) + " -> " + str(toks.asList()))
  580. def _defaultExceptionDebugAction( instring, loc, expr, exc ):
  581. print ("Exception raised:" + _ustr(exc))
  582. def nullDebugAction(*args):
  583. """'Do-nothing' debug action, to suppress debugging output during parsing."""
  584. pass
  585. class ParserElement(object):
  586. """Abstract base level parser element class."""
  587. DEFAULT_WHITE_CHARS = " \n\t\r"
  588. verbose_stacktrace = False
  589. def setDefaultWhitespaceChars( chars ):
  590. """Overrides the default whitespace chars
  591. """
  592. ParserElement.DEFAULT_WHITE_CHARS = chars
  593. setDefaultWhitespaceChars = staticmethod(setDefaultWhitespaceChars)
  594. def __init__( self, savelist=False ):
  595. self.parseAction = list()
  596. self.failAction = None
  597. #~ self.name = "<unknown>" # don't define self.name, let subclasses try/except upcall
  598. self.strRepr = None
  599. self.resultsName = None
  600. self.saveAsList = savelist
  601. self.skipWhitespace = True
  602. self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
  603. self.copyDefaultWhiteChars = True
  604. self.mayReturnEmpty = False # used when checking for left-recursion
  605. self.keepTabs = False
  606. self.ignoreExprs = list()
  607. self.debug = False
  608. self.streamlined = False
  609. self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index
  610. self.errmsg = ""
  611. self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all)
  612. self.debugActions = ( None, None, None ) #custom debug actions
  613. self.re = None
  614. self.callPreparse = True # used to avoid redundant calls to preParse
  615. self.callDuringTry = False
  616. def copy( self ):
  617. """Make a copy of this C{ParserElement}. Useful for defining different parse actions
  618. for the same parsing pattern, using copies of the original parse element."""
  619. cpy = copy.copy( self )
  620. cpy.parseAction = self.parseAction[:]
  621. cpy.ignoreExprs = self.ignoreExprs[:]
  622. if self.copyDefaultWhiteChars:
  623. cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
  624. return cpy
  625. def setName( self, name ):
  626. """Define name for this expression, for use in debugging."""
  627. self.name = name
  628. self.errmsg = "Expected " + self.name
  629. if hasattr(self,"exception"):
  630. self.exception.msg = self.errmsg
  631. return self
  632. def setResultsName( self, name, listAllMatches=False ):
  633. """Define name for referencing matching tokens as a nested attribute
  634. of the returned parse results.
  635. NOTE: this returns a *copy* of the original C{ParserElement} object;
  636. this is so that the client can define a basic element, such as an
  637. integer, and reference it in multiple places with different names.
  638. You can also set results names using the abbreviated syntax,
  639. C{expr("name")} in place of C{expr.setResultsName("name")} -
  640. see L{I{__call__}<__call__>}.
  641. """
  642. newself = self.copy()
  643. newself.resultsName = name
  644. newself.modalResults = not listAllMatches
  645. return newself
  646. def setBreak(self,breakFlag = True):
  647. """Method to invoke the Python pdb debugger when this element is
  648. about to be parsed. Set C{breakFlag} to True to enable, False to
  649. disable.
  650. """
  651. if breakFlag:
  652. _parseMethod = self._parse
  653. def breaker(instring, loc, doActions=True, callPreParse=True):
  654. import pdb
  655. pdb.set_trace()
  656. return _parseMethod( instring, loc, doActions, callPreParse )
  657. breaker._originalParseMethod = _parseMethod
  658. self._parse = breaker
  659. else:
  660. if hasattr(self._parse,"_originalParseMethod"):
  661. self._parse = self._parse._originalParseMethod
  662. return self
  663. def _normalizeParseActionArgs( f ):
  664. """Internal method used to decorate parse actions that take fewer than 3 arguments,
  665. so that all parse actions can be called as C{f(s,l,t)}."""
  666. STAR_ARGS = 4
  667. # special handling for single-argument builtins
  668. if (f in singleArgBuiltins):
  669. numargs = 1
  670. else:
  671. try:
  672. restore = None
  673. if isinstance(f,type):
  674. restore = f
  675. f = f.__init__
  676. if not _PY3K:
  677. codeObj = f.func_code
  678. else:
  679. codeObj = f.code
  680. if codeObj.co_flags & STAR_ARGS:
  681. return f
  682. numargs = codeObj.co_argcount
  683. if not _PY3K:
  684. if hasattr(f,"im_self"):
  685. numargs -= 1
  686. else:
  687. if hasattr(f,"__self__"):
  688. numargs -= 1
  689. if restore:
  690. f = restore
  691. except AttributeError:
  692. try:
  693. if not _PY3K:
  694. call_im_func_code = f.__call__.im_func.func_code
  695. else:
  696. call_im_func_code = f.__code__
  697. # not a function, must be a callable object, get info from the
  698. # im_func binding of its bound __call__ method
  699. if call_im_func_code.co_flags & STAR_ARGS:
  700. return f
  701. numargs = call_im_func_code.co_argcount
  702. if not _PY3K:
  703. if hasattr(f.__call__,"im_self"):
  704. numargs -= 1
  705. else:
  706. if hasattr(f.__call__,"__self__"):
  707. numargs -= 0
  708. except AttributeError:
  709. if not _PY3K:
  710. call_func_code = f.__call__.func_code
  711. else:
  712. call_func_code = f.__call__.__code__
  713. # not a bound method, get info directly from __call__ method
  714. if call_func_code.co_flags & STAR_ARGS:
  715. return f
  716. numargs = call_func_code.co_argcount
  717. if not _PY3K:
  718. if hasattr(f.__call__,"im_self"):
  719. numargs -= 1
  720. else:
  721. if hasattr(f.__call__,"__self__"):
  722. numargs -= 1
  723. # print ("adding function %s with %d args" % (f.func_name,numargs))
  724. if numargs == 3:
  725. return f
  726. else:
  727. if numargs > 3:
  728. def tmp(s,l,t):
  729. return f(s,l,t)
  730. elif numargs == 2:
  731. def tmp(s,l,t):
  732. return f(l,t)
  733. elif numargs == 1:
  734. def tmp(s,l,t):
  735. return f(t)
  736. else: #~ numargs == 0:
  737. def tmp(s,l,t):
  738. return f()
  739. try:
  740. tmp.__name__ = f.__name__
  741. except (AttributeError,TypeError):
  742. # no need for special handling if attribute doesnt exist
  743. pass
  744. try:
  745. tmp.__doc__ = f.__doc__
  746. except (AttributeError,TypeError):
  747. # no need for special handling if attribute doesnt exist
  748. pass
  749. try:
  750. tmp.__dict__.update(f.__dict__)
  751. except (AttributeError,TypeError):
  752. # no need for special handling if attribute doesnt exist
  753. pass
  754. return tmp
  755. _normalizeParseActionArgs = staticmethod(_normalizeParseActionArgs)
  756. def setParseAction( self, *fns, **kwargs ):
  757. """Define action to perform when successfully matching parse element definition.
  758. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
  759. C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
  760. - s = the original string being parsed (see note below)
  761. - loc = the location of the matching substring
  762. - toks = a list of the matched tokens, packaged as a ParseResults object
  763. If the functions in fns modify the tokens, they can return them as the return
  764. value from fn, and the modified list of tokens will replace the original.
  765. Otherwise, fn does not need to return any value.
  766. Note: the default parsing behavior is to expand tabs in the input string
  767. before starting the parsing process. See L{I{parseString}<parseString>} for more information
  768. on parsing strings containing <TAB>s, and suggested methods to maintain a
  769. consistent view of the parsed string, the parse location, and line and column
  770. positions within the parsed string.
  771. """
  772. self.parseAction = list(map(self._normalizeParseActionArgs, list(fns)))
  773. self.callDuringTry = ("callDuringTry" in kwargs and kwargs["callDuringTry"])
  774. return self
  775. def addParseAction( self, *fns, **kwargs ):
  776. """Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}."""
  777. self.parseAction += list(map(self._normalizeParseActionArgs, list(fns)))
  778. self.callDuringTry = self.callDuringTry or ("callDuringTry" in kwargs and kwargs["callDuringTry"])
  779. return self
  780. def setFailAction( self, fn ):
  781. """Define action to perform if parsing fails at this expression.
  782. Fail acton fn is a callable function that takes the arguments
  783. C{fn(s,loc,expr,err)} where:
  784. - s = string being parsed
  785. - loc = location where expression match was attempted and failed
  786. - expr = the parse expression that failed
  787. - err = the exception thrown
  788. The function returns no value. It may throw C{ParseFatalException}
  789. if it is desired to stop parsing immediately."""
  790. self.failAction = fn
  791. return self
  792. def _skipIgnorables( self, instring, loc ):
  793. exprsFound = True
  794. while exprsFound:
  795. exprsFound = False
  796. for e in self.ignoreExprs:
  797. try:
  798. while 1:
  799. loc,dummy = e._parse( instring, loc )
  800. exprsFound = True
  801. except ParseException:
  802. pass
  803. return loc
  804. def preParse( self, instring, loc ):
  805. if self.ignoreExprs:
  806. loc = self._skipIgnorables( instring, loc )
  807. if self.skipWhitespace:
  808. wt = self.whiteChars
  809. instrlen = len(instring)
  810. while loc < instrlen and instring[loc] in wt:
  811. loc += 1
  812. return loc
  813. def parseImpl( self, instring, loc, doActions=True ):
  814. return loc, []
  815. def postParse( self, instring, loc, tokenlist ):
  816. return tokenlist
  817. #~ @profile
  818. def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
  819. debugging = ( self.debug ) #and doActions )
  820. if debugging or self.failAction:
  821. #~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
  822. if (self.debugActions[0] ):
  823. self.debugActions[0]( instring, loc, self )
  824. if callPreParse and self.callPreparse:
  825. preloc = self.preParse( instring, loc )
  826. else:
  827. preloc = loc
  828. tokensStart = preloc
  829. try:
  830. try:
  831. loc,tokens = self.parseImpl( instring, preloc, doActions )
  832. except IndexError:
  833. raise ParseException( instring, len(instring), self.errmsg, self )
  834. except ParseBaseException as err:
  835. #~ print ("Exception raised:", err)
  836. if self.debugActions[2]:
  837. self.debugActions[2]( instring, tokensStart, self, err )
  838. if self.failAction:
  839. self.failAction( instring, tokensStart, self, err )
  840. raise
  841. else:
  842. if callPreParse and self.callPreparse:
  843. preloc = self.preParse( instring, loc )
  844. else:
  845. preloc = loc
  846. tokensStart = preloc
  847. if self.mayIndexError or loc >= len(instring):
  848. try:
  849. loc,tokens = self.parseImpl( instring, preloc, doActions )
  850. except IndexError:
  851. raise ParseException( instring, len(instring), self.errmsg, self )
  852. else:
  853. loc,tokens = self.parseImpl( instring, preloc, doActions )
  854. tokens = self.postParse( instring, loc, tokens )
  855. retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )
  856. if self.parseAction and (doActions or self.callDuringTry):
  857. if debugging:
  858. try:
  859. for fn in self.parseAction:
  860. tokens = fn( instring, tokensStart, retTokens )
  861. if tokens is not None:
  862. retTokens = ParseResults( tokens,
  863. self.resultsName,
  864. asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
  865. modal=self.modalResults )
  866. except ParseBaseException as err:
  867. #~ print "Exception raised in user parse action:", err
  868. if (self.debugActions[2] ):
  869. self.debugActions[2]( instring, tokensStart, self, err )
  870. raise
  871. else:
  872. for fn in self.parseAction:
  873. tokens = fn( instring, tokensStart, retTokens )
  874. if tokens is not None:
  875. retTokens = ParseResults( tokens,
  876. self.resultsName,
  877. asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
  878. modal=self.modalResults )
  879. if debugging:
  880. #~ print ("Matched",self,"->",retTokens.asList())
  881. if (self.debugActions[1] ):
  882. self.debugActions[1]( instring, tokensStart, loc, self, retTokens )
  883. return loc, retTokens
  884. def tryParse( self, instring, loc ):
  885. try:
  886. return self._parse( instring, loc, doActions=False )[0]
  887. except ParseFatalException:
  888. raise ParseException( instring, loc, self.errmsg, self)
  889. # this method gets repeatedly called during backtracking with the same arguments -
  890. # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
  891. def _parseCache( self, instring, loc, doActions=True, callPreParse=True ):
  892. lookup = (self,instring,loc,callPreParse,doActions)
  893. if lookup in ParserElement._exprArgCache:
  894. value = ParserElement._exprArgCache[ lookup ]
  895. if isinstance(value, Exception):
  896. raise value
  897. return value
  898. else:
  899. try:
  900. value = self._parseNoCache( instring, loc, doActions, callPreParse )
  901. ParserElement._exprArgCache[ lookup ] = (value[0],value[1].copy())
  902. return value
  903. except ParseBaseException as err:
  904. err.__traceback__ = None
  905. ParserElement._exprArgCache[ lookup ] = err
  906. raise
  907. _parse = _parseNoCache
  908. # argument cache for optimizing repeated calls when backtracking through recursive expressions
  909. _exprArgCache = {}
  910. def resetCache():
  911. ParserElement._exprArgCache.clear()
  912. resetCache = staticmethod(resetCache)
  913. _packratEnabled = False
  914. def enablePackrat():
  915. """Enables "packrat" parsing, which adds memoizing to the parsing logic.
  916. Repeated parse attempts at the same string location (which happens
  917. often in many complex grammars) can immediately return a cached value,
  918. instead of re-executing parsing/validating code. Memoizing is done of
  919. both valid results and parsing exceptions.
  920. This speedup may break existing programs that use parse actions that
  921. have side-effects. For this reason, packrat parsing is disabled when
  922. you first import pyparsing. To activate the packrat feature, your
  923. program must call the class method C{ParserElement.enablePackrat()}. If
  924. your program uses C{psyco} to "compile as you go", you must call
  925. C{enablePackrat} before calling C{psyco.full()}. If you do not do this,
  926. Python will crash. For best results, call C{enablePackrat()} immediately
  927. after importing pyparsing.
  928. """
  929. if not ParserElement._packratEnabled:
  930. ParserElement._packratEnabled = True
  931. ParserElement._parse = ParserElement._parseCache
  932. enablePackrat = staticmethod(enablePackrat)
  933. def parseString( self, instring, parseAll=False ):
  934. """Execute the parse expression with the given string.
  935. This is the main interface to the client code, once the complete
  936. expression has been built.
  937. If you want the grammar to require that the entire input string be
  938. successfully parsed, then set C{parseAll} to True (equivalent to ending
  939. the grammar with C{StringEnd()}).
  940. Note: C{parseString} implicitly calls C{expandtabs()} on the input string,
  941. in order to report proper column numbers in parse actions.
  942. If the input string contains tabs and
  943. the grammar uses parse actions that use the C{loc} argument to index into the
  944. string being parsed, you can ensure you have a consistent view of the input
  945. string by:
  946. - calling C{parseWithTabs} on your grammar before calling C{parseString}
  947. (see L{I{parseWithTabs}<parseWithTabs>})
  948. - define your parse action using the full C{(s,loc,toks)} signature, and
  949. reference the input string using the parse action's C{s} argument
  950. - explictly expand the tabs in your input string before calling
  951. C{parseString}
  952. """
  953. ParserElement.resetCache()
  954. if not self.streamlined:
  955. self.streamline()
  956. #~ self.saveAsList = True
  957. for e in self.ignoreExprs:
  958. e.streamline()
  959. if not self.keepTabs:
  960. instring = instring.expandtabs()
  961. try:
  962. loc, tokens = self._parse( instring, 0 )
  963. if parseAll:
  964. #loc = self.preParse( instring, loc )
  965. se = StringEnd()
  966. se._parse( instring, loc )
  967. except ParseBaseException as err:
  968. if ParserElement.verbose_stacktrace:
  969. raise
  970. else:
  971. # catch and re-raise exception from here, clears out pyparsing internal stack trace
  972. raise err
  973. else:
  974. return tokens
  975. def scanString( self, instring, maxMatches=_MAX_INT ):
  976. """Scan the input string for expression matches. Each match will return the
  977. matching tokens, start location, and end location. May be called with optional
  978. C{maxMatches} argument, to clip scanning after 'n' matches are found.
  979. Note that the start and end locations are reported relative to the string
  980. being parsed. See L{I{parseString}<parseString>} for more information on parsing
  981. strings with embedded tabs."""
  982. if not self.streamlined:
  983. self.streamline()
  984. for e in self.ignoreExprs:
  985. e.streamline()
  986. if not self.keepTabs:
  987. instring = _ustr(instring).expandtabs()
  988. instrlen = len(instring)
  989. loc = 0
  990. preparseFn = self.preParse
  991. parseFn = self._parse
  992. ParserElement.resetCache()
  993. matches = 0
  994. try:
  995. while loc <= instrlen and matches < maxMatches:
  996. try:
  997. preloc = preparseFn( instring, loc )
  998. nextLoc,tokens = parseFn( instring, preloc, callPreParse=False )
  999. except ParseException:
  1000. loc = preloc+1
  1001. else:
  1002. if nextLoc > loc:
  1003. matches += 1
  1004. yield tokens, preloc, nextLoc
  1005. loc = nextLoc
  1006. else:
  1007. loc = preloc+1
  1008. except ParseBaseException as err:
  1009. if ParserElement.verbose_stacktrace:
  1010. raise
  1011. else:
  1012. # catch and re-raise exception from here, clears out pyparsing internal stack trace
  1013. raise err
  1014. def transformString( self, instring ):
  1015. """Extension to C{scanString}, to modify matching text with modified tokens that may
  1016. be returned from a parse action. To use C{transformString}, define a grammar and
  1017. attach a parse action to it that modifies the returned token list.
  1018. Invoking C{transformString()} on a target string will then scan for matches,
  1019. and replace the matched text patterns according to the logic in the parse
  1020. action. C{transformString()} returns the resulting transformed string."""
  1021. out = []
  1022. lastE = 0
  1023. # force preservation of <TAB>s, to minimize unwanted transformation of string, and to
  1024. # keep string locs straight between transformString and scanString
  1025. self.keepTabs = True
  1026. try:
  1027. for t,s,e in self.scanString( instring ):
  1028. out.append( instring[lastE:s] )
  1029. if t:
  1030. if isinstance(t,ParseResults):
  1031. out += t.asList()
  1032. elif isinstance(t,list):
  1033. out += t
  1034. else:
  1035. out.append(t)
  1036. lastE = e
  1037. out.append(instring[lastE:])
  1038. return "".join(map(_ustr,out))
  1039. except ParseBaseException as err:
  1040. if ParserElement.verbose_stacktrace:
  1041. raise
  1042. else:
  1043. # catch and re-raise exception from here, clears out pyparsing internal stack trace
  1044. raise err
  1045. def searchString( self, instring, maxMatches=_MAX_INT ):
  1046. """Another extension to C{scanString}, simplifying the access to the tokens found
  1047. to match the given parse expression. May be called with optional
  1048. C{maxMatches} argument, to clip searching after 'n' matches are found.
  1049. """
  1050. try:
  1051. return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
  1052. except ParseBaseException as err:
  1053. if ParserElement.verbose_stacktrace:
  1054. raise
  1055. else:
  1056. # catch and re-raise exception from here, clears out pyparsing internal stack trace
  1057. raise err
  1058. def __add__(self, other ):
  1059. """Implementation of + operator - returns And"""
  1060. if isinstance( other, basestring ):
  1061. other = Literal( other )
  1062. if not isinstance( other, ParserElement ):
  1063. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1064. SyntaxWarning, stacklevel=2)
  1065. return None
  1066. return And( [ self, other ] )
  1067. def __radd__(self, other ):
  1068. """Implementation of + operator when left operand is not a C{ParserElement}"""
  1069. if isinstance( other, basestring ):
  1070. other = Literal( other )
  1071. if not isinstance( other, ParserElement ):
  1072. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1073. SyntaxWarning, stacklevel=2)
  1074. return None
  1075. return other + self
  1076. def __sub__(self, other):
  1077. """Implementation of - operator, returns C{And} with error stop"""
  1078. if isinstance( other, basestring ):
  1079. other = Literal( other )
  1080. if not isinstance( other, ParserElement ):
  1081. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1082. SyntaxWarning, stacklevel=2)
  1083. return None
  1084. return And( [ self, And._ErrorStop(), other ] )
  1085. def __rsub__(self, other ):
  1086. """Implementation of - operator when left operand is not a C{ParserElement}"""
  1087. if isinstance( other, basestring ):
  1088. other = Literal( other )
  1089. if not isinstance( other, ParserElement ):
  1090. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1091. SyntaxWarning, stacklevel=2)
  1092. return None
  1093. return other - self
  1094. def __mul__(self,other):
  1095. """Implementation of * operator, allows use of C{expr * 3} in place of
  1096. C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
  1097. tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
  1098. may also include C{None} as in:
  1099. - C{expr*(n,None)} or C{expr*(n,)} is equivalent
  1100. to C{expr*n + ZeroOrMore(expr)}
  1101. (read as "at least n instances of C{expr}")
  1102. - C{expr*(None,n)} is equivalent to C{expr*(0,n)}
  1103. (read as "0 to n instances of C{expr}")
  1104. - C{expr*(None,None)} is equivalent to C{ZeroOrMore(expr)}
  1105. - C{expr*(1,None)} is equivalent to C{OneOrMore(expr)}
  1106. Note that C{expr*(None,n)} does not raise an exception if
  1107. more than n exprs exist in the input stream; that is,
  1108. C{expr*(None,n)} does not enforce a maximum number of expr
  1109. occurrences. If this behavior is desired, then write
  1110. C{expr*(None,n) + ~expr}
  1111. """
  1112. if isinstance(other,int):
  1113. minElements, optElements = other,0
  1114. elif isinstance(other,tuple):
  1115. other = (other + (None, None))[:2]
  1116. if other[0] is None:
  1117. other = (0, other[1])
  1118. if isinstance(other[0],int) and other[1] is None:
  1119. if other[0] == 0:
  1120. return ZeroOrMore(self)
  1121. if other[0] == 1:
  1122. return OneOrMore(self)
  1123. else:
  1124. return self*other[0] + ZeroOrMore(self)
  1125. elif isinstance(other[0],int) and isinstance(other[1],int):
  1126. minElements, optElements = other
  1127. optElements -= minElements
  1128. else:
  1129. raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1]))
  1130. else:
  1131. raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
  1132. if minElements < 0:
  1133. raise ValueError("cannot multiply ParserElement by negative value")
  1134. if optElements < 0:
  1135. raise ValueError("second tuple value must be greater or equal to first tuple value")
  1136. if minElements == optElements == 0:
  1137. raise ValueError("cannot multiply ParserElement by 0 or (0,0)")
  1138. if (optElements):
  1139. def makeOptionalList(n):
  1140. if n>1:
  1141. return Optional(self + makeOptionalList(n-1))
  1142. else:
  1143. return Optional(self)
  1144. if minElements:
  1145. if minElements == 1:
  1146. ret = self + makeOptionalList(optElements)
  1147. else:
  1148. ret = And([self]*minElements) + makeOptionalList(optElements)
  1149. else:
  1150. ret = makeOptionalList(optElements)
  1151. else:
  1152. if minElements == 1:
  1153. ret = self
  1154. else:
  1155. ret = And([self]*minElements)
  1156. return ret
  1157. def __rmul__(self, other):
  1158. return self.__mul__(other)
  1159. def __or__(self, other ):
  1160. """Implementation of | operator - returns C{MatchFirst}"""
  1161. if isinstance( other, basestring ):
  1162. other = Literal( other )
  1163. if not isinstance( other, ParserElement ):
  1164. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1165. SyntaxWarning, stacklevel=2)
  1166. return None
  1167. return MatchFirst( [ self, other ] )
  1168. def __ror__(self, other ):
  1169. """Implementation of | operator when left operand is not a C{ParserElement}"""
  1170. if isinstance( other, basestring ):
  1171. other = Literal( other )
  1172. if not isinstance( other, ParserElement ):
  1173. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1174. SyntaxWarning, stacklevel=2)
  1175. return None
  1176. return other | self
  1177. def __xor__(self, other ):
  1178. """Implementation of ^ operator - returns C{Or}"""
  1179. if isinstance( other, basestring ):
  1180. other = Literal( other )
  1181. if not isinstance( other, ParserElement ):
  1182. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1183. SyntaxWarning, stacklevel=2)
  1184. return None
  1185. return Or( [ self, other ] )
  1186. def __rxor__(self, other ):
  1187. """Implementation of ^ operator when left operand is not a C{ParserElement}"""
  1188. if isinstance( other, basestring ):
  1189. other = Literal( other )
  1190. if not isinstance( other, ParserElement ):
  1191. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1192. SyntaxWarning, stacklevel=2)
  1193. return None
  1194. return other ^ self
  1195. def __and__(self, other ):
  1196. """Implementation of & operator - returns C{Each}"""
  1197. if isinstance( other, basestring ):
  1198. other = Literal( other )
  1199. if not isinstance( other, ParserElement ):
  1200. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1201. SyntaxWarning, stacklevel=2)
  1202. return None
  1203. return Each( [ self, other ] )
  1204. def __rand__(self, other ):
  1205. """Implementation of & operator when left operand is not a C{ParserElement}"""
  1206. if isinstance( other, basestring ):
  1207. other = Literal( other )
  1208. if not isinstance( other, ParserElement ):
  1209. warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
  1210. SyntaxWarning, stacklevel=2)
  1211. return None
  1212. return other & self
  1213. def __invert__( self ):
  1214. """Implementation of ~ operator - returns C{NotAny}"""
  1215. return NotAny( self )
  1216. def __call__(self, name):
  1217. """Shortcut for C{setResultsName}, with C{listAllMatches=default}::
  1218. userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
  1219. could be written as::
  1220. userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
  1221. """
  1222. return self.setResultsName(name)
  1223. def suppress( self ):
  1224. """Suppresses the output of this C{ParserElement}; useful to keep punctuation from
  1225. cluttering up returned output.
  1226. """
  1227. return Suppress( self )
  1228. def leaveWhitespace( self ):
  1229. """Disables the skipping of whitespace before matching the characters in the
  1230. C{ParserElement}'s defined pattern. This is normally only used internally by
  1231. the pyparsing module, but may be needed in some whitespace-sensitive grammars.
  1232. """
  1233. self.skipWhitespace = False
  1234. return self
  1235. def setWhitespaceChars( self, chars ):
  1236. """Overrides the default whitespace chars
  1237. """
  1238. self.skipWhitespace = True
  1239. self.whiteChars = chars
  1240. self.copyDefaultWhiteChars = False
  1241. return self
  1242. def parseWithTabs( self ):
  1243. """Overrides default behavior to expand <TAB>s to spaces before parsing the input string.
  1244. Must be called before C{parseString} when the input grammar contains elements that
  1245. match <TAB> characters."""
  1246. self.keepTabs = True
  1247. return self
  1248. def ignore( self, other ):
  1249. """Define expression to be ignored (e.g., comments) while doing pattern
  1250. matching; may be called repeatedly, to define multiple comment or other
  1251. ignorable patterns.
  1252. """
  1253. if isinstance( other, Suppress ):
  1254. if other not in self.ignoreExprs:
  1255. self.ignoreExprs.append( other.copy() )
  1256. else:
  1257. self.ignoreExprs.append( Suppress( other.copy() ) )
  1258. return self
  1259. def setDebugActions( self, startAction, successAction, exceptionAction ):
  1260. """Enable display of debugging messages while doing pattern matching."""
  1261. self.debugActions = (startAction or _defaultStartDebugAction,
  1262. successAction or _defaultSuccessDebugAction,
  1263. exceptionAction or _defaultExceptionDebugAction)
  1264. self.debug = True
  1265. return self
  1266. def setDebug( self, flag=True ):
  1267. """Enable display of debugging messages while doing pattern matching.
  1268. Set C{flag} to True to enable, False to disable."""
  1269. if flag:
  1270. self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
  1271. else:
  1272. self.debug = False
  1273. return self
  1274. def __str__( self ):
  1275. return self.name
  1276. def __repr__( self ):
  1277. return _ustr(self)
  1278. def streamline( self ):
  1279. self.streamlined = True
  1280. self.strRepr = None
  1281. return self
  1282. def checkRecursion( self, parseElementList ):
  1283. pass
  1284. def validate( self, validateTrace=[] ):
  1285. """Check defined expressions for valid structure, check for infinite recursive definitions."""
  1286. self.checkRecursion( [] )
  1287. def parseFile( self, file_or_filename, parseAll=False ):
  1288. """Execute the parse expression on the given file or filename.
  1289. If a filename is specified (instead of a file object),
  1290. the entire file is opened, read, and closed before parsing.
  1291. """
  1292. try:
  1293. file_contents = file_or_filename.read()
  1294. except AttributeError:
  1295. f = open(file_or_filename, "rb")
  1296. file_contents = f.read()
  1297. f.close()
  1298. try:
  1299. return self.parseString(file_contents, parseAll)
  1300. except ParseBaseException as err:
  1301. # catch and re-raise exception from here, clears out pyparsing internal stack trace
  1302. raise err
  1303. def __eq__(self,other):
  1304. if isinstance(other, ParserElement):
  1305. return self is other or self.__dict__ == other.__dict__
  1306. elif isinstance(other, basestring):
  1307. try:
  1308. self.parseString(_ustr(other), parseAll=True)
  1309. return True
  1310. except ParseBaseException:
  1311. return False
  1312. else:
  1313. return super(ParserElement,self)==other
  1314. def __ne__(self,other):
  1315. return not (self == other)
  1316. def __hash__(self):
  1317. return hash(id(self))
  1318. def __req__(self,other):
  1319. return self == other
  1320. def __rne__(self,other):
  1321. return not (self == other)
  1322. class Token(ParserElement):
  1323. """Abstract C{ParserElement} subclass, for defining atomic matching patterns."""
  1324. def __init__( self ):
  1325. super(Token,self).__init__( savelist=False )
  1326. #self.myException = ParseException("",0,"",self)
  1327. def setName(self, name):
  1328. s = super(Token,self).setName(name)
  1329. self.errmsg = "Expected " + self.name
  1330. #s.myException.msg = self.errmsg
  1331. return s
  1332. class Empty(Token):
  1333. """An empty token, will always match."""
  1334. def __init__( self ):
  1335. super(Empty,self).__init__()
  1336. self.name = "Empty"
  1337. self.mayReturnEmpty = True
  1338. self.mayIndexError = False
  1339. class NoMatch(Token):
  1340. """A token that will never match."""
  1341. def __init__( self ):
  1342. super(NoMatch,self).__init__()
  1343. self.name = "NoMatch"
  1344. self.mayReturnEmpty = True
  1345. self.mayIndexError = False
  1346. self.errmsg = "Unmatchable token"
  1347. #self.myException.msg = self.errmsg
  1348. def parseImpl( self, instring, loc, doActions=True ):
  1349. raise ParseException(instring, loc, self.errmsg, self)
  1350. class Literal(Token):
  1351. """Token to exactly match a specified string."""
  1352. def __init__( self, matchString ):
  1353. super(Literal,self).__init__()
  1354. self.match = matchString
  1355. self.matchLen = len(matchString)
  1356. try:
  1357. self.firstMatchChar = matchString[0]
  1358. except IndexError:
  1359. warnings.warn("null string passed to Literal; use Empty() instead",
  1360. SyntaxWarning, stacklevel=2)
  1361. self.__class__ = Empty
  1362. self.name = '"%s"' % _ustr(self.match)
  1363. self.errmsg = "Expected " + self.name
  1364. self.mayReturnEmpty = False
  1365. #self.myException.msg = self.errmsg
  1366. self.mayIndexError = False
  1367. # Performance tuning: this routine gets called a *lot*
  1368. # if this is a single character match string and the first character matches,
  1369. # short-circuit as quickly as possible, and avoid calling startswith
  1370. #~ @profile
  1371. def parseImpl( self, instring, loc, doActions=True ):
  1372. if (instring[loc] == self.firstMatchChar and
  1373. (self.matchLen==1 or instring.startswith(self.match,loc)) ):
  1374. return loc+self.matchLen, self.match
  1375. raise ParseException( instring, loc, self.errmsg, self )
  1376. _L = Literal
  1377. class Keyword(Token):
  1378. """Token to exactly match a specified string as a keyword, that is, it must be
  1379. immediately followed by a non-keyword character. Compare with C{Literal}::
  1380. Literal("if") will match the leading 'if' in 'ifAndOnlyIf'.
  1381. Keyword("if") will not; it will only match the leading 'if in 'if x=1', or 'if(y==2)'
  1382. Accepts two optional constructor arguments in addition to the keyword string:
  1383. C{identChars} is a string of characters that would be valid identifier characters,
  1384. defaulting to all alphanumerics + "_" and "$"; C{caseless} allows case-insensitive
  1385. matching, default is False.
  1386. """
  1387. DEFAULT_KEYWORD_CHARS = alphanums+"_$"
  1388. def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ):
  1389. super(Keyword,self).__init__()
  1390. self.match = matchString
  1391. self.matchLen = len(matchString)
  1392. try:
  1393. self.firstMatchChar = matchString[0]
  1394. except IndexError:
  1395. warnings.warn("null string passed to Keyword; use Empty() instead",
  1396. SyntaxWarning, stacklevel=2)
  1397. self.name = '"%s"' % self.match
  1398. self.errmsg = "Expected " + self.name
  1399. self.mayReturnEmpty = False
  1400. #self.myException.msg = self.errmsg
  1401. self.mayIndexError = False
  1402. self.caseless = caseless
  1403. if caseless:
  1404. self.caselessmatch = matchString.upper()
  1405. identChars = identChars.upper()
  1406. self.identChars = set(identChars)
  1407. def parseImpl( self, instring, loc, doActions=True ):
  1408. if self.caseless:
  1409. if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
  1410. (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and
  1411. (loc == 0 or instring[loc-1].upper() not in self.identChars) ):
  1412. return loc+self.matchLen, self.match
  1413. else:
  1414. if (instring[loc] == self.firstMatchChar and
  1415. (self.matchLen==1 or instring.startswith(self.match,loc)) and
  1416. (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and
  1417. (loc == 0 or instring[loc-1] not in self.identChars) ):
  1418. return loc+self.matchLen, self.match
  1419. raise ParseException( instring, loc, self.errmsg, self )
  1420. def copy(self):
  1421. c = super(Keyword,self).copy()
  1422. c.identChars = Keyword.DEFAULT_KEYWORD_CHARS
  1423. return c
  1424. def setDefaultKeywordChars( chars ):
  1425. """Overrides the default Keyword chars
  1426. """
  1427. Keyword.DEFAULT_KEYWORD_CHARS = chars
  1428. setDefaultKeywordChars = staticmethod(setDefaultKeywordChars)
  1429. class CaselessLiteral(Literal):
  1430. """Token to match a specified string, ignoring case of letters.
  1431. Note: the matched results will always be in the case of the given
  1432. match string, NOT the case of the input text.
  1433. """
  1434. def __init__( self, matchString ):
  1435. super(CaselessLiteral,self).__init__( matchString.upper() )
  1436. # Preserve the defining literal.
  1437. self.returnString = matchString
  1438. self.name = "'%s'" % self.returnString
  1439. self.errmsg = "Expected " + self.name
  1440. #self.myException.msg = self.errmsg
  1441. def parseImpl( self, instring, loc, doActions=True ):
  1442. if instring[ loc:loc+self.matchLen ].upper() == self.match:
  1443. return loc+self.matchLen, self.returnString
  1444. raise ParseException( instring, loc, self.errmsg, self )
  1445. class CaselessKeyword(Keyword):
  1446. def __init__( self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS ):
  1447. super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True )
  1448. def parseImpl( self, instring, loc, doActions=True ):
  1449. if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
  1450. (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ):
  1451. return loc+self.matchLen, self.match
  1452. raise ParseException( instring, loc, self.errmsg, self )
  1453. class Word(Token):
  1454. """Token for matching words composed of allowed character sets.
  1455. Defined with string containing all allowed initial characters,
  1456. an optional string containing allowed body characters (if omitted,
  1457. defaults to the initial character set), and an optional minimum,
  1458. maximum, and/or exact length. The default value for C{min} is 1 (a
  1459. minimum value < 1 is not valid); the default values for C{max} and C{exact}
  1460. are 0, meaning no maximum or exact length restriction.
  1461. """
  1462. def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False ):
  1463. super(Word,self).__init__()
  1464. self.initCharsOrig = initChars
  1465. self.initChars = set(initChars)
  1466. if bodyChars :
  1467. self.bodyCharsOrig = bodyChars
  1468. self.bodyChars = set(bodyChars)
  1469. else:
  1470. self.bodyCharsOrig = initChars
  1471. self.bodyChars = set(initChars)
  1472. self.maxSpecified = max > 0
  1473. if min < 1:
  1474. raise ValueError("cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted")
  1475. self.minLen = min
  1476. if max > 0:
  1477. self.maxLen = max
  1478. else:
  1479. self.maxLen = _MAX_INT
  1480. if exact > 0:
  1481. self.maxLen = exact
  1482. self.minLen = exact
  1483. self.name = _ustr(self)
  1484. self.errmsg = "Expected " + self.name
  1485. #self.myException.msg = self.errmsg
  1486. self.mayIndexError = False
  1487. self.asKeyword = asKeyword
  1488. if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0):
  1489. if self.bodyCharsOrig == self.initCharsOrig:
  1490. self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig)
  1491. elif len(self.bodyCharsOrig) == 1:
  1492. self.reString = "%s[%s]*" % \
  1493. (re.escape(self.initCharsOrig),
  1494. _escapeRegexRangeChars(self.bodyCharsOrig),)
  1495. else:
  1496. self.reString = "[%s][%s]*" % \
  1497. (_escapeRegexRangeChars(self.initCharsOrig),
  1498. _escapeRegexRangeChars(self.bodyCharsOrig),)
  1499. if self.asKeyword:
  1500. self.reString = r"\b"+self.reString+r"\b"
  1501. try:
  1502. self.re = re.compile( self.reString )
  1503. except:
  1504. self.re = None
  1505. def parseImpl( self, instring, loc, doActions=True ):
  1506. if self.re:
  1507. result = self.re.match(instring,loc)
  1508. if not result:
  1509. raise ParseException(instring, loc, self.errmsg, self)
  1510. loc = result.end()
  1511. return loc,result.group()
  1512. if not(instring[ loc ] in self.initChars):
  1513. raise ParseException( instring, loc, self.errmsg, self )
  1514. start = loc
  1515. loc += 1
  1516. instrlen = len(instring)
  1517. bodychars = self.bodyChars
  1518. maxloc = start + self.maxLen
  1519. maxloc = min( maxloc, instrlen )
  1520. while loc < maxloc and instring[loc] in bodychars:
  1521. loc += 1
  1522. throwException = False
  1523. if loc - start < self.minLen:
  1524. throwException = True
  1525. if self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
  1526. throwException = True
  1527. if self.asKeyword:
  1528. if (start>0 and instring[start-1] in bodychars) or (loc<instrlen and instring[loc] in bodychars):
  1529. throwException = True
  1530. if throwException:
  1531. raise ParseException( instring, loc, self.errmsg, self )
  1532. return loc, instring[start:loc]
  1533. def __str__( self ):
  1534. try:
  1535. return super(Word,self).__str__()
  1536. except:
  1537. pass
  1538. if self.strRepr is None:
  1539. def charsAsStr(s):
  1540. if len(s)>4:
  1541. return s[:4]+"..."
  1542. else:
  1543. return s
  1544. if ( self.initCharsOrig != self.bodyCharsOrig ):
  1545. self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) )
  1546. else:
  1547. self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig)
  1548. return self.strRepr
  1549. class Regex(Token):
  1550. """Token for matching strings that match a given regular expression.
  1551. Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module.
  1552. """
  1553. compiledREtype = type(re.compile("[A-Z]"))
  1554. def __init__( self, pattern, flags=0):
  1555. """The parameters pattern and flags are passed to the re.compile() function as-is. See the Python re module for an explanation of the acceptable patterns and flags."""
  1556. super(Regex,self).__init__()
  1557. if isinstance(pattern, basestring):
  1558. if len(pattern) == 0:
  1559. warnings.warn("null string passed to Regex; use Empty() instead",
  1560. SyntaxWarning, stacklevel=2)
  1561. self.pattern = pattern
  1562. self.flags = flags
  1563. try:
  1564. self.re = re.compile(self.pattern, self.flags)
  1565. self.reString = self.pattern
  1566. except sre_constants.error:
  1567. warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
  1568. SyntaxWarning, stacklevel=2)
  1569. raise
  1570. elif isinstance(pattern, Regex.compiledREtype):
  1571. self.re = pattern
  1572. self.pattern = \
  1573. self.reString = str(pattern)
  1574. self.flags = flags
  1575. else:
  1576. raise ValueError("Regex may only be constructed with a string or a compiled RE object")
  1577. self.name = _ustr(self)
  1578. self.errmsg = "Expected " + self.name
  1579. #self.myException.msg = self.errmsg
  1580. self.mayIndexError = False
  1581. self.mayReturnEmpty = True
  1582. def parseImpl( self, instring, loc, doActions=True ):
  1583. result = self.re.match(instring,loc)
  1584. if not result:
  1585. raise ParseException(instring, loc, self.errmsg, self)
  1586. loc = result.end()
  1587. d = result.groupdict()
  1588. ret = ParseResults(result.group())
  1589. if d:
  1590. for k in d:
  1591. ret[k] = d[k]
  1592. return loc,ret
  1593. def __str__( self ):
  1594. try:
  1595. return super(Regex,self).__str__()
  1596. except:
  1597. pass
  1598. if self.strRepr is None:
  1599. self.strRepr = "Re:(%s)" % repr(self.pattern)
  1600. return self.strRepr
  1601. class QuotedString(Token):
  1602. """Token for matching strings that are delimited by quoting characters.
  1603. """
  1604. def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None):
  1605. """
  1606. Defined with the following parameters:
  1607. - quoteChar - string of one or more characters defining the quote delimiting string
  1608. - escChar - character to escape quotes, typically backslash (default=None)
  1609. - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=None)
  1610. - multiline - boolean indicating whether quotes can span multiple lines (default=False)
  1611. - unquoteResults - boolean indicating whether the matched text should be unquoted (default=True)
  1612. - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=None => same as quoteChar)
  1613. """
  1614. super(QuotedString,self).__init__()
  1615. # remove white space from quote chars - wont work anyway
  1616. quoteChar = quoteChar.strip()
  1617. if len(quoteChar) == 0:
  1618. warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
  1619. raise SyntaxError()
  1620. if endQuoteChar is None:
  1621. endQuoteChar = quoteChar
  1622. else:
  1623. endQuoteChar = endQuoteChar.strip()
  1624. if len(endQuoteChar) == 0:
  1625. warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
  1626. raise SyntaxError()
  1627. self.quoteChar = quoteChar
  1628. self.quoteCharLen = len(quoteChar)
  1629. self.firstQuoteChar = quoteChar[0]
  1630. self.endQuoteChar = endQuoteChar
  1631. self.endQuoteCharLen = len(endQuoteChar)
  1632. self.escChar = escChar
  1633. self.escQuote = escQuote
  1634. self.unquoteResults = unquoteResults
  1635. if multiline:
  1636. self.flags = re.MULTILINE | re.DOTALL
  1637. self.pattern = r'%s(?:[^%s%s]' % \
  1638. ( re.escape(self.quoteChar),
  1639. _escapeRegexRangeChars(self.endQuoteChar[0]),
  1640. (escChar is not None and _escapeRegexRangeChars(escChar) or '') )
  1641. else:
  1642. self.flags = 0
  1643. self.pattern = r'%s(?:[^%s\n\r%s]' % \
  1644. ( re.escape(self.quoteChar),
  1645. _escapeRegexRangeChars(self.endQuoteChar[0]),
  1646. (escChar is not None and _escapeRegexRangeChars(escChar) or '') )
  1647. if len(self.endQuoteChar) > 1:
  1648. self.pattern += (
  1649. '|(?:' + ')|(?:'.join(["%s[^%s]" % (re.escape(self.endQuoteChar[:i]),
  1650. _escapeRegexRangeChars(self.endQuoteChar[i]))
  1651. for i in range(len(self.endQuoteChar)-1,0,-1)]) + ')'
  1652. )
  1653. if escQuote:
  1654. self.pattern += (r'|(?:%s)' % re.escape(escQuote))
  1655. if escChar:
  1656. self.pattern += (r'|(?:%s.)' % re.escape(escChar))
  1657. self.escCharReplacePattern = re.escape(self.escChar)+"(.)"
  1658. self.pattern += (r')*%s' % re.escape(self.endQuoteChar))
  1659. try:
  1660. self.re = re.compile(self.pattern, self.flags)
  1661. self.reString = self.pattern
  1662. except sre_constants.error:
  1663. warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern,
  1664. SyntaxWarning, stacklevel=2)
  1665. raise
  1666. self.name = _ustr(self)
  1667. self.errmsg = "Expected " + self.name
  1668. #self.myException.msg = self.errmsg
  1669. self.mayIndexError = False
  1670. self.mayReturnEmpty = True
  1671. def parseImpl( self, instring, loc, doActions=True ):
  1672. result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None
  1673. if not result:
  1674. raise ParseException(instring, loc, self.errmsg, self)
  1675. loc = result.end()
  1676. ret = result.group()
  1677. if self.unquoteResults:
  1678. # strip off quotes
  1679. ret = ret[self.quoteCharLen:-self.endQuoteCharLen]
  1680. if isinstance(ret,basestring):
  1681. # replace escaped characters
  1682. if self.escChar:
  1683. ret = re.sub(self.escCharReplacePattern,"\g<1>",ret)
  1684. # replace escaped quotes
  1685. if self.escQuote:
  1686. ret = ret.replace(self.escQuote, self.endQuoteChar)
  1687. return loc, ret
  1688. def __str__( self ):
  1689. try:
  1690. return super(QuotedString,self).__str__()
  1691. except:
  1692. pass
  1693. if self.strRepr is None:
  1694. self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar)
  1695. return self.strRepr
  1696. class CharsNotIn(Token):
  1697. """Token for matching words composed of characters *not* in a given set.
  1698. Defined with string containing all disallowed characters, and an optional
  1699. minimum, maximum, and/or exact length. The default value for C{min} is 1 (a
  1700. minimum value < 1 is not valid); the default values for C{max} and C{exact}
  1701. are 0, meaning no maximum or exact length restriction.
  1702. """
  1703. def __init__( self, notChars, min=1, max=0, exact=0 ):
  1704. super(CharsNotIn,self).__init__()
  1705. self.skipWhitespace = False
  1706. self.notChars = notChars
  1707. if min < 1:
  1708. raise ValueError("cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted")
  1709. self.minLen = min
  1710. if max > 0:
  1711. self.maxLen = max
  1712. else:
  1713. self.maxLen = _MAX_INT
  1714. if exact > 0:
  1715. self.maxLen = exact
  1716. self.minLen = exact
  1717. self.name = _ustr(self)
  1718. self.errmsg = "Expected " + self.name
  1719. self.mayReturnEmpty = ( self.minLen == 0 )
  1720. #self.myException.msg = self.errmsg
  1721. self.mayIndexError = False
  1722. def parseImpl( self, instring, loc, doActions=True ):
  1723. if instring[loc] in self.notChars:
  1724. raise ParseException( instring, loc, self.errmsg, self )
  1725. start = loc
  1726. loc += 1
  1727. notchars = self.notChars
  1728. maxlen = min( start+self.maxLen, len(instring) )
  1729. while loc < maxlen and \
  1730. (instring[loc] not in notchars):
  1731. loc += 1
  1732. if loc - start < self.minLen:
  1733. raise ParseException( instring, loc, self.errmsg, self )
  1734. return loc, instring[start:loc]
  1735. def __str__( self ):
  1736. try:
  1737. return super(CharsNotIn, self).__str__()
  1738. except:
  1739. pass
  1740. if self.strRepr is None:
  1741. if len(self.notChars) > 4:
  1742. self.strRepr = "!W:(%s...)" % self.notChars[:4]
  1743. else:
  1744. self.strRepr = "!W:(%s)" % self.notChars
  1745. return self.strRepr
  1746. class White(Token):
  1747. """Special matching class for matching whitespace. Normally, whitespace is ignored
  1748. by pyparsing grammars. This class is included when some whitespace structures
  1749. are significant. Define with a string containing the whitespace characters to be
  1750. matched; default is C{" \\t\\r\\n"}. Also takes optional C{min}, C{max}, and C{exact} arguments,
  1751. as defined for the C{Word} class."""
  1752. whiteStrs = {
  1753. " " : "<SPC>",
  1754. "\t": "<TAB>",
  1755. "\n": "<LF>",
  1756. "\r": "<CR>",
  1757. "\f": "<FF>",
  1758. }
  1759. def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0):
  1760. super(White,self).__init__()
  1761. self.matchWhite = ws
  1762. self.setWhitespaceChars( "".join([c for c in self.whiteChars if c not in self.matchWhite]) )
  1763. #~ self.leaveWhitespace()
  1764. self.name = ("".join([White.whiteStrs[c] for c in self.matchWhite]))
  1765. self.mayReturnEmpty = True
  1766. self.errmsg = "Expected " + self.name
  1767. #self.myException.msg = self.errmsg
  1768. self.minLen = min
  1769. if max > 0:
  1770. self.maxLen = max
  1771. else:
  1772. self.maxLen = _MAX_INT
  1773. if exact > 0:
  1774. self.maxLen = exact
  1775. self.minLen = exact
  1776. def parseImpl( self, instring, loc, doActions=True ):
  1777. if not(instring[ loc ] in self.matchWhite):
  1778. raise ParseException( instring, loc, self.errmsg, self )
  1779. start = loc
  1780. loc += 1
  1781. maxloc = start + self.maxLen
  1782. maxloc = min( maxloc, len(instring) )
  1783. while loc < maxloc and instring[loc] in self.matchWhite:
  1784. loc += 1
  1785. if loc - start < self.minLen:
  1786. raise ParseException( instring, loc, self.errmsg, self )
  1787. return loc, instring[start:loc]
  1788. class _PositionToken(Token):
  1789. def __init__( self ):
  1790. super(_PositionToken,self).__init__()
  1791. self.name=self.__class__.__name__
  1792. self.mayReturnEmpty = True
  1793. self.mayIndexError = False
  1794. class GoToColumn(_PositionToken):
  1795. """Token to advance to a specific column of input text; useful for tabular report scraping."""
  1796. def __init__( self, colno ):
  1797. super(GoToColumn,self).__init__()
  1798. self.col = colno
  1799. def preParse( self, instring, loc ):
  1800. if col(loc,instring) != self.col:
  1801. instrlen = len(instring)
  1802. if self.ignoreExprs:
  1803. loc = self._skipIgnorables( instring, loc )
  1804. while loc < instrlen and instring[loc].isspace() and col( loc, instring ) != self.col :
  1805. loc += 1
  1806. return loc
  1807. def parseImpl( self, instring, loc, doActions=True ):
  1808. thiscol = col( loc, instring )
  1809. if thiscol > self.col:
  1810. raise ParseException( instring, loc, "Text not in expected column", self )
  1811. newloc = loc + self.col - thiscol
  1812. ret = instring[ loc: newloc ]
  1813. return newloc, ret
  1814. class LineStart(_PositionToken):
  1815. """Matches if current position is at the beginning of a line within the parse string"""
  1816. def __init__( self ):
  1817. super(LineStart,self).__init__()
  1818. self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") )
  1819. self.errmsg = "Expected start of line"
  1820. #self.myException.msg = self.errmsg
  1821. def preParse( self, instring, loc ):
  1822. preloc = super(LineStart,self).preParse(instring,loc)
  1823. if instring[preloc] == "\n":
  1824. loc += 1
  1825. return loc
  1826. def parseImpl( self, instring, loc, doActions=True ):
  1827. if not( loc==0 or
  1828. (loc == self.preParse( instring, 0 )) or
  1829. (instring[loc-1] == "\n") ): #col(loc, instring) != 1:
  1830. raise ParseException( instring, loc, self.errmsg, self )
  1831. return loc, []
  1832. class LineEnd(_PositionToken):
  1833. """Matches if current position is at the end of a line within the parse string"""
  1834. def __init__( self ):
  1835. super(LineEnd,self).__init__()
  1836. self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") )
  1837. self.errmsg = "Expected end of line"
  1838. #self.myException.msg = self.errmsg
  1839. def parseImpl( self, instring, loc, doActions=True ):
  1840. if loc<len(instring):
  1841. if instring[loc] == "\n":
  1842. return loc+1, "\n"
  1843. else:
  1844. raise ParseException( instring, loc, self.errmsg, self )
  1845. elif loc == len(instring):
  1846. return loc+1, []
  1847. else:
  1848. raise ParseException( instring, loc, self.errmsg, self )
  1849. class StringStart(_PositionToken):
  1850. """Matches if current position is at the beginning of the parse string"""
  1851. def __init__( self ):
  1852. super(StringStart,self).__init__()
  1853. self.errmsg = "Expected start of text"
  1854. #self.myException.msg = self.errmsg
  1855. def parseImpl( self, instring, loc, doActions=True ):
  1856. if loc != 0:
  1857. # see if entire string up to here is just whitespace and ignoreables
  1858. if loc != self.preParse( instring, 0 ):
  1859. raise ParseException( instring, loc, self.errmsg, self )
  1860. return loc, []
  1861. class StringEnd(_PositionToken):
  1862. """Matches if current position is at the end of the parse string"""
  1863. def __init__( self ):
  1864. super(StringEnd,self).__init__()
  1865. self.errmsg = "Expected end of text"
  1866. #self.myException.msg = self.errmsg
  1867. def parseImpl( self, instring, loc, doActions=True ):
  1868. if loc < len(instring):
  1869. raise ParseException( instring, loc, self.errmsg, self )
  1870. elif loc == len(instring):
  1871. return loc+1, []
  1872. elif loc > len(instring):
  1873. return loc, []
  1874. else:
  1875. raise ParseException( instring, loc, self.errmsg, self )
  1876. class WordStart(_PositionToken):
  1877. """Matches if the current position is at the beginning of a Word, and
  1878. is not preceded by any character in a given set of wordChars
  1879. (default=C{printables}). To emulate the C{\b} behavior of regular expressions,
  1880. use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of
  1881. the string being parsed, or at the beginning of a line.
  1882. """
  1883. def __init__(self, wordChars = printables):
  1884. super(WordStart,self).__init__()
  1885. self.wordChars = set(wordChars)
  1886. self.errmsg = "Not at the start of a word"
  1887. def parseImpl(self, instring, loc, doActions=True ):
  1888. if loc != 0:
  1889. if (instring[loc-1] in self.wordChars or
  1890. instring[loc] not in self.wordChars):
  1891. raise ParseException( instring, loc, self.errmsg, self )
  1892. return loc, []
  1893. class WordEnd(_PositionToken):
  1894. """Matches if the current position is at the end of a Word, and
  1895. is not followed by any character in a given set of wordChars
  1896. (default=C{printables}). To emulate the C{\b} behavior of regular expressions,
  1897. use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of
  1898. the string being parsed, or at the end of a line.
  1899. """
  1900. def __init__(self, wordChars = printables):
  1901. super(WordEnd,self).__init__()
  1902. self.wordChars = set(wordChars)
  1903. self.skipWhitespace = False
  1904. self.errmsg = "Not at the end of a word"
  1905. def parseImpl(self, instring, loc, doActions=True ):
  1906. instrlen = len(instring)
  1907. if instrlen>0 and loc<instrlen:
  1908. if (instring[loc] in self.wordChars or
  1909. instring[loc-1] not in self.wordChars):
  1910. raise ParseException( instring, loc, self.errmsg, self )
  1911. return loc, []
  1912. class ParseExpression(ParserElement):
  1913. """Abstract subclass of ParserElement, for combining and post-processing parsed tokens."""
  1914. def __init__( self, exprs, savelist = False ):
  1915. super(ParseExpression,self).__init__(savelist)
  1916. if isinstance( exprs, list ):
  1917. self.exprs = exprs
  1918. elif isinstance( exprs, basestring ):
  1919. self.exprs = [ Literal( exprs ) ]
  1920. else:
  1921. try:
  1922. self.exprs = list( exprs )
  1923. except TypeError:
  1924. self.exprs = [ exprs ]
  1925. self.callPreparse = False
  1926. def __getitem__( self, i ):
  1927. return self.exprs[i]
  1928. def append( self, other ):
  1929. self.exprs.append( other )
  1930. self.strRepr = None
  1931. return self
  1932. def leaveWhitespace( self ):
  1933. """Extends leaveWhitespace defined in base class, and also invokes leaveWhitespace on
  1934. all contained expressions."""
  1935. self.skipWhitespace = False
  1936. self.exprs = [ e.copy() for e in self.exprs ]
  1937. for e in self.exprs:
  1938. e.leaveWhitespace()
  1939. return self
  1940. def ignore( self, other ):
  1941. if isinstance( other, Suppress ):
  1942. if other not in self.ignoreExprs:
  1943. super( ParseExpression, self).ignore( other )
  1944. for e in self.exprs:
  1945. e.ignore( self.ignoreExprs[-1] )
  1946. else:
  1947. super( ParseExpression, self).ignore( other )
  1948. for e in self.exprs:
  1949. e.ignore( self.ignoreExprs[-1] )
  1950. return self
  1951. def __str__( self ):
  1952. try:
  1953. return super(ParseExpression,self).__str__()
  1954. except:
  1955. pass
  1956. if self.strRepr is None:
  1957. self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.exprs) )
  1958. return self.strRepr
  1959. def streamline( self ):
  1960. super(ParseExpression,self).streamline()
  1961. for e in self.exprs:
  1962. e.streamline()
  1963. # collapse nested And's of the form And( And( And( a,b), c), d) to And( a,b,c,d )
  1964. # but only if there are no parse actions or resultsNames on the nested And's
  1965. # (likewise for Or's and MatchFirst's)
  1966. if ( len(self.exprs) == 2 ):
  1967. other = self.exprs[0]
  1968. if ( isinstance( other, self.__class__ ) and
  1969. not(other.parseAction) and
  1970. other.resultsName is None and
  1971. not other.debug ):
  1972. self.exprs = other.exprs[:] + [ self.exprs[1] ]
  1973. self.strRepr = None
  1974. self.mayReturnEmpty |= other.mayReturnEmpty
  1975. self.mayIndexError |= other.mayIndexError
  1976. other = self.exprs[-1]
  1977. if ( isinstance( other, self.__class__ ) and
  1978. not(other.parseAction) and
  1979. other.resultsName is None and
  1980. not other.debug ):
  1981. self.exprs = self.exprs[:-1] + other.exprs[:]
  1982. self.strRepr = None
  1983. self.mayReturnEmpty |= other.mayReturnEmpty
  1984. self.mayIndexError |= other.mayIndexError
  1985. return self
  1986. def setResultsName( self, name, listAllMatches=False ):
  1987. ret = super(ParseExpression,self).setResultsName(name,listAllMatches)
  1988. return ret
  1989. def validate( self, validateTrace=[] ):
  1990. tmp = validateTrace[:]+[self]
  1991. for e in self.exprs:
  1992. e.validate(tmp)
  1993. self.checkRecursion( [] )
  1994. class And(ParseExpression):
  1995. """Requires all given C{ParseExpressions} to be found in the given order.
  1996. Expressions may be separated by whitespace.
  1997. May be constructed using the '+' operator.
  1998. """
  1999. class _ErrorStop(Empty):
  2000. def __init__(self, *args, **kwargs):
  2001. super(Empty,self).__init__(*args, **kwargs)
  2002. self.leaveWhitespace()
  2003. def __init__( self, exprs, savelist = True ):
  2004. super(And,self).__init__(exprs, savelist)
  2005. self.mayReturnEmpty = True
  2006. for e in self.exprs:
  2007. if not e.mayReturnEmpty:
  2008. self.mayReturnEmpty = False
  2009. break
  2010. self.setWhitespaceChars( exprs[0].whiteChars )
  2011. self.skipWhitespace = exprs[0].skipWhitespace
  2012. self.callPreparse = True
  2013. def parseImpl( self, instring, loc, doActions=True ):
  2014. # pass False as last arg to _parse for first element, since we already
  2015. # pre-parsed the string as part of our And pre-parsing
  2016. loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
  2017. errorStop = False
  2018. for e in self.exprs[1:]:
  2019. if isinstance(e, And._ErrorStop):
  2020. errorStop = True
  2021. continue
  2022. if errorStop:
  2023. try:
  2024. loc, exprtokens = e._parse( instring, loc, doActions )
  2025. except ParseSyntaxException:
  2026. raise
  2027. except ParseBaseException as e:
  2028. e.__traceback__ = None
  2029. raise ParseSyntaxException(e)
  2030. except IndexError:
  2031. raise ParseSyntaxException( ParseException(instring, len(instring), self.errmsg, self) )
  2032. else:
  2033. loc, exprtokens = e._parse( instring, loc, doActions )
  2034. if exprtokens or exprtokens.keys():
  2035. resultlist += exprtokens
  2036. return loc, resultlist
  2037. def __iadd__(self, other ):
  2038. if isinstance( other, basestring ):
  2039. other = Literal( other )
  2040. return self.append( other ) #And( [ self, other ] )
  2041. def checkRecursion( self, parseElementList ):
  2042. subRecCheckList = parseElementList[:] + [ self ]
  2043. for e in self.exprs:
  2044. e.checkRecursion( subRecCheckList )
  2045. if not e.mayReturnEmpty:
  2046. break
  2047. def __str__( self ):
  2048. if hasattr(self,"name"):
  2049. return self.name
  2050. if self.strRepr is None:
  2051. self.strRepr = "{" + " ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
  2052. return self.strRepr
  2053. class Or(ParseExpression):
  2054. """Requires that at least one C{ParseExpression} is found.
  2055. If two expressions match, the expression that matches the longest string will be used.
  2056. May be constructed using the '^' operator.
  2057. """
  2058. def __init__( self, exprs, savelist = False ):
  2059. super(Or,self).__init__(exprs, savelist)
  2060. self.mayReturnEmpty = False
  2061. for e in self.exprs:
  2062. if e.mayReturnEmpty:
  2063. self.mayReturnEmpty = True
  2064. break
  2065. def parseImpl( self, instring, loc, doActions=True ):
  2066. maxExcLoc = -1
  2067. maxMatchLoc = -1
  2068. maxException = None
  2069. for e in self.exprs:
  2070. try:
  2071. loc2 = e.tryParse( instring, loc )
  2072. except ParseException as err:
  2073. err.__traceback__ = None
  2074. if err.loc > maxExcLoc:
  2075. maxException = err
  2076. maxExcLoc = err.loc
  2077. except IndexError:
  2078. if len(instring) > maxExcLoc:
  2079. maxException = ParseException(instring,len(instring),e.errmsg,self)
  2080. maxExcLoc = len(instring)
  2081. else:
  2082. if loc2 > maxMatchLoc:
  2083. maxMatchLoc = loc2
  2084. maxMatchExp = e
  2085. if maxMatchLoc < 0:
  2086. if maxException is not None:
  2087. maxException.__traceback__ = None
  2088. raise maxException
  2089. else:
  2090. raise ParseException(instring, loc, "no defined alternatives to match", self)
  2091. return maxMatchExp._parse( instring, loc, doActions )
  2092. def __ixor__(self, other ):
  2093. if isinstance( other, basestring ):
  2094. other = Literal( other )
  2095. return self.append( other ) #Or( [ self, other ] )
  2096. def __str__( self ):
  2097. if hasattr(self,"name"):
  2098. return self.name
  2099. if self.strRepr is None:
  2100. self.strRepr = "{" + " ^ ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
  2101. return self.strRepr
  2102. def checkRecursion( self, parseElementList ):
  2103. subRecCheckList = parseElementList[:] + [ self ]
  2104. for e in self.exprs:
  2105. e.checkRecursion( subRecCheckList )
  2106. class MatchFirst(ParseExpression):
  2107. """Requires that at least one C{ParseExpression} is found.
  2108. If two expressions match, the first one listed is the one that will match.
  2109. May be constructed using the '|' operator.
  2110. """
  2111. def __init__( self, exprs, savelist = False ):
  2112. super(MatchFirst,self).__init__(exprs, savelist)
  2113. if exprs:
  2114. self.mayReturnEmpty = False
  2115. for e in self.exprs:
  2116. if e.mayReturnEmpty:
  2117. self.mayReturnEmpty = True
  2118. break
  2119. else:
  2120. self.mayReturnEmpty = True
  2121. def parseImpl( self, instring, loc, doActions=True ):
  2122. maxExcLoc = -1
  2123. maxException = None
  2124. for e in self.exprs:
  2125. try:
  2126. ret = e._parse( instring, loc, doActions )
  2127. return ret
  2128. except ParseException as err:
  2129. err.__traceback__ = None
  2130. if err.loc > maxExcLoc:
  2131. maxException = err
  2132. maxExcLoc = err.loc
  2133. except IndexError:
  2134. if len(instring) > maxExcLoc:
  2135. maxException = ParseException(instring,len(instring),e.errmsg,self)
  2136. maxExcLoc = len(instring)
  2137. # only got here if no expression matched, raise exception for match that made it the furthest
  2138. else:
  2139. if maxException is not None:
  2140. maxException.__traceback__ = None
  2141. raise maxException
  2142. else:
  2143. raise ParseException(instring, loc, "no defined alternatives to match", self)
  2144. def __ior__(self, other ):
  2145. if isinstance( other, basestring ):
  2146. other = Literal( other )
  2147. return self.append( other ) #MatchFirst( [ self, other ] )
  2148. def __str__( self ):
  2149. if hasattr(self,"name"):
  2150. return self.name
  2151. if self.strRepr is None:
  2152. self.strRepr = "{" + " | ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
  2153. return self.strRepr
  2154. def checkRecursion( self, parseElementList ):
  2155. subRecCheckList = parseElementList[:] + [ self ]
  2156. for e in self.exprs:
  2157. e.checkRecursion( subRecCheckList )
  2158. class Each(ParseExpression):
  2159. """Requires all given C{ParseExpressions} to be found, but in any order.
  2160. Expressions may be separated by whitespace.
  2161. May be constructed using the '&' operator.
  2162. """
  2163. def __init__( self, exprs, savelist = True ):
  2164. super(Each,self).__init__(exprs, savelist)
  2165. self.mayReturnEmpty = True
  2166. for e in self.exprs:
  2167. if not e.mayReturnEmpty:
  2168. self.mayReturnEmpty = False
  2169. break
  2170. self.skipWhitespace = True
  2171. self.initExprGroups = True
  2172. def parseImpl( self, instring, loc, doActions=True ):
  2173. if self.initExprGroups:
  2174. opt1 = [ e.expr for e in self.exprs if isinstance(e,Optional) ]
  2175. opt2 = [ e for e in self.exprs if e.mayReturnEmpty and e not in opt1 ]
  2176. self.optionals = opt1 + opt2
  2177. self.multioptionals = [ e.expr for e in self.exprs if isinstance(e,ZeroOrMore) ]
  2178. self.multirequired = [ e.expr for e in self.exprs if isinstance(e,OneOrMore) ]
  2179. self.required = [ e for e in self.exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ]
  2180. self.required += self.multirequired
  2181. self.initExprGroups = False
  2182. tmpLoc = loc
  2183. tmpReqd = self.required[:]
  2184. tmpOpt = self.optionals[:]
  2185. matchOrder = []
  2186. keepMatching = True
  2187. while keepMatching:
  2188. tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired
  2189. failed = []
  2190. for e in tmpExprs:
  2191. try:
  2192. tmpLoc = e.tryParse( instring, tmpLoc )
  2193. except ParseException:
  2194. failed.append(e)
  2195. else:
  2196. matchOrder.append(e)
  2197. if e in tmpReqd:
  2198. tmpReqd.remove(e)
  2199. elif e in tmpOpt:
  2200. tmpOpt.remove(e)
  2201. if len(failed) == len(tmpExprs):
  2202. keepMatching = False
  2203. if tmpReqd:
  2204. missing = ", ".join( [ _ustr(e) for e in tmpReqd ] )
  2205. raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing )
  2206. # add any unmatched Optionals, in case they have default values defined
  2207. matchOrder += list(e for e in self.exprs if isinstance(e,Optional) and e.expr in tmpOpt)
  2208. resultlist = []
  2209. for e in matchOrder:
  2210. loc,results = e._parse(instring,loc,doActions)
  2211. resultlist.append(results)
  2212. finalResults = ParseResults([])
  2213. for r in resultlist:
  2214. dups = {}
  2215. for k in r.keys():
  2216. if k in finalResults.keys():
  2217. tmp = ParseResults(finalResults[k])
  2218. tmp += ParseResults(r[k])
  2219. dups[k] = tmp
  2220. finalResults += ParseResults(r)
  2221. for k,v in dups.items():
  2222. finalResults[k] = v
  2223. return loc, finalResults
  2224. def __str__( self ):
  2225. if hasattr(self,"name"):
  2226. return self.name
  2227. if self.strRepr is None:
  2228. self.strRepr = "{" + " & ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
  2229. return self.strRepr
  2230. def checkRecursion( self, parseElementList ):
  2231. subRecCheckList = parseElementList[:] + [ self ]
  2232. for e in self.exprs:
  2233. e.checkRecursion( subRecCheckList )
  2234. class ParseElementEnhance(ParserElement):
  2235. """Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens."""
  2236. def __init__( self, expr, savelist=False ):
  2237. super(ParseElementEnhance,self).__init__(savelist)
  2238. if isinstance( expr, basestring ):
  2239. expr = Literal(expr)
  2240. self.expr = expr
  2241. self.strRepr = None
  2242. if expr is not None:
  2243. self.mayIndexError = expr.mayIndexError
  2244. self.mayReturnEmpty = expr.mayReturnEmpty
  2245. self.setWhitespaceChars( expr.whiteChars )
  2246. self.skipWhitespace = expr.skipWhitespace
  2247. self.saveAsList = expr.saveAsList
  2248. self.callPreparse = expr.callPreparse
  2249. self.ignoreExprs.extend(expr.ignoreExprs)
  2250. def parseImpl( self, instring, loc, doActions=True ):
  2251. if self.expr is not None:
  2252. return self.expr._parse( instring, loc, doActions, callPreParse=False )
  2253. else:
  2254. raise ParseException("",loc,self.errmsg,self)
  2255. def leaveWhitespace( self ):
  2256. self.skipWhitespace = False
  2257. self.expr = self.expr.copy()
  2258. if self.expr is not None:
  2259. self.expr.leaveWhitespace()
  2260. return self
  2261. def ignore( self, other ):
  2262. if isinstance( other, Suppress ):
  2263. if other not in self.ignoreExprs:
  2264. super( ParseElementEnhance, self).ignore( other )
  2265. if self.expr is not None:
  2266. self.expr.ignore( self.ignoreExprs[-1] )
  2267. else:
  2268. super( ParseElementEnhance, self).ignore( other )
  2269. if self.expr is not None:
  2270. self.expr.ignore( self.ignoreExprs[-1] )
  2271. return self
  2272. def streamline( self ):
  2273. super(ParseElementEnhance,self).streamline()
  2274. if self.expr is not None:
  2275. self.expr.streamline()
  2276. return self
  2277. def checkRecursion( self, parseElementList ):
  2278. if self in parseElementList:
  2279. raise RecursiveGrammarException( parseElementList+[self] )
  2280. subRecCheckList = parseElementList[:] + [ self ]
  2281. if self.expr is not None:
  2282. self.expr.checkRecursion( subRecCheckList )
  2283. def validate( self, validateTrace=[] ):
  2284. tmp = validateTrace[:]+[self]
  2285. if self.expr is not None:
  2286. self.expr.validate(tmp)
  2287. self.checkRecursion( [] )
  2288. def __str__( self ):
  2289. try:
  2290. return super(ParseElementEnhance,self).__str__()
  2291. except:
  2292. pass
  2293. if self.strRepr is None and self.expr is not None:
  2294. self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.expr) )
  2295. return self.strRepr
  2296. class FollowedBy(ParseElementEnhance):
  2297. """Lookahead matching of the given parse expression. C{FollowedBy}
  2298. does *not* advance the parsing position within the input string, it only
  2299. verifies that the specified parse expression matches at the current
  2300. position. C{FollowedBy} always returns a null token list."""
  2301. def __init__( self, expr ):
  2302. super(FollowedBy,self).__init__(expr)
  2303. self.mayReturnEmpty = True
  2304. def parseImpl( self, instring, loc, doActions=True ):
  2305. self.expr.tryParse( instring, loc )
  2306. return loc, []
  2307. class NotAny(ParseElementEnhance):
  2308. """Lookahead to disallow matching with the given parse expression. C{NotAny}
  2309. does *not* advance the parsing position within the input string, it only
  2310. verifies that the specified parse expression does *not* match at the current
  2311. position. Also, C{NotAny} does *not* skip over leading whitespace. C{NotAny}
  2312. always returns a null token list. May be constructed using the '~' operator."""
  2313. def __init__( self, expr ):
  2314. super(NotAny,self).__init__(expr)
  2315. #~ self.leaveWhitespace()
  2316. self.skipWhitespace = False # do NOT use self.leaveWhitespace(), don't want to propagate to exprs
  2317. self.mayReturnEmpty = True
  2318. self.errmsg = "Found unwanted token, "+_ustr(self.expr)
  2319. #self.myException = ParseException("",0,self.errmsg,self)
  2320. def parseImpl( self, instring, loc, doActions=True ):
  2321. try:
  2322. self.expr.tryParse( instring, loc )
  2323. except (ParseException,IndexError):
  2324. pass
  2325. else:
  2326. raise ParseException( instring, loc, self.errmsg, self )
  2327. return loc, []
  2328. def __str__( self ):
  2329. if hasattr(self,"name"):
  2330. return self.name
  2331. if self.strRepr is None:
  2332. self.strRepr = "~{" + _ustr(self.expr) + "}"
  2333. return self.strRepr
  2334. class ZeroOrMore(ParseElementEnhance):
  2335. """Optional repetition of zero or more of the given expression."""
  2336. def __init__( self, expr ):
  2337. super(ZeroOrMore,self).__init__(expr)
  2338. self.mayReturnEmpty = True
  2339. def parseImpl( self, instring, loc, doActions=True ):
  2340. tokens = []
  2341. try:
  2342. loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
  2343. hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
  2344. while 1:
  2345. if hasIgnoreExprs:
  2346. preloc = self._skipIgnorables( instring, loc )
  2347. else:
  2348. preloc = loc
  2349. loc, tmptokens = self.expr._parse( instring, preloc, doActions )
  2350. if tmptokens or tmptokens.keys():
  2351. tokens += tmptokens
  2352. except (ParseException,IndexError):
  2353. pass
  2354. return loc, tokens
  2355. def __str__( self ):
  2356. if hasattr(self,"name"):
  2357. return self.name
  2358. if self.strRepr is None:
  2359. self.strRepr = "[" + _ustr(self.expr) + "]..."
  2360. return self.strRepr
  2361. def setResultsName( self, name, listAllMatches=False ):
  2362. ret = super(ZeroOrMore,self).setResultsName(name,listAllMatches)
  2363. ret.saveAsList = True
  2364. return ret
  2365. class OneOrMore(ParseElementEnhance):
  2366. """Repetition of one or more of the given expression."""
  2367. def parseImpl( self, instring, loc, doActions=True ):
  2368. # must be at least one
  2369. loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
  2370. try:
  2371. hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
  2372. while 1:
  2373. if hasIgnoreExprs:
  2374. preloc = self._skipIgnorables( instring, loc )
  2375. else:
  2376. preloc = loc
  2377. loc, tmptokens = self.expr._parse( instring, preloc, doActions )
  2378. if tmptokens or tmptokens.keys():
  2379. tokens += tmptokens
  2380. except (ParseException,IndexError):
  2381. pass
  2382. return loc, tokens
  2383. def __str__( self ):
  2384. if hasattr(self,"name"):
  2385. return self.name
  2386. if self.strRepr is None:
  2387. self.strRepr = "{" + _ustr(self.expr) + "}..."
  2388. return self.strRepr
  2389. def setResultsName( self, name, listAllMatches=False ):
  2390. ret = super(OneOrMore,self).setResultsName(name,listAllMatches)
  2391. ret.saveAsList = True
  2392. return ret
  2393. class _NullToken(object):
  2394. def __bool__(self):
  2395. return False
  2396. __nonzero__ = __bool__
  2397. def __str__(self):
  2398. return ""
  2399. _optionalNotMatched = _NullToken()
  2400. class Optional(ParseElementEnhance):
  2401. """Optional matching of the given expression.
  2402. A default return string can also be specified, if the optional expression
  2403. is not found.
  2404. """
  2405. def __init__( self, exprs, default=_optionalNotMatched ):
  2406. super(Optional,self).__init__( exprs, savelist=False )
  2407. self.defaultValue = default
  2408. self.mayReturnEmpty = True
  2409. def parseImpl( self, instring, loc, doActions=True ):
  2410. try:
  2411. loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
  2412. except (ParseException,IndexError):
  2413. if self.defaultValue is not _optionalNotMatched:
  2414. if self.expr.resultsName:
  2415. tokens = ParseResults([ self.defaultValue ])
  2416. tokens[self.expr.resultsName] = self.defaultValue
  2417. else:
  2418. tokens = [ self.defaultValue ]
  2419. else:
  2420. tokens = []
  2421. return loc, tokens
  2422. def __str__( self ):
  2423. if hasattr(self,"name"):
  2424. return self.name
  2425. if self.strRepr is None:
  2426. self.strRepr = "[" + _ustr(self.expr) + "]"
  2427. return self.strRepr
  2428. class SkipTo(ParseElementEnhance):
  2429. """Token for skipping over all undefined text until the matched expression is found.
  2430. If C{include} is set to true, the matched expression is also parsed (the skipped text
  2431. and matched expression are returned as a 2-element list). The C{ignore}
  2432. argument is used to define grammars (typically quoted strings and comments) that
  2433. might contain false matches.
  2434. """
  2435. def __init__( self, other, include=False, ignore=None, failOn=None ):
  2436. super( SkipTo, self ).__init__( other )
  2437. self.ignoreExpr = ignore
  2438. self.mayReturnEmpty = True
  2439. self.mayIndexError = False
  2440. self.includeMatch = include
  2441. self.asList = False
  2442. if failOn is not None and isinstance(failOn, basestring):
  2443. self.failOn = Literal(failOn)
  2444. else:
  2445. self.failOn = failOn
  2446. self.errmsg = "No match found for "+_ustr(self.expr)
  2447. #self.myException = ParseException("",0,self.errmsg,self)
  2448. def parseImpl( self, instring, loc, doActions=True ):
  2449. startLoc = loc
  2450. instrlen = len(instring)
  2451. expr = self.expr
  2452. failParse = False
  2453. while loc <= instrlen:
  2454. try:
  2455. if self.failOn:
  2456. try:
  2457. self.failOn.tryParse(instring, loc)
  2458. except ParseBaseException:
  2459. pass
  2460. else:
  2461. failParse = True
  2462. raise ParseException(instring, loc, "Found expression " + str(self.failOn))
  2463. failParse = False
  2464. if self.ignoreExpr is not None:
  2465. while 1:
  2466. try:
  2467. loc = self.ignoreExpr.tryParse(instring,loc)
  2468. # print("found ignoreExpr, advance to", loc)
  2469. except ParseBaseException:
  2470. break
  2471. expr._parse( instring, loc, doActions=False, callPreParse=False )
  2472. skipText = instring[startLoc:loc]
  2473. if self.includeMatch:
  2474. loc,mat = expr._parse(instring,loc,doActions,callPreParse=False)
  2475. if mat:
  2476. skipRes = ParseResults( skipText )
  2477. skipRes += mat
  2478. return loc, [ skipRes ]
  2479. else:
  2480. return loc, [ skipText ]
  2481. else:
  2482. return loc, [ skipText ]
  2483. except (ParseException,IndexError):
  2484. if failParse:
  2485. raise
  2486. else:
  2487. loc += 1
  2488. raise ParseException( instring, loc, self.errmsg, self )
  2489. class Forward(ParseElementEnhance):
  2490. """Forward declaration of an expression to be defined later -
  2491. used for recursive grammars, such as algebraic infix notation.
  2492. When the expression is known, it is assigned to the C{Forward} variable using the '<<' operator.
  2493. Note: take care when assigning to C{Forward} not to overlook precedence of operators.
  2494. Specifically, '|' has a lower precedence than '<<', so that::
  2495. fwdExpr << a | b | c
  2496. will actually be evaluated as::
  2497. (fwdExpr << a) | b | c
  2498. thereby leaving b and c out as parseable alternatives. It is recommended that you
  2499. explicitly group the values inserted into the C{Forward}::
  2500. fwdExpr << (a | b | c)
  2501. """
  2502. def __init__( self, other=None ):
  2503. super(Forward,self).__init__( other, savelist=False )
  2504. def __lshift__( self, other ):
  2505. if isinstance( other, basestring ):
  2506. other = Literal(other)
  2507. self.expr = other
  2508. self.mayReturnEmpty = other.mayReturnEmpty
  2509. self.strRepr = None
  2510. self.mayIndexError = self.expr.mayIndexError
  2511. self.mayReturnEmpty = self.expr.mayReturnEmpty
  2512. self.setWhitespaceChars( self.expr.whiteChars )
  2513. self.skipWhitespace = self.expr.skipWhitespace
  2514. self.saveAsList = self.expr.saveAsList
  2515. self.ignoreExprs.extend(self.expr.ignoreExprs)
  2516. return None
  2517. def leaveWhitespace( self ):
  2518. self.skipWhitespace = False
  2519. return self
  2520. def streamline( self ):
  2521. if not self.streamlined:
  2522. self.streamlined = True
  2523. if self.expr is not None:
  2524. self.expr.streamline()
  2525. return self
  2526. def validate( self, validateTrace=[] ):
  2527. if self not in validateTrace:
  2528. tmp = validateTrace[:]+[self]
  2529. if self.expr is not None:
  2530. self.expr.validate(tmp)
  2531. self.checkRecursion([])
  2532. def __str__( self ):
  2533. if hasattr(self,"name"):
  2534. return self.name
  2535. self._revertClass = self.__class__
  2536. self.__class__ = _ForwardNoRecurse
  2537. try:
  2538. if self.expr is not None:
  2539. retString = _ustr(self.expr)
  2540. else:
  2541. retString = "None"
  2542. finally:
  2543. self.__class__ = self._revertClass
  2544. return self.__class__.__name__ + ": " + retString
  2545. def copy(self):
  2546. if self.expr is not None:
  2547. return super(Forward,self).copy()
  2548. else:
  2549. ret = Forward()
  2550. ret << self
  2551. return ret
  2552. class _ForwardNoRecurse(Forward):
  2553. def __str__( self ):
  2554. return "..."
  2555. class TokenConverter(ParseElementEnhance):
  2556. """Abstract subclass of ParseExpression, for converting parsed results."""
  2557. def __init__( self, expr, savelist=False ):
  2558. super(TokenConverter,self).__init__( expr )#, savelist )
  2559. self.saveAsList = False
  2560. class Upcase(TokenConverter):
  2561. """Converter to upper case all matching tokens."""
  2562. def __init__(self, *args):
  2563. super(Upcase,self).__init__(*args)
  2564. warnings.warn("Upcase class is deprecated, use upcaseTokens parse action instead",
  2565. DeprecationWarning,stacklevel=2)
  2566. def postParse( self, instring, loc, tokenlist ):
  2567. return list(map( string.upper, tokenlist ))
  2568. class Combine(TokenConverter):
  2569. """Converter to concatenate all matching tokens to a single string.
  2570. By default, the matching patterns must also be contiguous in the input string;
  2571. this can be disabled by specifying C{'adjacent=False'} in the constructor.
  2572. """
  2573. def __init__( self, expr, joinString="", adjacent=True ):
  2574. super(Combine,self).__init__( expr )
  2575. # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself
  2576. if adjacent:
  2577. self.leaveWhitespace()
  2578. self.adjacent = adjacent
  2579. self.skipWhitespace = True
  2580. self.joinString = joinString
  2581. self.callPreparse = True
  2582. def ignore( self, other ):
  2583. if self.adjacent:
  2584. ParserElement.ignore(self, other)
  2585. else:
  2586. super( Combine, self).ignore( other )
  2587. return self
  2588. def postParse( self, instring, loc, tokenlist ):
  2589. retToks = tokenlist.copy()
  2590. del retToks[:]
  2591. retToks += ParseResults([ "".join(tokenlist._asStringList(self.joinString)) ], modal=self.modalResults)
  2592. if self.resultsName and len(retToks.keys())>0:
  2593. return [ retToks ]
  2594. else:
  2595. return retToks
  2596. class Group(TokenConverter):
  2597. """Converter to return the matched tokens as a list - useful for returning tokens of ZeroOrMore and OneOrMore expressions."""
  2598. def __init__( self, expr ):
  2599. super(Group,self).__init__( expr )
  2600. self.saveAsList = True
  2601. def postParse( self, instring, loc, tokenlist ):
  2602. return [ tokenlist ]
  2603. class Dict(TokenConverter):
  2604. """Converter to return a repetitive expression as a list, but also as a dictionary.
  2605. Each element can also be referenced using the first token in the expression as its key.
  2606. Useful for tabular report scraping when the first column can be used as a item key.
  2607. """
  2608. def __init__( self, exprs ):
  2609. super(Dict,self).__init__( exprs )
  2610. self.saveAsList = True
  2611. def postParse( self, instring, loc, tokenlist ):
  2612. for i,tok in enumerate(tokenlist):
  2613. if len(tok) == 0:
  2614. continue
  2615. ikey = tok[0]
  2616. if isinstance(ikey,int):
  2617. ikey = _ustr(tok[0]).strip()
  2618. if len(tok)==1:
  2619. tokenlist[ikey] = _ParseResultsWithOffset("",i)
  2620. elif len(tok)==2 and not isinstance(tok[1],ParseResults):
  2621. tokenlist[ikey] = _ParseResultsWithOffset(tok[1],i)
  2622. else:
  2623. dictvalue = tok.copy() #ParseResults(i)
  2624. del dictvalue[0]
  2625. if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.keys()):
  2626. tokenlist[ikey] = _ParseResultsWithOffset(dictvalue,i)
  2627. else:
  2628. tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0],i)
  2629. if self.resultsName:
  2630. return [ tokenlist ]
  2631. else:
  2632. return tokenlist
  2633. class Suppress(TokenConverter):
  2634. """Converter for ignoring the results of a parsed expression."""
  2635. def postParse( self, instring, loc, tokenlist ):
  2636. return []
  2637. def suppress( self ):
  2638. return self
  2639. class OnlyOnce(object):
  2640. """Wrapper for parse actions, to ensure they are only called once."""
  2641. def __init__(self, methodCall):
  2642. self.callable = ParserElement._normalizeParseActionArgs(methodCall)
  2643. self.called = False
  2644. def __call__(self,s,l,t):
  2645. if not self.called:
  2646. results = self.callable(s,l,t)
  2647. self.called = True
  2648. return results
  2649. raise ParseException(s,l,"")
  2650. def reset(self):
  2651. self.called = False
  2652. def traceParseAction(f):
  2653. """Decorator for debugging parse actions."""
  2654. f = ParserElement._normalizeParseActionArgs(f)
  2655. def z(*paArgs):
  2656. thisFunc = f.func_name
  2657. s,l,t = paArgs[-3:]
  2658. if len(paArgs)>3:
  2659. thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
  2660. sys.stderr.write( ">>entering %s(line: '%s', %d, %s)\n" % (thisFunc,line(l,s),l,t) )
  2661. try:
  2662. ret = f(*paArgs)
  2663. except Exception as exc:
  2664. sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) )
  2665. raise exc
  2666. sys.stderr.write( "<<leaving %s (ret: %s)\n" % (thisFunc,ret) )
  2667. return ret
  2668. try:
  2669. z.__name__ = f.__name__
  2670. except AttributeError:
  2671. pass
  2672. return z
  2673. #
  2674. # global helpers
  2675. #
  2676. def delimitedList( expr, delim=",", combine=False ):
  2677. """Helper to define a delimited list of expressions - the delimiter defaults to ','.
  2678. By default, the list elements and delimiters can have intervening whitespace, and
  2679. comments, but this can be overridden by passing C{combine=True} in the constructor.
  2680. If C{combine} is set to True, the matching tokens are returned as a single token
  2681. string, with the delimiters included; otherwise, the matching tokens are returned
  2682. as a list of tokens, with the delimiters suppressed.
  2683. """
  2684. dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..."
  2685. if combine:
  2686. return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName)
  2687. else:
  2688. return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)
  2689. def countedArray( expr ):
  2690. """Helper to define a counted list of expressions.
  2691. This helper defines a pattern of the form::
  2692. integer expr expr expr...
  2693. where the leading integer tells how many expr expressions follow.
  2694. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.
  2695. """
  2696. arrayExpr = Forward()
  2697. def countFieldParseAction(s,l,t):
  2698. n = int(t[0])
  2699. arrayExpr << (n and Group(And([expr]*n)) or Group(empty))
  2700. return []
  2701. return ( Word(nums).setName("arrayLen").setParseAction(countFieldParseAction, callDuringTry=True) + arrayExpr )
  2702. def _flatten(L):
  2703. if type(L) is not list: return [L]
  2704. if L == []: return L
  2705. return _flatten(L[0]) + _flatten(L[1:])
  2706. def matchPreviousLiteral(expr):
  2707. """Helper to define an expression that is indirectly defined from
  2708. the tokens matched in a previous expression, that is, it looks
  2709. for a 'repeat' of a previous expression. For example::
  2710. first = Word(nums)
  2711. second = matchPreviousLiteral(first)
  2712. matchExpr = first + ":" + second
  2713. will match C{"1:1"}, but not C{"1:2"}. Because this matches a
  2714. previous literal, will also match the leading C{"1:1"} in C{"1:10"}.
  2715. If this is not desired, use C{matchPreviousExpr}.
  2716. Do *not* use with packrat parsing enabled.
  2717. """
  2718. rep = Forward()
  2719. def copyTokenToRepeater(s,l,t):
  2720. if t:
  2721. if len(t) == 1:
  2722. rep << t[0]
  2723. else:
  2724. # flatten t tokens
  2725. tflat = _flatten(t.asList())
  2726. rep << And( [ Literal(tt) for tt in tflat ] )
  2727. else:
  2728. rep << Empty()
  2729. expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
  2730. return rep
  2731. def matchPreviousExpr(expr):
  2732. """Helper to define an expression that is indirectly defined from
  2733. the tokens matched in a previous expression, that is, it looks
  2734. for a 'repeat' of a previous expression. For example::
  2735. first = Word(nums)
  2736. second = matchPreviousExpr(first)
  2737. matchExpr = first + ":" + second
  2738. will match C{"1:1"}, but not C{"1:2"}. Because this matches by
  2739. expressions, will *not* match the leading C{"1:1"} in C{"1:10"};
  2740. the expressions are evaluated first, and then compared, so
  2741. C{"1"} is compared with C{"10"}.
  2742. Do *not* use with packrat parsing enabled.
  2743. """
  2744. rep = Forward()
  2745. e2 = expr.copy()
  2746. rep << e2
  2747. def copyTokenToRepeater(s,l,t):
  2748. matchTokens = _flatten(t.asList())
  2749. def mustMatchTheseTokens(s,l,t):
  2750. theseTokens = _flatten(t.asList())
  2751. if theseTokens != matchTokens:
  2752. raise ParseException("",0,"")
  2753. rep.setParseAction( mustMatchTheseTokens, callDuringTry=True )
  2754. expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
  2755. return rep
  2756. def _escapeRegexRangeChars(s):
  2757. #~ escape these chars: ^-]
  2758. for c in r"\^-]":
  2759. s = s.replace(c,_bslash+c)
  2760. s = s.replace("\n",r"\n")
  2761. s = s.replace("\t",r"\t")
  2762. return _ustr(s)
  2763. def oneOf( strs, caseless=False, useRegex=True ):
  2764. """Helper to quickly define a set of alternative Literals, and makes sure to do
  2765. longest-first testing when there is a conflict, regardless of the input order,
  2766. but returns a C{MatchFirst} for best performance.
  2767. Parameters:
  2768. - strs - a string of space-delimited literals, or a list of string literals
  2769. - caseless - (default=False) - treat all literals as caseless
  2770. - useRegex - (default=True) - as an optimization, will generate a Regex
  2771. object; otherwise, will generate a C{MatchFirst} object (if C{caseless=True}, or
  2772. if creating a C{Regex} raises an exception)
  2773. """
  2774. if caseless:
  2775. isequal = ( lambda a,b: a.upper() == b.upper() )
  2776. masks = ( lambda a,b: b.upper().startswith(a.upper()) )
  2777. parseElementClass = CaselessLiteral
  2778. else:
  2779. isequal = ( lambda a,b: a == b )
  2780. masks = ( lambda a,b: b.startswith(a) )
  2781. parseElementClass = Literal
  2782. if isinstance(strs,(list,tuple)):
  2783. symbols = list(strs[:])
  2784. elif isinstance(strs,basestring):
  2785. symbols = strs.split()
  2786. else:
  2787. warnings.warn("Invalid argument to oneOf, expected string or list",
  2788. SyntaxWarning, stacklevel=2)
  2789. i = 0
  2790. while i < len(symbols)-1:
  2791. cur = symbols[i]
  2792. for j,other in enumerate(symbols[i+1:]):
  2793. if ( isequal(other, cur) ):
  2794. del symbols[i+j+1]
  2795. break
  2796. elif ( masks(cur, other) ):
  2797. del symbols[i+j+1]
  2798. symbols.insert(i,other)
  2799. cur = other
  2800. break
  2801. else:
  2802. i += 1
  2803. if not caseless and useRegex:
  2804. #~ print (strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] ))
  2805. try:
  2806. if len(symbols)==len("".join(symbols)):
  2807. return Regex( "[%s]" % "".join( [ _escapeRegexRangeChars(sym) for sym in symbols] ) )
  2808. else:
  2809. return Regex( "|".join( [ re.escape(sym) for sym in symbols] ) )
  2810. except:
  2811. warnings.warn("Exception creating Regex for oneOf, building MatchFirst",
  2812. SyntaxWarning, stacklevel=2)
  2813. # last resort, just use MatchFirst
  2814. return MatchFirst( [ parseElementClass(sym) for sym in symbols ] )
  2815. def dictOf( key, value ):
  2816. """Helper to easily and clearly define a dictionary by specifying the respective patterns
  2817. for the key and value. Takes care of defining the C{Dict}, C{ZeroOrMore}, and C{Group} tokens
  2818. in the proper order. The key pattern can include delimiting markers or punctuation,
  2819. as long as they are suppressed, thereby leaving the significant key text. The value
  2820. pattern can include named results, so that the C{Dict} results can include named token
  2821. fields.
  2822. """
  2823. return Dict( ZeroOrMore( Group ( key + value ) ) )
  2824. def originalTextFor(expr, asString=True):
  2825. """Helper to return the original, untokenized text for a given expression. Useful to
  2826. restore the parsed fields of an HTML start tag into the raw tag text itself, or to
  2827. revert separate tokens with intervening whitespace back to the original matching
  2828. input text. Simpler to use than the parse action C{keepOriginalText}, and does not
  2829. require the inspect module to chase up the call stack. By default, returns a
  2830. string containing the original parsed text.
  2831. If the optional C{asString} argument is passed as False, then the return value is a
  2832. C{ParseResults} containing any results names that were originally matched, and a
  2833. single token containing the original matched text from the input string. So if
  2834. the expression passed to C{originalTextFor} contains expressions with defined
  2835. results names, you must set C{asString} to False if you want to preserve those
  2836. results name values."""
  2837. locMarker = Empty().setParseAction(lambda s,loc,t: loc)
  2838. endlocMarker = locMarker.copy()
  2839. endlocMarker.callPreparse = False
  2840. matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
  2841. if asString:
  2842. extractText = lambda s,l,t: s[t._original_start:t._original_end]
  2843. else:
  2844. def extractText(s,l,t):
  2845. del t[:]
  2846. t.insert(0, s[t._original_start:t._original_end])
  2847. del t["_original_start"]
  2848. del t["_original_end"]
  2849. matchExpr.setParseAction(extractText)
  2850. return matchExpr
  2851. # convenience constants for positional expressions
  2852. empty = Empty().setName("empty")
  2853. lineStart = LineStart().setName("lineStart")
  2854. lineEnd = LineEnd().setName("lineEnd")
  2855. stringStart = StringStart().setName("stringStart")
  2856. stringEnd = StringEnd().setName("stringEnd")
  2857. _escapedPunc = Word( _bslash, r"\[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1])
  2858. _printables_less_backslash = "".join([ c for c in printables if c not in r"\]" ])
  2859. _escapedHexChar = Combine( Suppress(_bslash + "0x") + Word(hexnums) ).setParseAction(lambda s,l,t:unichr(int(t[0],16)))
  2860. _escapedOctChar = Combine( Suppress(_bslash) + Word("0","01234567") ).setParseAction(lambda s,l,t:unichr(int(t[0],8)))
  2861. _singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | Word(_printables_less_backslash,exact=1)
  2862. _charRange = Group(_singleChar + Suppress("-") + _singleChar)
  2863. _reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]"
  2864. _expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in range(ord(p[0]),ord(p[1])+1) ]) or p)
  2865. def srange(s):
  2866. r"""Helper to easily define string ranges for use in Word construction. Borrows
  2867. syntax from regexp '[]' string range definitions::
  2868. srange("[0-9]") -> "0123456789"
  2869. srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
  2870. srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
  2871. The input string must be enclosed in []'s, and the returned string is the expanded
  2872. character set joined into a single string.
  2873. The values enclosed in the []'s may be::
  2874. a single character
  2875. an escaped character with a leading backslash (such as \- or \])
  2876. an escaped hex character with a leading '\0x' (\0x21, which is a '!' character)
  2877. an escaped octal character with a leading '\0' (\041, which is a '!' character)
  2878. a range of any of the above, separated by a dash ('a-z', etc.)
  2879. any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.)
  2880. """
  2881. try:
  2882. return "".join([_expanded(part) for part in _reBracketExpr.parseString(s).body])
  2883. except:
  2884. return ""
  2885. def matchOnlyAtCol(n):
  2886. """Helper method for defining parse actions that require matching at a specific
  2887. column in the input text.
  2888. """
  2889. def verifyCol(strg,locn,toks):
  2890. if col(locn,strg) != n:
  2891. raise ParseException(strg,locn,"matched token not at column %d" % n)
  2892. return verifyCol
  2893. def replaceWith(replStr):
  2894. """Helper method for common parse actions that simply return a literal value. Especially
  2895. useful when used with C{transformString()}.
  2896. """
  2897. def _replFunc(*args):
  2898. return [replStr]
  2899. return _replFunc
  2900. def removeQuotes(s,l,t):
  2901. """Helper parse action for removing quotation marks from parsed quoted strings.
  2902. To use, add this parse action to quoted string using::
  2903. quotedString.setParseAction( removeQuotes )
  2904. """
  2905. return t[0][1:-1]
  2906. def upcaseTokens(s,l,t):
  2907. """Helper parse action to convert tokens to upper case."""
  2908. return [ tt.upper() for tt in map(_ustr,t) ]
  2909. def downcaseTokens(s,l,t):
  2910. """Helper parse action to convert tokens to lower case."""
  2911. return [ tt.lower() for tt in map(_ustr,t) ]
  2912. def keepOriginalText(s,startLoc,t):
  2913. """DEPRECATED - use new helper method C{originalTextFor}.
  2914. Helper parse action to preserve original parsed text,
  2915. overriding any nested parse actions."""
  2916. try:
  2917. endloc = getTokensEndLoc()
  2918. except ParseException:
  2919. raise ParseFatalException("incorrect usage of keepOriginalText - may only be called as a parse action")
  2920. del t[:]
  2921. t += ParseResults(s[startLoc:endloc])
  2922. return t
  2923. def getTokensEndLoc():
  2924. """Method to be called from within a parse action to determine the end
  2925. location of the parsed tokens."""
  2926. import inspect
  2927. fstack = inspect.stack()
  2928. try:
  2929. # search up the stack (through intervening argument normalizers) for correct calling routine
  2930. for f in fstack[2:]:
  2931. if f[3] == "_parseNoCache":
  2932. endloc = f[0].f_locals["loc"]
  2933. return endloc
  2934. else:
  2935. raise ParseFatalException("incorrect usage of getTokensEndLoc - may only be called from within a parse action")
  2936. finally:
  2937. del fstack
  2938. def _makeTags(tagStr, xml):
  2939. """Internal helper to construct opening and closing tag expressions, given a tag name"""
  2940. if isinstance(tagStr,basestring):
  2941. resname = tagStr
  2942. tagStr = Keyword(tagStr, caseless=not xml)
  2943. else:
  2944. resname = tagStr.name
  2945. tagAttrName = Word(alphas,alphanums+"_-:")
  2946. if (xml):
  2947. tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes )
  2948. openTag = Suppress("<") + tagStr("tag") + \
  2949. Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \
  2950. Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
  2951. else:
  2952. printablesLessRAbrack = "".join( [ c for c in printables if c not in ">" ] )
  2953. tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack)
  2954. openTag = Suppress("<") + tagStr + \
  2955. Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \
  2956. Optional( Suppress("=") + tagAttrValue ) ))) + \
  2957. Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
  2958. closeTag = Combine(_L("</") + tagStr + ">")
  2959. openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % tagStr)
  2960. closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % tagStr)
  2961. openTag.tag = resname
  2962. closeTag.tag = resname
  2963. return openTag, closeTag
  2964. def makeHTMLTags(tagStr):
  2965. """Helper to construct opening and closing tag expressions for HTML, given a tag name"""
  2966. return _makeTags( tagStr, False )
  2967. def makeXMLTags(tagStr):
  2968. """Helper to construct opening and closing tag expressions for XML, given a tag name"""
  2969. return _makeTags( tagStr, True )
  2970. def withAttribute(*args,**attrDict):
  2971. """Helper to create a validating parse action to be used with start tags created
  2972. with makeXMLTags or makeHTMLTags. Use withAttribute to qualify a starting tag
  2973. with a required attribute value, to avoid false matches on common tags such as
  2974. <TD> or <DIV>.
  2975. Call withAttribute with a series of attribute names and values. Specify the list
  2976. of filter attributes names and values as:
  2977. - keyword arguments, as in (class="Customer",align="right"), or
  2978. - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )
  2979. For attribute names with a namespace prefix, you must use the second form. Attribute
  2980. names are matched insensitive to upper/lower case.
  2981. To verify that the attribute exists, but without specifying a value, pass
  2982. withAttribute.ANY_VALUE as the value.
  2983. """
  2984. if args:
  2985. attrs = args[:]
  2986. else:
  2987. attrs = attrDict.items()
  2988. attrs = [(k,v) for k,v in attrs]
  2989. def pa(s,l,tokens):
  2990. for attrName,attrValue in attrs:
  2991. if attrName not in tokens:
  2992. raise ParseException(s,l,"no matching attribute " + attrName)
  2993. if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue:
  2994. raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" %
  2995. (attrName, tokens[attrName], attrValue))
  2996. return pa
  2997. withAttribute.ANY_VALUE = object()
  2998. opAssoc = _Constants()
  2999. opAssoc.LEFT = object()
  3000. opAssoc.RIGHT = object()
  3001. def operatorPrecedence( baseExpr, opList ):
  3002. """Helper method for constructing grammars of expressions made up of
  3003. operators working in a precedence hierarchy. Operators may be unary or
  3004. binary, left- or right-associative. Parse actions can also be attached
  3005. to operator expressions.
  3006. Parameters:
  3007. - baseExpr - expression representing the most basic element for the nested
  3008. - opList - list of tuples, one for each operator precedence level in the
  3009. expression grammar; each tuple is of the form
  3010. (opExpr, numTerms, rightLeftAssoc, parseAction), where:
  3011. - opExpr is the pyparsing expression for the operator;
  3012. may also be a string, which will be converted to a Literal;
  3013. if numTerms is 3, opExpr is a tuple of two expressions, for the
  3014. two operators separating the 3 terms
  3015. - numTerms is the number of terms for this operator (must
  3016. be 1, 2, or 3)
  3017. - rightLeftAssoc is the indicator whether the operator is
  3018. right or left associative, using the pyparsing-defined
  3019. constants opAssoc.RIGHT and opAssoc.LEFT.
  3020. - parseAction is the parse action to be associated with
  3021. expressions matching this operator expression (the
  3022. parse action tuple member may be omitted)
  3023. """
  3024. ret = Forward()
  3025. lastExpr = baseExpr | ( Suppress('(') + ret + Suppress(')') )
  3026. for i,operDef in enumerate(opList):
  3027. opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4]
  3028. if arity == 3:
  3029. if opExpr is None or len(opExpr) != 2:
  3030. raise ValueError("if numterms=3, opExpr must be a tuple or list of two expressions")
  3031. opExpr1, opExpr2 = opExpr
  3032. thisExpr = Forward()#.setName("expr%d" % i)
  3033. if rightLeftAssoc == opAssoc.LEFT:
  3034. if arity == 1:
  3035. matchExpr = FollowedBy(lastExpr + opExpr) + Group( lastExpr + OneOrMore( opExpr ) )
  3036. elif arity == 2:
  3037. if opExpr is not None:
  3038. matchExpr = FollowedBy(lastExpr + opExpr + lastExpr) + Group( lastExpr + OneOrMore( opExpr + lastExpr ) )
  3039. else:
  3040. matchExpr = FollowedBy(lastExpr+lastExpr) + Group( lastExpr + OneOrMore(lastExpr) )
  3041. elif arity == 3:
  3042. matchExpr = FollowedBy(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) + \
  3043. Group( lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr )
  3044. else:
  3045. raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
  3046. elif rightLeftAssoc == opAssoc.RIGHT:
  3047. if arity == 1:
  3048. # try to avoid LR with this extra test
  3049. if not isinstance(opExpr, Optional):
  3050. opExpr = Optional(opExpr)
  3051. matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr )
  3052. elif arity == 2:
  3053. if opExpr is not None:
  3054. matchExpr = FollowedBy(lastExpr + opExpr + thisExpr) + Group( lastExpr + OneOrMore( opExpr + thisExpr ) )
  3055. else:
  3056. matchExpr = FollowedBy(lastExpr + thisExpr) + Group( lastExpr + OneOrMore( thisExpr ) )
  3057. elif arity == 3:
  3058. matchExpr = FollowedBy(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + \
  3059. Group( lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr )
  3060. else:
  3061. raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
  3062. else:
  3063. raise ValueError("operator must indicate right or left associativity")
  3064. if pa:
  3065. matchExpr.setParseAction( pa )
  3066. thisExpr << ( matchExpr | lastExpr )
  3067. lastExpr = thisExpr
  3068. ret << lastExpr
  3069. return ret
  3070. dblQuotedString = Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*"').setName("string enclosed in double quotes")
  3071. sglQuotedString = Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*'").setName("string enclosed in single quotes")
  3072. quotedString = Regex(r'''(?:"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*")|(?:'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*')''').setName("quotedString using single or double quotes")
  3073. unicodeString = Combine(_L('u') + quotedString.copy())
  3074. def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()):
  3075. """Helper method for defining nested lists enclosed in opening and closing
  3076. delimiters ("(" and ")" are the default).
  3077. Parameters:
  3078. - opener - opening character for a nested list (default="("); can also be a pyparsing expression
  3079. - closer - closing character for a nested list (default=")"); can also be a pyparsing expression
  3080. - content - expression for items within the nested lists (default=None)
  3081. - ignoreExpr - expression for ignoring opening and closing delimiters (default=quotedString)
  3082. If an expression is not provided for the content argument, the nested
  3083. expression will capture all whitespace-delimited content between delimiters
  3084. as a list of separate values.
  3085. Use the ignoreExpr argument to define expressions that may contain
  3086. opening or closing characters that should not be treated as opening
  3087. or closing characters for nesting, such as quotedString or a comment
  3088. expression. Specify multiple expressions using an Or or MatchFirst.
  3089. The default is quotedString, but if no expressions are to be ignored,
  3090. then pass None for this argument.
  3091. """
  3092. if opener == closer:
  3093. raise ValueError("opening and closing strings cannot be the same")
  3094. if content is None:
  3095. if isinstance(opener,basestring) and isinstance(closer,basestring):
  3096. if len(opener) == 1 and len(closer)==1:
  3097. if ignoreExpr is not None:
  3098. content = (Combine(OneOrMore(~ignoreExpr +
  3099. CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS,exact=1))
  3100. ).setParseAction(lambda t:t[0].strip()))
  3101. else:
  3102. content = (empty.copy()+CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS
  3103. ).setParseAction(lambda t:t[0].strip()))
  3104. else:
  3105. if ignoreExpr is not None:
  3106. content = (Combine(OneOrMore(~ignoreExpr +
  3107. ~Literal(opener) + ~Literal(closer) +
  3108. CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1))
  3109. ).setParseAction(lambda t:t[0].strip()))
  3110. else:
  3111. content = (Combine(OneOrMore(~Literal(opener) + ~Literal(closer) +
  3112. CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1))
  3113. ).setParseAction(lambda t:t[0].strip()))
  3114. else:
  3115. raise ValueError("opening and closing arguments must be strings if no content expression is given")
  3116. ret = Forward()
  3117. if ignoreExpr is not None:
  3118. ret << Group( Suppress(opener) + ZeroOrMore( ignoreExpr | ret | content ) + Suppress(closer) )
  3119. else:
  3120. ret << Group( Suppress(opener) + ZeroOrMore( ret | content ) + Suppress(closer) )
  3121. return ret
  3122. def indentedBlock(blockStatementExpr, indentStack, indent=True):
  3123. """Helper method for defining space-delimited indentation blocks, such as
  3124. those used to define block statements in Python source code.
  3125. Parameters:
  3126. - blockStatementExpr - expression defining syntax of statement that
  3127. is repeated within the indented block
  3128. - indentStack - list created by caller to manage indentation stack
  3129. (multiple statementWithIndentedBlock expressions within a single grammar
  3130. should share a common indentStack)
  3131. - indent - boolean indicating whether block must be indented beyond the
  3132. the current level; set to False for block of left-most statements
  3133. (default=True)
  3134. A valid block must contain at least one blockStatement.
  3135. """
  3136. def checkPeerIndent(s,l,t):
  3137. if l >= len(s): return
  3138. curCol = col(l,s)
  3139. if curCol != indentStack[-1]:
  3140. if curCol > indentStack[-1]:
  3141. raise ParseFatalException(s,l,"illegal nesting")
  3142. raise ParseException(s,l,"not a peer entry")
  3143. def checkSubIndent(s,l,t):
  3144. curCol = col(l,s)
  3145. if curCol > indentStack[-1]:
  3146. indentStack.append( curCol )
  3147. else:
  3148. raise ParseException(s,l,"not a subentry")
  3149. def checkUnindent(s,l,t):
  3150. if l >= len(s): return
  3151. curCol = col(l,s)
  3152. if not(indentStack and curCol < indentStack[-1] and curCol <= indentStack[-2]):
  3153. raise ParseException(s,l,"not an unindent")
  3154. indentStack.pop()
  3155. NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress())
  3156. INDENT = Empty() + Empty().setParseAction(checkSubIndent)
  3157. PEER = Empty().setParseAction(checkPeerIndent)
  3158. UNDENT = Empty().setParseAction(checkUnindent)
  3159. if indent:
  3160. smExpr = Group( Optional(NL) +
  3161. #~ FollowedBy(blockStatementExpr) +
  3162. INDENT + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) + UNDENT)
  3163. else:
  3164. smExpr = Group( Optional(NL) +
  3165. (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) )
  3166. blockStatementExpr.ignore(_bslash + LineEnd())
  3167. return smExpr
  3168. alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]")
  3169. punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]")
  3170. anyOpenTag,anyCloseTag = makeHTMLTags(Word(alphas,alphanums+"_:"))
  3171. commonHTMLEntity = Combine(_L("&") + oneOf("gt lt amp nbsp quot").setResultsName("entity") +";").streamline()
  3172. _htmlEntityMap = dict(zip("gt lt amp nbsp quot".split(),'><& "'))
  3173. replaceHTMLEntity = lambda t : t.entity in _htmlEntityMap and _htmlEntityMap[t.entity] or None
  3174. # it's easy to get these comment structures wrong - they're very common, so may as well make them available
  3175. cStyleComment = Regex(r"/\*(?:[^*]*\*+)+?/").setName("C style comment")
  3176. htmlComment = Regex(r"<!--[\s\S]*?-->")
  3177. restOfLine = Regex(r".*").leaveWhitespace()
  3178. dblSlashComment = Regex(r"\/\/(\\\n|.)*").setName("// comment")
  3179. cppStyleComment = Regex(r"/(?:\*(?:[^*]*\*+)+?/|/[^\n]*(?:\n[^\n]*)*?(?:(?<!\\)|\Z))").setName("C++ style comment")
  3180. javaStyleComment = cppStyleComment
  3181. pythonStyleComment = Regex(r"#.*").setName("Python style comment")
  3182. _noncomma = "".join( [ c for c in printables if c != "," ] )
  3183. _commasepitem = Combine(OneOrMore(Word(_noncomma) +
  3184. Optional( Word(" \t") +
  3185. ~Literal(",") + ~LineEnd() ) ) ).streamline().setName("commaItem")
  3186. commaSeparatedList = delimitedList( Optional( quotedString.copy() | _commasepitem, default="") ).setName("commaSeparatedList")
  3187. if __name__ == "__main__":
  3188. def test( teststring ):
  3189. try:
  3190. tokens = simpleSQL.parseString( teststring )
  3191. tokenlist = tokens.asList()
  3192. print (teststring + "->" + str(tokenlist))
  3193. print ("tokens = " + str(tokens))
  3194. print ("tokens.columns = " + str(tokens.columns))
  3195. print ("tokens.tables = " + str(tokens.tables))
  3196. print (tokens.asXML("SQL",True))
  3197. except ParseBaseException as err:
  3198. print (teststring + "->")
  3199. print (err.line)
  3200. print (" "*(err.column-1) + "^")
  3201. print (err)
  3202. print()
  3203. selectToken = CaselessLiteral( "select" )
  3204. fromToken = CaselessLiteral( "from" )
  3205. ident = Word( alphas, alphanums + "_$" )
  3206. columnName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
  3207. columnNameList = Group( delimitedList( columnName ) )#.setName("columns")
  3208. tableName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
  3209. tableNameList = Group( delimitedList( tableName ) )#.setName("tables")
  3210. simpleSQL = ( selectToken + \
  3211. ( '*' | columnNameList ).setResultsName( "columns" ) + \
  3212. fromToken + \
  3213. tableNameList.setResultsName( "tables" ) )
  3214. test( "SELECT * from XYZZY, ABC" )
  3215. test( "select * from SYS.XYZZY" )
  3216. test( "Select A from Sys.dual" )
  3217. test( "Select AA,BB,CC from Sys.dual" )
  3218. test( "Select A, B, C from Sys.dual" )
  3219. test( "Select A, B, C from Sys.dual" )
  3220. test( "Xelect A, B, C from Sys.dual" )
  3221. test( "Select A, B, C frox Sys.dual" )
  3222. test( "Select" )
  3223. test( "Select ^^^ frox Sys.dual" )
  3224. test( "Select A, B, C from Sys.dual, Table2 " )