pyparsing.py 157 KB

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