PageRenderTime 57ms 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

Large files files are truncated, but you can click here to view the full file

  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 ):

Large files files are truncated, but you can click here to view the full file