3 ”Reò+ã¢@sdZdZdZdZddlZddlmZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlmZddlmZddlZdd lmZdd lmZydd lmZWn ek rÔdd lmZYnXydd lmZWn"ek �rdd lmZYnXy ddlm Z ddlm!Z!m"Z"Wn2ek �r\ddl m Z ddl m!Z!m"Z"YnXyddl m#Z$WnBek �r°yddl%m#Z$Wnek �rªdZ$YnXYnXyddlm&Z&Wn$ek �ræGdd„dƒZ&YnXe&ƒZ'de'_de'_(e&ƒZ)de)_de)_*de)_+de)_,de)_-de)_.dd„e/e)ƒDƒe)_0dd„Z1e1e)_2ddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dd€d�d‚dƒd„d…d†d‡dˆd‰dŠd‹dŒd�dŽd�gtZ3e4e j5ƒdd�…Z6e6dd�kZ7e7�rˆe j8Z9e:Z;ee:Z?e@eAeBeCeDe4eEeFeGeHeIg ZJnbe jKZ9eLZMd‘d’„Z?gZJddlNZNxBd“jOƒD]6ZPyeJjQeReNePƒƒWneSk �râ�w°YnX�q°WeTd”d•„eMd–ƒDƒƒZUd—d˜„ZVejWejXZYd™ZZeZdšZ[eYeZZ\e„d>ehƒZje!jkejƒd§dV„Zld¨dg„Zmd©dd„Zndªd«„Zod¬d­„Zpd®d¯„Zqd°dn„Zr�dbd²d³„ZsGd´d@„d@ehƒZtGdµd¶„d¶etƒZuGd·dH„dHetƒZvGd¸d(„d(evƒZwGd¹d3„d3evƒZxGdºd0„d0evƒZyGd»d¼„d¼eyƒZzeyZ{eyet_|Gd½d-„d-evƒZ}Gd¾d#„d#eyƒZ~Gd¿d"„d"e}ƒZGdÀd‰„d‰evƒZ€GdÁdK„dKevƒZ�GdÂdÄdÃe�ƒZ‚GdÄdO„dOe‚ƒZƒGdÅdC„dCevƒZ„GdÆdA„dAevƒZ…GdÇd$„d$evƒZ†GdÈdJ„dJevƒZ‡GdÉdÊ„dÊevƒZˆGdËd+„d+eˆƒZ‰GdÌd/„d/eˆƒZŠGdÍd.„d.eˆƒZ‹GdÎdF„dFeˆƒZŒGdÏdE„dEeˆƒZ�GdÐdM„dMeˆƒZŽGdÑdL„dLeˆƒZ�GdÒd<„dƒZëe§e�eÔjƒeëBdœ�d?�ƒj²dWƒZìG�d@d‹„d‹ƒZíG�dA�dB„�dBehƒZîG�dCd�„d�ehƒZïG�dDdŒ„dŒeïƒZðeðjñjòjóeðjñjôjóeðjñjõjóeðjñ_óe7� r˜eöeð�dEeðj÷ƒeöeð�dFeðjøƒeöeð�dGeðjùƒeöeð�dHeðjúƒeöeð�dIeðjûƒeöeð�dJeðjñƒeöeðjñ�dKeðjñjòƒeöeðjñ�dLeðjñjõƒeöeðjñ�dMeðjñjôƒeöeð�dNeðjüƒeöeð�dOeðjýƒeöeð�dPeðjþƒG�dQ�dR„�dRƒZÿ�e�dSk�re~�dTƒ�Ze~�dUƒ�Ze�eYe\�dVƒ�Ze§�e�dWd�dX�j¸eŃ�Ze¢e§�eƒƒj²�dYƒ�Z�dZ�eB�Ze§�e�dWd�dX�j¸eŃ�Ze¢e§�eƒƒj²�d[ƒ�Z�e�d\ƒ�e�dYƒ�e�e�d[ƒ�Z �e �j �d]ƒeí�j �j �d^ƒeí�j �j �d^ƒeí�j �j �d_ƒdd�l�Zeí�jj¸eÄ�e�jƒƒeí�j�j �d`ƒdS(ia× pyparsing module - Classes and methods to define and execute parsing grammars ============================================================================= The pyparsing module is an alternative approach to creating and executing simple grammars, vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you don't need to learn a new syntax for defining grammars or matching expressions - the parsing module provides a library of classes that you use to construct the grammar directly in Python. Here is a program to parse "Hello, World!" (or any greeting of the form ``", !"``), built up using :class:`Word`, :class:`Literal`, and :class:`And` elements (the :class:`'+'` operators create :class:`And` expressions, and the strings are auto-converted to :class:`Literal` expressions):: from pip._vendor.pyparsing import Word, alphas # define grammar of a greeting greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) The program outputs the following:: Hello, World! -> ['Hello', ',', 'World', '!'] The Python representation of the grammar is quite readable, owing to the self-explanatory class names, and the use of '+', '|' and '^' operators. The :class:`ParseResults` object returned from :class:`ParserElement.parseString` can be accessed as a nested list, a dictionary, or an object with named attributes. The pyparsing module handles some of the problems that are typically vexing when writing text parsers: - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.) - quoted strings - embedded comments Getting Started - ----------------- Visit the classes :class:`ParserElement` and :class:`ParseResults` to see the base classes that most other pyparsing classes inherit from. Use the docstrings for examples of how to: - construct literal match expressions from :class:`Literal` and :class:`CaselessLiteral` classes - construct character word-group expressions using the :class:`Word` class - see how to create repetitive expressions using :class:`ZeroOrMore` and :class:`OneOrMore` classes - use :class:`'+'`, :class:`'|'`, :class:`'^'`, and :class:`'&'` operators to combine simple expressions into more complex ones - associate names with your parsed results using :class:`ParserElement.setResultsName` - access the parsed data, which is returned as a :class:`ParseResults` object - find some helpful expression short-cuts like :class:`delimitedList` and :class:`oneOf` - find more useful common expressions in the :class:`pyparsing_common` namespace class z2.4.7z30 Mar 2020 00:43 UTCz*Paul McGuire éN)Úref)Údatetime)Ú itemgetter)Úwraps)Úcontextmanager)Ú filterfalse)Ú ifilterfalse)ÚRLock)ÚIterable)ÚMutableMappingÚMapping)Ú OrderedDict)ÚSimpleNamespacec@s eZdZdS)rN)Ú__name__Ú __module__Ú __qualname__©rrú„/builddir/build/BUILDROOT/alt-python36-pip-20.2.4-5.el8.x86_64/opt/alt/python36/lib/python3.6/site-packages/pip/_vendor/pyparsing.pyr–sraA A cross-version compatibility configuration for pyparsing features that will be released in a future version. By setting values in this configuration to True, those features can be enabled in prior versions for compatibility development and testing. - collect_all_And_tokens - flag to enable fix for Issue #63 that fixes erroneous grouping of results names when an And expression is nested within an Or or MatchFirst; set to True to enable bugfix released in pyparsing 2.3.0, or False to preserve pre-2.3.0 handling of named results Ta“ Diagnostic configuration (all default to False) - warn_multiple_tokens_in_named_alternation - flag to enable warnings when a results name is defined on a MatchFirst or Or expression with one or more And subexpressions (only warns if __compat__.collect_all_And_tokens is False) - warn_ungrouped_named_tokens_in_collection - flag to enable warnings when a results name is defined on a containing expression with ungrouped subexpressions that also have results names - warn_name_set_on_empty_Forward - flag to enable warnings whan a Forward is defined with a results name, but has no contents defined - warn_on_multiple_string_args_to_oneof - flag to enable warnings whan oneOf is incorrectly called with multiple str arguments - enable_debug_on_named_expressions - flag to auto-enable debug on all subsequent calls to ParserElement.setName() FcCs$g|]}|jdƒs|jdƒr|‘qS)Zenable_Zwarn_)Ú startswith)Ú.0Únmrrrú ¼srcCsdt_dt_dt_dt_dS)NT)Ú__diag__Ú)warn_multiple_tokens_in_named_alternationÚ)warn_ungrouped_named_tokens_in_collectionÚwarn_name_set_on_empty_ForwardÚ%warn_on_multiple_string_args_to_oneofrrrrÚ_enable_all_warnings¾srÚ __version__Ú__versionTime__Ú __author__Ú __compat__rÚAndÚCaselessKeywordÚCaselessLiteralÚ CharsNotInÚCombineÚDictÚEachÚEmptyÚ FollowedByÚForwardÚ GoToColumnÚGroupÚKeywordÚLineEndÚ LineStartÚLiteralÚ PrecededByÚ MatchFirstÚNoMatchÚNotAnyÚ OneOrMoreÚOnlyOnceÚOptionalÚOrÚParseBaseExceptionÚParseElementEnhanceÚParseExceptionÚParseExpressionÚParseFatalExceptionÚ ParseResultsÚParseSyntaxExceptionÚ ParserElementÚ QuotedStringÚRecursiveGrammarExceptionÚRegexÚSkipToÚ StringEndÚ StringStartÚSuppressÚTokenÚTokenConverterÚWhiteÚWordÚWordEndÚ WordStartÚ ZeroOrMoreÚCharÚ alphanumsÚalphasÚ alphas8bitÚ anyCloseTagÚ anyOpenTagÚ cStyleCommentÚcolÚcommaSeparatedListÚcommonHTMLEntityÚ countedArrayÚcppStyleCommentÚdblQuotedStringÚdblSlashCommentÚ delimitedListÚdictOfÚdowncaseTokensÚemptyÚhexnumsÚ htmlCommentÚjavaStyleCommentÚlineÚlineEndÚ lineStartÚlinenoÚ makeHTMLTagsÚ makeXMLTagsÚmatchOnlyAtColÚmatchPreviousExprÚmatchPreviousLiteralÚ nestedExprÚnullDebugActionÚnumsÚoneOfÚopAssocÚoperatorPrecedenceÚ printablesÚpunc8bitÚpythonStyleCommentÚ quotedStringÚ removeQuotesÚreplaceHTMLEntityÚ replaceWithÚ restOfLineÚsglQuotedStringÚsrangeÚ stringEndÚ stringStartÚtraceParseActionÚ unicodeStringÚ upcaseTokensÚ withAttributeÚ indentedBlockÚoriginalTextForÚungroupÚ infixNotationÚ locatedExprÚ withClassÚ CloseMatchÚtokenMapÚpyparsing_commonÚpyparsing_unicodeÚ unicode_setÚconditionAsParseActionÚreéc Cs`t|tƒr|Syt|ƒStk rZt|ƒjtjƒdƒ}tdƒ}|jdd„ƒ|j |ƒSXdS)aDrop-in replacement for str(obj) that tries to be Unicode friendly. It first tries str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It then < returns the unicode object | encodes it with the default encoding | ... >. Úxmlcharrefreplacez&#\d+;cSs$dtt|ddd…ƒƒdd…S)Nz\uréééÿÿÿÿ)ÚhexÚint)ÚtrrrÚÿsz_ustr..N) Ú isinstanceÚunicodeÚstrÚUnicodeEncodeErrorÚencodeÚsysÚgetdefaultencodingrDÚsetParseActionÚtransformString)ÚobjÚretZ xmlcharrefrrrÚ_ustrìs r¥z6sum len sorted reversed list tuple set any all min maxccs|] }|VqdS)Nr)rÚyrrrú sr§r”cCs>d}dd„djƒDƒ}x"t||ƒD]\}}|j||ƒ}q"W|S)z/Escape &, <, >, ", ', etc. in a string of data.z&><"'css|]}d|dVqdS)ú&ú;Nr)rÚsrrrr§sz_xml_escape..zamp gt lt quot apos)ÚsplitÚzipÚreplace)ÚdataÚ from_symbolsÚ to_symbolsÚfrom_Úto_rrrÚ _xml_escapes r³Ú 0123456789Z ABCDEFabcdefé\Úccs|]}|tjkr|VqdS)N)ÚstringÚ whitespace)rÚcrrrr§scs@|dk r |nd‰|rtnt‰tˆƒ‰tˆƒ‡‡‡fdd„ƒ}|S)Nzfailed user-defined conditioncs tˆ|||ƒƒsˆ||ˆƒ‚dS)N)Úbool)rªÚlr˜)Úexc_typeÚfnÚmsgrrÚpa%sz"conditionAsParseAction..pa)r>r<Ú _trim_arityr)r½ÚmessageÚfatalr¿r)r¼r½r¾rr� s  c@sPeZdZdZddd„Zedd„ƒZdd „Zd d „Zd d „Z ddd„Z dd„Z dS)r:z7base exception class for all parsing runtime exceptionsrNcCs>||_|dkr||_d|_n ||_||_||_|||f|_dS)Nr¶)Úlocr¾ÚpstrÚ parserElementÚargs)ÚselfrÄrÃr¾ÚelemrrrÚ__init__0szParseBaseException.__init__cCs||j|j|j|jƒS)z¬ internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses )rÄrÃr¾rÅ)ÚclsÚperrrÚ_from_exception;sz"ParseBaseException._from_exceptioncCsN|dkrt|j|jƒS|dkr,t|j|jƒS|dkrBt|j|jƒSt|ƒ‚dS)zôsupported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text rhrWÚcolumnreN)rWrÍ)rhrÃrÄrWreÚAttributeError)rÇÚanamerrrÚ __getattr__CszParseBaseException.__getattr__cCs^|jr@|jt|jƒkrd}qDd|j|j|jd…jddƒ}nd}d|j||j|j|jfS)Nz, found end of textz , found %rr”z\\ú\r¶z%%s%s (at char %d), (line:%d, col:%d))rÄrÃÚlenr­r¾rhrÍ)rÇÚfoundstrrrrÚ__str__Rs$zParseBaseException.__str__cCst|ƒS)N)r¥)rÇrrrÚ__repr__\szParseBaseException.__repr__ú>!z{0}Ú )rærç)rèré)ÚinspectrŸÚgetrecursionlimitršr:ÚappendrerWÚformatrÞrÚgetinnerframesÚ __traceback__ÚsetÚ enumerateÚf_localsÚgetrAÚf_codeÚco_nameÚaddrr×) ÚexcÚdepthrër¤ÚcallersÚseenÚiÚffÚfrmÚf_selfÚ self_typeÚcoderrrÚexplain‚sH            zParseException.explainN)râ)rrrràÚ staticmethodrrrrrr<ksc@seZdZdZdS)r>znuser-throwable exception thrown when inconsistent parse content is found; stops all parsing immediatelyN)rrrràrrrrr>Èsc@seZdZdZdS)r@zîjust like :class:`ParseFatalException`, but thrown internally when an :class:`ErrorStop` ('-' operator) indicates that parsing is to stop immediately because an unbacktrackable syntax error has been found. N)rrrràrrrrr@Ísc@s eZdZdZdd„Zdd„ZdS)rCziexception thrown by :class:`ParserElement.validate` if the grammar could be improperly recursive cCs ||_dS)N)ÚparseElementTrace)rÇÚparseElementListrrrrÉæsz"RecursiveGrammarException.__init__cCs d|jS)NzRecursiveGrammarException: %s)r)rÇrrrrÔész!RecursiveGrammarException.__str__N)rrrràrÉrÔrrrrrCâsc@s,eZdZdd„Zdd„Zdd„Zdd„Zd S) Ú_ParseResultsWithOffsetcCs||f|_dS)N)Útup)rÇÚp1Úp2rrrrÉísz _ParseResultsWithOffset.__init__cCs |j|S)N)r)rÇrürrrÚ __getitem__ïsz#_ParseResultsWithOffset.__getitem__cCst|jdƒS)Nr)Úreprr)rÇrrrrÕñsz _ParseResultsWithOffset.__repr__cCs|jd|f|_dS)Nr)r)rÇrürrrÚ setOffsetósz!_ParseResultsWithOffset.setOffsetN)rrrrÉr rÕr rrrrrìsrc@sªeZdZdZd]dd„Zddddefdd„Zdd „Zefd d „Zd d „Z dd„Z dd„Z dd„Z e Z dd„Zdd„Zdd„Zdd„Zdd„ZerœeZeZeZn$eZeZeZdd„Zd d!„Zd"d#„Zd$d%„Zd&d'„Zd^d(d)„Zd*d+„Zd,d-„Zd.d/„Zd0d1„Z d2d3„Z!d4d5„Z"d6d7„Z#d8d9„Z$d:d;„Z%d`` - see :class:`ParserElement.setResultsName`) Example:: integer = Word(nums) date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: # date_str = integer("year") + '/' + integer("month") + '/' + integer("day") # parseString returns a ParseResults object result = date_str.parseString("1999/12/31") def test(s, fn=repr): print("%s -> %s" % (s, fn(eval(s)))) test("list(result)") test("result[0]") test("result['month']") test("result.day") test("'month' in result") test("'minutes' in result") test("result.dump()", str) prints:: list(result) -> ['1999', '/', '12', '/', '31'] result[0] -> '1999' result['month'] -> '12' result.day -> '31' 'month' in result -> True 'minutes' in result -> False result.dump() -> ['1999', '/', '12', '/', '31'] - day: 31 - month: 12 - year: 1999 NTcCs"t||ƒr|Stj|ƒ}d|_|S)NT)ršÚobjectÚ__new__Ú_ParseResults__doinit)rÊÚtoklistÚnameÚasListÚmodalÚretobjrrrr!s   zParseResults.__new__c Csb|jrvd|_d|_d|_i|_||_||_|dkr6g}||tƒrP|dd…|_n||tƒrft|ƒ|_n|g|_t ƒ|_ |dk o€|�r^|s’d|j|<||t ƒr¤t |ƒ}||_||t dƒttfƒoÊ|ddgfk�s^||tƒrÞ|g}|�r(||tƒ�rtt|jƒdƒ||<ntt|dƒdƒ||<|||_n6y|d||<Wn$tttfk �r\|||<YnXdS)NFrr¶)rÚ_ParseResults__nameÚ_ParseResults__parentÚ_ParseResults__accumNamesÚ_ParseResults__asListÚ_ParseResults__modalÚlistÚ_ParseResults__toklistÚ_generatorTypeÚdictÚ_ParseResults__tokdictr—r¥rÞÚ basestringr?rÚKeyErrorÚ TypeErrorÚ IndexError)rÇrrrrršrrrrÉ*sB     $   zParseResults.__init__cCsPt|ttfƒr|j|S||jkr4|j|ddStdd„|j|DƒƒSdS)Nr”rcSsg|] }|d‘qS)rr)rÚvrrrrXsz,ParseResults.__getitem__..r•)ršr—Úslicerrrr?)rÇrürrrr Qs   zParseResults.__getitem__cCsŒ||tƒr0|jj|tƒƒ|g|j|<|d}nD||ttfƒrN||j|<|}n&|jj|tƒƒt|dƒg|j|<|}||tƒrˆt|ƒ|_ dS)Nr) rrrôrr—r$rr?Úwkrefr)rÇÚkr#ršÚsubrrrÚ __setitem__Zs   " zParseResults.__setitem__c CsÆt|ttfƒrºt|jƒ}|j|=t|tƒrH|dkr:||7}t||dƒ}tt|j|ƒŽƒ}|jƒx^|j j ƒD]F\}}x<|D]4}x.t |ƒD]"\}\}} t || | |kƒ||<qŠWq|WqnWn|j |=dS)Nrr”) ršr—r$rÒrrÚrangeÚindicesÚreverserÚitemsròr) rÇrüÚmylenÚremovedrÚ occurrencesÚjr&ÚvalueÚpositionrrrÚ __delitem__gs   $zParseResults.__delitem__cCs ||jkS)N)r)rÇr&rrrÚ __contains__|szParseResults.__contains__cCs t|jƒS)N)rÒr)rÇrrrÚ__len__szParseResults.__len__cCs |j S)N)r)rÇrrrÚ__bool__‚szParseResults.__bool__cCs t|jƒS)N)Úiterr)rÇrrrÚ__iter__†szParseResults.__iter__cCst|jddd…ƒS)Nr”r•)r7r)rÇrrrÚ __reversed__‰szParseResults.__reversed__cCs$t|jdƒr|jjƒSt|jƒSdS)NÚiterkeys)Úhasattrrr:r7)rÇrrrÚ _iterkeysŒs  zParseResults._iterkeyscs‡fdd„ˆjƒDƒS)Nc3s|]}ˆ|VqdS)Nr)rr&)rÇrrr§“sz+ParseResults._itervalues..)r<)rÇr)rÇrÚ _itervalues’szParseResults._itervaluescs‡fdd„ˆjƒDƒS)Nc3s|]}|ˆ|fVqdS)Nr)rr&)rÇrrr§–sz*ParseResults._iteritems..)r<)rÇr)rÇrÚ _iteritems•szParseResults._iteritemscCs t|jƒƒS)zVReturns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x).)rr:)rÇrrrÚkeys¬szParseResults.keyscCs t|jƒƒS)zXReturns all named result values (as a list in Python 2.x, as an iterator in Python 3.x).)rÚ itervalues)rÇrrrÚvalues°szParseResults.valuescCs t|jƒƒS)zfReturns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x).)rÚ iteritems)rÇrrrr,´szParseResults.itemscCs t|jƒS)z�Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.)rºr)rÇrrrÚhaskeys¸szParseResults.haskeyscOs’|s dg}x6|jƒD]*\}}|dkr2|d|f}qtd|ƒ‚qWt|dtƒsht|ƒdksh|d|kr‚|d}||}||=|S|d}|SdS)aÁ Removes and returns item at specified index (default= ``last``). Supports both ``list`` and ``dict`` semantics for ``pop()``. If passed no argument or an integer argument, it will use ``list`` semantics and pop tokens from the list of parsed tokens. If passed a non-integer argument (most likely a string), it will use ``dict`` semantics and pop the corresponding value from any defined results names. A second default return value argument is supported, just as in ``dict.pop()``. Example:: def remove_first(tokens): tokens.pop(0) print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321'] label = Word(alphas) patt = label("LABEL") + OneOrMore(Word(nums)) print(patt.parseString("AAB 123 321").dump()) # Use pop() in a parse action to remove named result (note that corresponding value is not # removed from list form of results) def remove_LABEL(tokens): tokens.pop("LABEL") return tokens patt.addParseAction(remove_LABEL) print(patt.parseString("AAB 123 321").dump()) prints:: ['AAB', '123', '321'] - LABEL: AAB ['AAB', '123', '321'] r”Údefaultrz-pop() got an unexpected keyword argument '%s'Nr•)r,r!ršr—rÒ)rÇrÆÚkwargsr&r#Úindexr¤Ú defaultvaluerrrÚpop½s%  zParseResults.popcCs||kr||S|SdS)a[ Returns named result matching the given key, or if there is no such name, then returns the given ``defaultValue`` or ``None`` if no ``defaultValue`` is specified. Similar to ``dict.get()``. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString("1999/12/31") print(result.get("year")) # -> '1999' print(result.get("hour", "not specified")) # -> 'not specified' print(result.get("hour")) # -> None Nr)rÇÚkeyÚ defaultValuerrrrôôszParseResults.getcCsZ|jj||ƒxF|jjƒD]8\}}x.t|ƒD]"\}\}}t||||kƒ||<q,WqWdS)a Inserts new element at location index in the list of parsed tokens. Similar to ``list.insert()``. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to insert the parse location in the front of the parsed results def insert_locn(locn, tokens): tokens.insert(0, locn) print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321'] N)rÚinsertrr,ròr)rÇrFÚinsStrrr/r&r1r2rrrrK szParseResults.insertcCs|jj|ƒdS)aó Add single element to end of ParseResults list of elements. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to compute the sum of the parsed integers, and add it to the end def append_sum(tokens): tokens.append(sum(map(int, tokens))) print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444] N)rrí)rÇÚitemrrrrí s zParseResults.appendcCs&t|tƒr|j|ƒn |jj|ƒdS)a  Add sequence of elements to end of ParseResults list of elements. Example:: patt = OneOrMore(Word(alphas)) # use a parse action to append the reverse of the matched strings, to make a palindrome def make_palindrome(tokens): tokens.extend(reversed([t[::-1] for t in tokens])) return ''.join(tokens) print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl' N)ršr?Ú__iadd__rÚextend)rÇÚitemseqrrrrO/s  zParseResults.extendcCs|jdd…=|jjƒdS)z7 Clear all elements and results names. N)rrÚclear)rÇrrrrQBs zParseResults.clearc Cs"y||Stk rdSXdS)Nr¶)r )rÇrrrrrÐIszParseResults.__getattr__cCs|jƒ}||7}|S)N)Úcopy)rÇÚotherr¤rrrÚ__add__OszParseResults.__add__cs�|jrnt|jƒ‰‡fdd„‰|jjƒ}‡fdd„|Dƒ}x4|D],\}}|||<t|dtƒr>t|ƒ|d_q>W|j|j7_|jj |jƒ|S)Ncs|dkr ˆS|ˆS)Nrr)Úa)Úoffsetrrr™Wsz'ParseResults.__iadd__..c s4g|],\}}|D]}|t|dˆ|dƒƒf‘qqS)rr”)r)rr&Úvlistr#)Ú addoffsetrrrYsz)ParseResults.__iadd__..r) rrÒrr,ršr?r%rrÚupdate)rÇrSÚ otheritemsÚotherdictitemsr&r#r)rXrVrrNTs    zParseResults.__iadd__cCs&t|tƒr|dkr|jƒS||SdS)Nr)ršr—rR)rÇrSrrrÚ__radd__dszParseResults.__radd__cCsdt|jƒt|jƒfS)Nz(%s, %s))r rr)rÇrrrrÕlszParseResults.__repr__cCsddjdd„|jDƒƒdS)Nú[z, css(|] }t|tƒrt|ƒnt|ƒVqdS)N)ršr?r¥r )rrürrrr§psz'ParseResults.__str__..ú])r×r)rÇrrrrÔoszParseResults.__str__r¶cCsPg}xF|jD]<}|r"|r"|j|ƒt|tƒr:||jƒ7}q |jt|ƒƒq W|S)N)rríršr?Ú _asStringListr¥)rÇÚsepÚoutrMrrrr_rs   zParseResults._asStringListcCsdd„|jDƒS)ax Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is actually a pyparsing ParseResults print(type(result), result) # -> ['sldkj', 'lsdkj', 'sldkj'] # Use asList() to create an actual list result_list = result.asList() print(type(result_list), result_list) # -> ['sldkj', 'lsdkj', 'sldkj'] cSs"g|]}t|tƒr|jƒn|‘qSr)ršr?r)rÚresrrrrŒsz'ParseResults.asList..)r)rÇrrrr}szParseResults.asListcs6tr |j}n|j}‡fdd„‰t‡fdd„|ƒDƒƒS)a¬ Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(type(result), repr(result)) # -> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) result_dict = result.asDict() print(type(result_dict), repr(result_dict)) # -> {'day': '1999', 'year': '12', 'month': '31'} # even though a ParseResults supports dict-like access, sometime you just need to have a dict import json print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"} cs6t|tƒr.|jƒr|jƒS‡fdd„|DƒSn|SdS)Ncsg|] }ˆ|ƒ‘qSrr)rr#)ÚtoItemrrr¬sz7ParseResults.asDict..toItem..)ršr?rCÚasDict)r£)rcrrrc§s  z#ParseResults.asDict..toItemc3s|]\}}|ˆ|ƒfVqdS)Nr)rr&r#)rcrrr§°sz&ParseResults.asDict..)ÚPY_3r,rBr)rÇÚitem_fnr)rcrrdŽs  zParseResults.asDictcCs<t|jƒ}t|jjƒƒ|_|j|_|jj|jƒ|j|_|S)zG Returns a new copy of a :class:`ParseResults` object. ) r?rrrr,rrrYr)rÇr¤rrrrR²s  zParseResults.copyFc CsPd}g}tdd„|jjƒDƒƒ}|d}|s8d}d}d}d} |dk rJ|} n |jrV|j} | sf|rbdSd} |||d| d g7}xºt|jƒD]¬\} } t| tƒrâ| |krÂ|| j|| |o´|dk||ƒg7}n|| jd|oÔ|dk||ƒg7}q„d} | |krö|| } | �s |�rq„nd} t t | ƒƒ} |||d| d | d | d g 7}q„W|||d | d g7}dj |ƒS) z‡ (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names. rêcss(|] \}}|D]}|d|fVqqdS)r”Nr)rr&rWr#rrrr§Ãsz%ParseResults.asXML..z r¶NÚITEMú<ú>z.z %s%s- %s: z r”)rmÚfullÚ include_listÚ_depthcss|]}t|tƒVqdS)N)ršr?)rÚvvrrrr§Ssz %s%s[%d]: %s%s%s) rír¥rrCÚsortedr,ršr?Údumpr Úanyròr×) rÇrmrzr{r|raÚNLr,r&r#rür}rrrr)sJ      zParseResults.dumpcOstj|jƒf|ž|ŽdS)a# Pretty-printer for parsed results as a list, using the `pprint `_ module. Accepts additional positional or keyword args as defined for `pprint.pprint `_ . Example:: ident = Word(alphas, alphanums) num = Word(nums) func = Forward() term = ident | num | Group('(' + func + ')') func <<= ident + Group(Optional(delimitedList(term))) result = func.parseString("fna a,b,(fnb c,d,200),100") result.pprint(width=40) prints:: ['fna', ['a', 'b', ['(', 'fnb', ['c', 'd', '200'], ')'], '100']] N)Úpprintr)rÇrÆrErrrr‚jszParseResults.pprintcCs.|j|jjƒ|jdk r|jƒp d|j|jffS)N)rrrRrrr)rÇrrrÚ __getstate__†s zParseResults.__getstate__cCsN|d|_|d\|_}}|_i|_|jj|ƒ|dk rDt|ƒ|_nd|_dS)Nrr”)rrrrrYr%r)rÇÚstaterxÚ inAccumNamesrrrÚ __setstate__�s   zParseResults.__setstate__cCs|j|j|j|jfS)N)rrrr)rÇrrrÚ__getnewargs__—szParseResults.__getnewargs__cCstt|ƒƒt|jƒƒS)N)rÝrÞrr?)rÇrrrrßšszParseResults.__dir__cCsvdd„}|gƒ}xJ|jƒD]>\}}t|tƒr@||j||d�7}q|||g|||ƒd�7}qW|dk rr||g|d�}|S)zã Helper classmethod to construct a ParseResults from a dict, preserving the name-value relations as results names. If an optional 'name' argument is given, a nested ParseResults will be returned c SsFy t|ƒWntk r dSXtr6t|ttfƒ St|tƒ SdS)NF)r7Ú ExceptionreršrœÚbytesr)r£rrrÚ is_iterable¤s z+ParseResults.from_dict..is_iterable)r)rrN)r,ršr Ú from_dict)rÊrSrrŠr¤r&r#rrrr‹�s  zParseResults.from_dict)NNTT)N)r¶)NFr¶T)r¶TTr)N)6rrrràrršrÉr r(r3r4r5r6Ú __nonzero__r8r9r<r=r>rer?rAr,r:r@rBrCrHrôrKrírOrQrÐrTrNr\rÕrÔr_rrdrRrjrvryrr‚rƒr†r‡rßrár‹rrrrr?ösl* ' 7  $ =( A cCsF|}d|kot|ƒknr4||ddkr4dS||jdd|ƒS)añReturns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See :class:`ParserElement.parseString` for more information on parsing strings containing ```` s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. rr”rê)rÒÚrfind)rÃÚstrgrªrrrrW»s cCs|jdd|ƒdS)aùReturns current line number within a string, counting newlines as line separators. The first line is number 1. Note - the default parsing behavior is to expand tabs in the input string before starting the parsing process. See :class:`ParserElement.parseString` for more information on parsing strings containing ```` s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. rêrr”)Úcount)rÃrŽrrrrhÉs cCsF|jdd|ƒ}|jd|ƒ}|dkr2||d|…S||dd…SdS)zfReturns the line of text containing loc within a string, counting newlines as line separators. rêrr”N)r�Úfind)rÃrŽÚlastCRÚnextCRrrrreÕs  cCs8tdt|ƒdt|ƒdt||ƒt||ƒfƒdS)NzMatch z at loc z(%d,%d))Úprintr¥rhrW)ÚinstringrÃÚexprrrrÚ_defaultStartDebugActionßsr–cCs$tdt|ƒdt|jƒƒƒdS)NzMatched z -> )r“r¥rœr)r”ÚstartlocÚendlocr•ÚtoksrrrÚ_defaultSuccessDebugActionâsršcCstdt|ƒƒdS)NzException raised:)r“r¥)r”rÃr•rørrrÚ_defaultExceptionDebugActionåsr›cGsdS)zG'Do-nothing' debug action, to suppress debugging output during parsing.Nr)rÆrrrroèsr“c sÒˆtkr‡fdd„Sdg‰dg‰tdd…dkrFddd „}dd d „‰n tj}tj‰d }|dd �d}|d|d|f‰‡‡‡‡‡‡fdd„}d}ytˆdtˆdƒjƒ}Wntk rÆtˆƒ}YnX||_|S)Ncsˆ|ƒS)Nr)rªr»r˜)Úfuncrrr™sz_trim_arity..rFr“r‘écSs8tdkr dnd }tj| |dd�|}|dd…gS) Nr‘r�rr“r”)Úlimit)r‘r�réýÿÿÿéþÿÿÿ)Úsystem_versionÚ tracebackÚ extract_stack)ržrVÚ frame_summaryrrrr£ sz"_trim_arity..extract_stackcSs$tj||d�}|d}|dd…gS)N)ržr”r“r•)r¢Ú extract_tb)ÚtbržÚframesr¤rrrr¥sz_trim_arity..extract_tbé)ržr”csºx´y ˆ|ˆdd…Ž}dˆd<|Stk r°ˆdr>‚nNz.tjƒd}ˆ|dd�ddd…ˆksj‚Wdy~Wntk rˆYnXXˆdˆkrªˆdd7<w‚YqXqWdS)NrTr”r“)ržr•r•)r!rŸÚexc_infoÚ NameError)rÆr¤r¦)r¥Ú foundArityrœržÚmaxargsÚpa_call_line_synthrrrè!s(  z_trim_arity..wrapperzrÚ __class__)r‘r�)r)rr•) ÚsingleArgBuiltinsr¡r¢r£r¥Úgetattrrrˆrœ)rœr¬r£Ú LINE_DIFFÚ this_linerèÚ func_namer)r¥r«rœržr¬r­rrÀs*   rÀc@s°eZdZdZdZdZedd„ƒZedd„ƒZe dd „ƒZ dŽd d „Z d d „Z dd„Z d�dd„Zd�dd„Zd‘dd„Zdd„Zdd„Zdd„Zdd„Zdd „Zd!d"„Zd’d#d$„Zd%d&„Zd“d'd(„Zd)d*„Zd+d,„ZGd-d.„d.eƒZed/k �røGd0d1„d1eƒZnGd2d1„d1eƒZiZ e!ƒZ"d3d3gZ#d”d4d5„Z$eZ%ed6d7„ƒZ&dZ'ed•d9d:„ƒZ(d–d;d<„Z)e*dfd=d>„Z+d?d@„Z,e*fdAdB„Z-e*dfdCdD„Z.dEdF„Z/dGdH„Z0dIdJ„Z1dKdL„Z2dMdN„Z3dOdP„Z4dQdR„Z5dSdT„Z6dUdV„Z7dWdX„Z8dYdZ„Z9d[d\„Z:d]d^„Z;d_d`„Zdedf„Z?dgdh„Z@didj„ZAdkdl„ZBdmdn„ZCdodp„ZDd˜dqdr„ZEdsdt„ZFdudv„ZGdwdx„ZHdydz„ZId™d{d|„ZJdšd}d~„ZKdd€„ZLd�d‚„ZMdƒd„„ZNd…d†„ZOd‡dˆ„ZPd›d‰dŠ„ZQdœdŒd�„ZRd/S)�rAz)Abstract base level parser element class.z FcCs |t_dS)aÆ Overrides the default whitespace chars Example:: # default whitespace chars are space, and newline OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] # change to just treat newline as significant ParserElement.setDefaultWhitespaceChars(" \t") OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def'] N)rAÚDEFAULT_WHITE_CHARS)ÚcharsrrrÚsetDefaultWhitespaceCharsLsz'ParserElement.setDefaultWhitespaceCharscCs |t_dS)ah Set class to be used for inclusion of string literals into a parser. Example:: # default literal class used is Literal integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # change to Suppress ParserElement.inlineLiteralsUsing(Suppress) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # -> ['1999', '12', '31'] N)rAÚ_literalStringClass)rÊrrrÚinlineLiteralsUsing\sz!ParserElement.inlineLiteralsUsingcCsx|jr|j}qW|S)N)Útb_next)rÊr¦rrrÚ_trim_tracebackrs zParserElement._trim_tracebackcCs†tƒ|_d|_d|_d|_||_d|_ttj ƒ|_ d|_ d|_ d|_ tƒ|_d|_d|_d|_d|_d|_d|_d|_d|_d|_dS)NTFr¶)NNN)rÚ parseActionÚ failActionÚstrReprÚ resultsNameÚ saveAsListÚskipWhitespacerñrAr´Ú whiteCharsÚcopyDefaultWhiteCharsÚmayReturnEmptyÚkeepTabsÚ ignoreExprsÚdebugÚ streamlinedÚ mayIndexErrorÚerrmsgÚ modalResultsÚ debugActionsr�Ú callPreparseÚ callDuringTry)rÇÚsavelistrrrrÉxs( zParserElement.__init__cCs<tj|ƒ}|jdd…|_|jdd…|_|jr8tj|_|S)a/ Make a copy of this :class:`ParserElement`. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element. Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) integerK = integer.copy().addParseAction(lambda toks: toks[0] * 1024) + Suppress("K") integerM = integer.copy().addParseAction(lambda toks: toks[0] * 1024 * 1024) + Suppress("M") print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M")) prints:: [5120, 100, 655360, 268435456] Equivalent form of ``expr.copy()`` is just ``expr()``:: integerM = integer().addParseAction(lambda toks: toks[0] * 1024 * 1024) + Suppress("M") N)rRr»rÅrÂrAr´rÁ)rÇÚcpyrrrrR�s  zParserElement.copycCs$||_d|j|_tjr |jƒ|S)a_ Define name for this expression, makes debugging and exception messages clearer. Example:: Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1) z Expected )rrÉrÚ!enable_debug_on_named_expressionsÚsetDebug)rÇrrrrÚsetName¬s  zParserElement.setNamecCs |j||ƒS)aO Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original :class:`ParserElement` object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. You can also set results names using the abbreviated syntax, ``expr("name")`` in place of ``expr.setResultsName("name")`` - see :class:`__call__`. Example:: date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: date_str = integer("year") + '/' + integer("month") + '/' + integer("day") )Ú_setResultsName)rÇrÚlistAllMatchesrrrÚsetResultsName»szParserElement.setResultsNamecCs4|jƒ}|jdƒr"|dd…}d}||_| |_|S)NÚ*r”Tr•)rRÚendswithr¾rÊ)rÇrrÔÚnewselfrrrrÓÒs  zParserElement._setResultsNameTcs@|r&|j‰d‡fdd„ }ˆ|_||_nt|jdƒr<|jj|_|S)z§Method to invoke the Python pdb debugger when this element is about to be parsed. Set ``breakFlag`` to True to enable, False to disable. Tcsddl}|jƒˆ||||ƒS)Nr)ÚpdbÚ set_trace)r”rÃÚ doActionsÚ callPreParserÙ)Ú _parseMethodrrÚbreakerâsz'ParserElement.setBreak..breakerÚ_originalParseMethod)TT)Ú_parserßr;)rÇÚ breakFlagrÞr)rÝrÚsetBreakÛs  zParserElement.setBreakcOsVt|ƒdgkrg|_n`` s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. Example:: integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31] Ncss|]}t|ƒVqdS)N)Úcallable)rr½rrrr§sz/ParserElement.setParseAction..zparse actions must be callablerÍF)rr»Úallr!ÚmaprÀrôrÍ)rÇÚfnsrErrrr¡îs(zParserElement.setParseActioncOs4|jtttt|ƒƒƒ7_|jp,|jddƒ|_|S)z› Add one or more parse actions to expression's list of parse actions. See :class:`setParseAction`. See examples in :class:`copy`. rÍF)r»rrårÀrÍrô)rÇrærErrrÚaddParseActionszParserElement.addParseActioncOsJx0|D](}|jjt||jdƒ|jddƒd�ƒqW|jpB|jddƒ|_|S)a¼Add a boolean predicate function to expression's list of parse actions. See :class:`setParseAction` for function call signatures. Unlike ``setParseAction``, functions passed to ``addCondition`` need to return boolean success/fail of the condition. Optional keyword arguments: - message = define a custom message to be used in the raised exception - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) year_int = integer.copy() year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") date_str = year_int + '/' + integer + '/' + integer result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1) rÁrÂF)rÁrÂrÍ)r»rír�rôrÍ)rÇrærEr½rrrÚ addCondition)s  zParserElement.addConditioncCs ||_|S)aDefine action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments ``fn(s, loc, expr, err)`` where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The function returns no value. It may throw :class:`ParseFatalException` if it is desired to stop parsing immediately.)r¼)rÇr½rrrÚ setFailActionBs zParserElement.setFailActionc CsZd}xP|rTd}xB|jD]8}yx|j||ƒ\}}d}qWWqtk rLYqXqWqW|S)NTF)rÅràr<)rÇr”rÃÚ exprsFoundÚeÚdummyrrrÚ_skipIgnorablesOs  zParserElement._skipIgnorablescCsL|jr|j||ƒ}|jrH|j}t|ƒ}x ||krF|||krF|d7}q(W|S)Nr”)rÅrírÀrÁrÒ)rÇr”rÃÚwtÚinstrlenrrrÚpreParse\s  zParserElement.preParsecCs|gfS)Nr)rÇr”rÃrÛrrrræhszParserElement.parseImplcCs|S)Nr)rÇr”rÃÚ tokenlistrrrÚ postParsekszParserElement.postParsec*Cs˜d\}}}|j}|s|j�r"|j|r8|j||||ƒyŠ|rR|jrR|j||ƒ} n|} | } |jsl| t|ƒkr®y|j|| |ƒ\}} WqÀtk rªt |t|ƒ|j |ƒ‚YqÀXn|j|| |ƒ\}} Wn\t k �r} z>|j|rô|j||| || ƒ|j�r |j|| || ƒ‚WYdd} ~ XnXn�|�r>|j�r>|j||ƒ} n|} | } |j�s\| t|ƒk�r y|j|| |ƒ\}} Wn*tk �rœt |t|ƒ|j |ƒ‚YnXn|j|| |ƒ\}} |j ||| ƒ} t | |j|j|jd�} |j�rh|�sì|j�rh|�rÔy˜x’|jD]ˆ}y||| | ƒ} Wn6tk �rF}zt dƒ}||_|‚WYdd}~XnX| dk �rü| | k �rüt | |j|j�oxt| t tfƒ|jd�} �qüWWnFt k �rÐ} z(|j|�r¾|j||| || ƒ‚WYdd} ~ XnXn”x’|jD]ˆ}y||| | ƒ} Wn6tk �r&}zt dƒ}||_|‚WYdd}~XnX| dk �rÜ| | k �rÜt | |j|j�oXt| t tfƒ|jd�} �qÜW|�r�|j|�r�|j||| ||| ƒ|| fS)Nrr”r“)rrz exception raised in parse action)rr”r“)rÆr¼rËrÌrðrÈrÒrær"r<rÉrˆròr?r¾r¿rÊr»rÍÚ __cause__ršr)rÇr”rÃrÛrÜÚTRYÚMATCHÚFAILÚ debuggingÚprelocÚ tokensStartÚtokensÚerrÚ retTokensr½Úparse_action_excrørrrrçosŠ         zParserElement._parseNoCachec Cs>y|j||dd�dStk r8t|||j|ƒ‚YnXdS)NF)rÛr)ràr>r<rÉ)rÇr”rÃrrrÚtryParseÆszParserElement.tryParsec Cs2y|j||ƒWnttfk r(dSXdSdS)NFT)rþr<r")rÇr”rÃrrrÚ canParseNextÌs zParserElement.canParseNextc@seZdZdd„ZdS)zParserElement._UnboundedCachecs~i‰tƒ|_‰‡‡fdd„}‡fdd„}‡fdd„}‡fdd„}tj||ƒ|_tj||ƒ|_tj||ƒ|_tj||ƒ|_dS) Ncs ˆj|ˆƒS)N)rô)rÇrI)ÚcacheÚ not_in_cacherrrôÙsz3ParserElement._UnboundedCache.__init__..getcs |ˆ|<dS)Nr)rÇrIr1)rrrrñÜsz3ParserElement._UnboundedCache.__init__..setcs ˆjƒdS)N)rQ)rÇ)rrrrQßsz5ParserElement._UnboundedCache.__init__..clearcstˆƒS)N)rÒ)rÇ)rrrÚ cache_lenâsz9ParserElement._UnboundedCache.__init__..cache_len)r rÚtypesÚ MethodTyperôrñrQr5)rÇrôrñrQrr)rrrrÉÕs    z&ParserElement._UnboundedCache.__init__N)rrrrÉrrrrÚ_UnboundedCacheÔsrNc@seZdZdd„ZdS)zParserElement._FifoCachecs‚tƒ|_‰tƒ‰‡‡fdd„}‡‡fdd„}‡fdd„}‡fdd„}tj||ƒ|_tj||ƒ|_tj||ƒ|_tj||ƒ|_dS) Ncs ˆj|ˆƒS)N)rô)rÇrI)rrrrrôñsz.ParserElement._FifoCache.__init__..getc sB|ˆ|<x4tˆƒˆkr.setcs ˆjƒdS)N)rQ)rÇ)rrrrQüsz0ParserElement._FifoCache.__init__..clearcstˆƒS)N)rÒ)rÇ)rrrrÿsz4ParserElement._FifoCache.__init__..cache_len) r rÚ _OrderedDictrrrôrñrQr5)rÇrrôrñrQrr)rrrrrÉìs   z!ParserElement._FifoCache.__init__N)rrrrÉrrrrÚ _FifoCacheësr c@seZdZdd„ZdS)zParserElement._FifoCachecs�tƒ|_‰i‰tjgˆƒ‰‡‡fdd„}‡‡‡fdd„}‡‡fdd„}‡fdd„}tj||ƒ|_tj||ƒ|_tj||ƒ|_tj||ƒ|_ dS) Ncs ˆj|ˆƒS)N)rô)rÇrI)rrrrrôsz.ParserElement._FifoCache.__init__..getcs8|ˆ|<x tˆƒˆkr(ˆjˆjƒdƒq Wˆj|ƒdS)N)rÒrHÚpopleftrí)rÇrIr1)rÚkey_fiforrrrñsz.ParserElement._FifoCache.__init__..setcsˆjƒˆjƒdS)N)rQ)rÇ)rr rrrQsz0ParserElement._FifoCache.__init__..clearcstˆƒS)N)rÒ)rÇ)rrrrsz4ParserElement._FifoCache.__init__..cache_len) r rÚ collectionsÚdequerrrôrñrQr5)rÇrrôrñrQrr)rr rrrrÉ s   z!ParserElement._FifoCache.__init__N)rrrrÉrrrrr src Csüd\}}|||||f}tj�Ötj}|j|ƒ} | |jkrºtj|d7<y|j||||ƒ} Wn8tk r–} z|j|| j | j Žƒ‚WYdd} ~ XqîX|j|| d| dj ƒfƒ| Sn4tj|d7<t | t ƒrÚ| ‚| d| dj ƒfSWdQRXdS)Nrr”)rr”)rAÚpackrat_cache_lockÚ packrat_cacherôrÚpackrat_cache_statsrçr:rñr®rÆrRršrˆ) rÇr”rÃrÛrÜÚHITÚMISSÚlookuprr1rËrrrÚ _parseCache+s$   zParserElement._parseCachecCs(tjjƒdgttjƒtjdd…<dS)Nr)rArrQrÒrrrrrÚ resetCacheDs zParserElement.resetCacheé€cCs8tjs4dt_|dkr tjƒt_n tj|ƒt_tjt_dS)aÒEnables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions. Parameters: - cache_size_limit - (default= ``128``) - if an integer value is provided will limit the size of the packrat cache; if None is passed, then the cache size will be unbounded; if 0 is passed, the cache will be effectively disabled. This speedup may break existing programs that use parse actions that have side-effects. For this reason, packrat parsing is disabled when you first import pyparsing. To activate the packrat feature, your program must call the class method :class:`ParserElement.enablePackrat`. For best results, call ``enablePackrat()`` immediately after importing pyparsing. Example:: from pip._vendor import pyparsing pyparsing.ParserElement.enablePackrat() TN)rAÚ_packratEnabledrrr rrà)Úcache_size_limitrrrÚ enablePackratJs   zParserElement.enablePackratcCsÐtjƒ|js|jƒx|jD] }|jƒqW|js<|jƒ}y<|j|dƒ\}}|rv|j||ƒ}t ƒt ƒ}|j||ƒWnNt k rÆ}z2tj r”‚n"t |ddƒdk r²|j|jƒ|_|‚WYdd}~XnX|SdS)aû Execute the parse expression with the given string. This is the main interface to the client code, once the complete expression has been built. Returns the parsed data as a :class:`ParseResults` object, which may be accessed as a list, or as a dict or object with attributes if the given parser includes results names. If you want the grammar to require that the entire input string be successfully parsed, then set ``parseAll`` to True (equivalent to ending the grammar with ``StringEnd()``). Note: ``parseString`` implicitly calls ``expandtabs()`` on the input string, in order to report proper column numbers in parse actions. If the input string contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string being parsed, you can ensure you have a consistent view of the input string by: - calling ``parseWithTabs`` on your grammar before calling ``parseString`` (see :class:`parseWithTabs`) - define your parse action using the full ``(s, loc, toks)`` signature, and reference the input string using the parse action's ``s`` argument - explictly expand the tabs in your input string before calling ``parseString`` Example:: Word('a').parseString('aaaaabaaa') # -> ['aaaaa'] Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text rrðN)rArrÇÚ streamlinerÅrÄÚ expandtabsràrðr)rFr:Úverbose_stacktracer°rºrð)rÇr”ÚparseAllrërÃrúÚserørrrÚ parseStringms(!    zParserElement.parseStringccs`|js|jƒx|jD] }|jƒqW|js8t|ƒjƒ}t|ƒ}d}|j}|j}t j ƒd} yªx¤||kon| |k�ry |||ƒ} ||| dd�\} } Wnt k r®| d}Yq`X| |krø| d7} | | | fV|rò|||ƒ} | |krè| }qö|d7}n| }q`| d}q`WWnTt k �rZ}z6t j �r&‚n$t|ddƒdk �rF|j|jƒ|_|‚WYdd}~XnXdS)aq Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional ``maxMatches`` argument, to clip scanning after 'n' matches are found. If ``overlap`` is specified, then overlapping matches will be reported. Note that the start and end locations are reported relative to the string being parsed. See :class:`parseString` for more information on parsing strings with embedded tabs. Example:: source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" print(source) for tokens, start, end in Word(alphas).scanString(source): print(' '*start + '^'*(end-start)) print(' '*start + tokens[0]) prints:: sldjf123lsdjjkf345sldkjf879lkjsfd987 ^^^^^ sldjf ^^^^^^^ lsdjjkf ^^^^^^ sldkjf ^^^^^^ lkjsfd rF)rÜr”rðN)rÇrrÅrÄr¥rrÒrðràrArr<r:rr°rºrð)rÇr”Ú maxMatchesÚoverlaprërïrÃÚ preparseFnÚparseFnÚmatchesrøÚnextLocrúÚnextlocrørrrÚ scanString§sF       zParserElement.scanStringcCsg}d}d|_yžxh|j|ƒD]Z\}}}|j|||…ƒ|rrt|tƒrT||jƒ7}nt|tƒrh||7}n |j|ƒ|}qW|j||d…ƒdd„|Dƒ}djtt t |ƒƒƒSt k rú}z2t j rÈ‚n"t|ddƒdk ræ|j|jƒ|_|‚WYdd}~XnXdS)a[ Extension to :class:`scanString`, to modify matching text with modified tokens that may be returned from a parse action. To use ``transformString``, define a grammar and attach a parse action to it that modifies the returned token list. Invoking ``transformString()`` on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. ``transformString()`` returns the resulting transformed string. Example:: wd = Word(alphas) wd.setParseAction(lambda toks: toks[0].title()) print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. rTNcSsg|] }|r|‘qSrr)rÚorrrrsz1ParserElement.transformString..r¶rð)rÄr'ríršr?rrr×rår¥Ú_flattenr:rArr°rºrð)rÇr”raÚlastEr˜rªrërørrrr¢ñs,    zParserElement.transformStringcCsnytdd„|j||ƒDƒƒStk rh}z2tjr6‚n"t|ddƒdk rT|j|jƒ|_|‚WYdd}~XnXdS)a  Another extension to :class:`scanString`, simplifying the access to the tokens found to match the given parse expression. May be called with optional ``maxMatches`` argument, to clip searching after 'n' matches are found. Example:: # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters cap_word = Word(alphas.upper(), alphas.lower()) print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")) # the sum() builtin can be used to merge results into a single ParseResults object print(sum(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))) prints:: [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']] ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity'] cSsg|]\}}}|‘qSrr)rr˜rªrërrrr7sz.ParserElement.searchString..rðN)r?r'r:rArr°rºrð)rÇr”r rørrrÚ searchString!szParserElement.searchStringc csXd}d}x<|j||d�D]*\}}}|||…V|r>|dV|}qW||d…VdS)aR Generator method to split a string using the given expression as a separator. May be called with optional ``maxsplit`` argument, to limit the number of splits; and the optional ``includeSeparators`` argument (default= ``False``), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] r)r N)r') rÇr”ÚmaxsplitÚincludeSeparatorsÚsplitsÚlastr˜rªrërrrr«As zParserElement.splitcCsV|tkrt|ƒSt|tƒr$|j|ƒ}t|tƒsJtjdt|ƒt dd�dSt ||gƒS)a[ Implementation of + operator - returns :class:`And`. Adding strings to a ParserElement converts them to :class:`Literal`s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) prints:: Hello, World! -> ['Hello', ',', 'World', '!'] ``...`` may be used as a parse expression as a short form of :class:`SkipTo`. Literal('start') + ... + Literal('end') is equivalent to: Literal('start') + SkipTo('end')("_skipped*") + Literal('end') Note that the skipped text is returned with '_skipped' as a results name, and to support having multiple skips in the same parser, the value returned is a list of all skipped text. z4Cannot combine element of type %s with ParserElementr“)Ú stacklevelN) ÚEllipsisÚ _PendingSkipršrr·rAÚwarningsÚwarnrÞÚ SyntaxWarningr")rÇrSrrrrTZs    zParserElement.__add__cCsZ|tkrt|ƒdƒ|St|tƒr,|j|ƒ}t|tƒsRtjdt|ƒt dd�dS||S)z` Implementation of + operator when left operand is not a :class:`ParserElement` z _skipped*z4Cannot combine element of type %s with ParserElementr“)r0N) r1rEršrr·rAr3r4rÞr5)rÇrSrrrr\€s    zParserElement.__radd__cCsJt|tƒr|j|ƒ}t|tƒs:tjdt|ƒtdd�dS|tj ƒ|S)zT Implementation of - operator, returns :class:`And` with error stop z4Cannot combine element of type %s with ParserElementr“)r0N) ršrr·rAr3r4rÞr5r"Ú _ErrorStop)rÇrSrrrÚ__sub__�s    zParserElement.__sub__cCsBt|tƒr|j|ƒ}t|tƒs:tjdt|ƒtdd�dS||S)z` Implementation of - operator when left operand is not a :class:`ParserElement` z4Cannot combine element of type %s with ParserElementr“)r0N)ršrr·rAr3r4rÞr5)rÇrSrrrÚ__rsub__›s    zParserElement.__rsub__cs|tkrd}n8t|tƒrF|dd…tfkrFd|dd…ddd…}t|tƒr^|d}}�nþt|tƒ�rNtdd„|Dƒƒ}|ddd…}|ddkr¤d|df}t|dtƒo¼|ddk�rþ|ddkrÔtˆƒS|ddkrètˆƒSˆ|dtˆƒSnNt|dtƒ�r0t|dtƒ�r0|\}}||8}ntdt|dƒt|dƒƒ‚ntdt|ƒƒ‚|dk�rntd ƒ‚|dk�r€td ƒ‚||k�o”dkn�r¤td ƒ‚|�rø‡‡fd d „‰|�rî|dk�rÖˆˆ|ƒ}nt ˆg|ƒˆ|ƒ}nˆ|ƒ}n|dk�rˆ}nt ˆg|ƒ}|S)aø Implementation of * operator, allows use of ``expr * 3`` in place of ``expr + expr + expr``. Expressions may also me multiplied by a 2-integer tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples may also include ``None`` as in: - ``expr*(n, None)`` or ``expr*(n, )`` is equivalent to ``expr*n + ZeroOrMore(expr)`` (read as "at least n instances of ``expr``") - ``expr*(None, n)`` is equivalent to ``expr*(0, n)`` (read as "0 to n instances of ``expr``") - ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)`` - ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)`` Note that ``expr*(None, n)`` does not raise an exception if more than n exprs exist in the input stream; that is, ``expr*(None, n)`` does not enforce a maximum number of expr occurrences. If this behavior is desired, then write ``expr*(None, n) + ~expr`` rNr”r“css|]}|tk r|ndVqdS)N)r1)rr(rrrr§Ãsz(ParserElement.__mul__..z8cannot multiply 'ParserElement' and ('%s', '%s') objectsz0cannot multiply 'ParserElement' and '%s' objectsz/cannot multiply ParserElement by negative valuez@second tuple value must be greater or equal to first tuple valuez,cannot multiply ParserElement by 0 or (0, 0)cs(|dkrtˆˆ|dƒƒStˆƒSdS)Nr”)r8)Ún)ÚmakeOptionalListrÇrrr:Þsz/ParserElement.__mul__..makeOptionalList)rN)r)N)NN) r1ršÚtupler—rOr6r!rÞÚ ValueErrorr")rÇrSÚ minElementsÚ optElementsr¤r)r:rÇrÚ__mul__§sN             zParserElement.__mul__cCs |j|ƒS)N)r?)rÇrSrrrÚ__rmul__ñszParserElement.__rmul__cCsZ|tkrt|dd�St|tƒr(|j|ƒ}t|tƒsNtjdt|ƒt dd�dSt ||gƒS)zL Implementation of | operator - returns :class:`MatchFirst` T)Ú must_skipz4Cannot combine element of type %s with ParserElementr“)r0N) r1r2ršrr·rAr3r4rÞr5r3)rÇrSrrrÚ__or__ôs     zParserElement.__or__cCsBt|tƒr|j|ƒ}t|tƒs:tjdt|ƒtdd�dS||BS)z` Implementation of | operator when left operand is not a :class:`ParserElement` z4Cannot combine element of type %s with ParserElementr“)r0N)ršrr·rAr3r4rÞr5)rÇrSrrrÚ__ror__ s    zParserElement.__ror__cCsFt|tƒr|j|ƒ}t|tƒs:tjdt|ƒtdd�dSt||gƒS)zD Implementation of ^ operator - returns :class:`Or` z4Cannot combine element of type %s with ParserElementr“)r0N) ršrr·rAr3r4rÞr5r9)rÇrSrrrÚ__xor__ s    zParserElement.__xor__cCsBt|tƒr|j|ƒ}t|tƒs:tjdt|ƒtdd�dS||AS)z` Implementation of ^ operator when left operand is not a :class:`ParserElement` z4Cannot combine element of type %s with ParserElementr“)r0N)ršrr·rAr3r4rÞr5)rÇrSrrrÚ__rxor__ s    zParserElement.__rxor__cCsFt|tƒr|j|ƒ}t|tƒs:tjdt|ƒtdd�dSt||gƒS)zF Implementation of & operator - returns :class:`Each` z4Cannot combine element of type %s with ParserElementr“)r0N) ršrr·rAr3r4rÞr5r()rÇrSrrrÚ__and__' s    zParserElement.__and__cCsBt|tƒr|j|ƒ}t|tƒs:tjdt|ƒtdd�dS||@S)z` Implementation of & operator when left operand is not a :class:`ParserElement` z4Cannot combine element of type %s with ParserElementr“)r0N)ršrr·rAr3r4rÞr5)rÇrSrrrÚ__rand__3 s    zParserElement.__rand__cCst|ƒS)zH Implementation of ~ operator - returns :class:`NotAny` )r5)rÇrrrÚ __invert__? szParserElement.__invert__cCstd|jjƒ‚dS)Nz%r object is not iterable)r!r®r)rÇrrrr8E szParserElement.__iter__cCs’yt|tƒr|f}t|ƒWntk r8||f}YnXt|ƒdkrztjdj|dd…t|ƒdkrrdjt|ƒƒndƒƒ|t|dd…ƒ}|S)a‚ use ``[]`` indexing notation as a short form for expression repetition: - ``expr[n]`` is equivalent to ``expr*n`` - ``expr[m, n]`` is equivalent to ``expr*(m, n)`` - ``expr[n, ...]`` or ``expr[n,]`` is equivalent to ``expr*n + ZeroOrMore(expr)`` (read as "at least n instances of ``expr``") - ``expr[..., n]`` is equivalent to ``expr*(0, n)`` (read as "0 to n instances of ``expr``") - ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)`` - ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)`` ``None`` may be used in place of ``...``. Note that ``expr[..., n]`` and ``expr[m, n]``do not raise an exception if more than ``n`` ``expr``s exist in the input stream. If this behavior is desired, then write ``expr[..., n] + ~expr``. r“z.only 1 or 2 index arguments supported ({0}{1})Nr�z ... [{0}]r¶) ršrœr7r!rÒr3r4rîr;)rÇrIr¤rrrr J s   "zParserElement.__getitem__cCs|dk r|j|ƒS|jƒSdS)aý Shortcut for :class:`setResultsName`, with ``listAllMatches=False``. If ``name`` is given with a trailing ``'*'`` character, then ``listAllMatches`` will be passed as ``True``. If ``name` is omitted, same as calling :class:`copy`. Example:: # these are equivalent userdata = Word(alphas).setResultsName("name") + Word(nums + "-").setResultsName("socsecno") userdata = Word(alphas)("name") + Word(nums + "-")("socsecno") N)rÓrR)rÇrrrrÚ__call__n s zParserElement.__call__cCst|ƒS)zŽ Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from cluttering up returned output. )rH)rÇrrrÚsuppress‚ szParserElement.suppresscCs d|_|S)a Disables the skipping of whitespace before matching the characters in the :class:`ParserElement`'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars. F)rÀ)rÇrrrÚleaveWhitespace‰ szParserElement.leaveWhitespacecCsd|_||_d|_|S)z8 Overrides the default whitespace chars TF)rÀrÁrÂ)rÇrµrrrÚsetWhitespaceChars’ sz ParserElement.setWhitespaceCharscCs d|_|S)zì Overrides default behavior to expand ````s to spaces before parsing the input string. Must be called before ``parseString`` when the input grammar contains elements that match ```` characters. T)rÄ)rÇrrrÚ parseWithTabs› szParserElement.parseWithTabscCsLt|tƒrt|ƒ}t|tƒr4||jkrH|jj|ƒn|jjt|jƒƒƒ|S)aÄ Define expression to be ignored (e.g., comments) while doing pattern matching; may be called repeatedly, to define multiple comment or other ignorable patterns. Example:: patt = OneOrMore(Word(alphas)) patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj'] patt.ignore(cStyleComment) patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd'] )ršrrHrÅrírR)rÇrSrrrÚignore¤ s   zParserElement.ignorecCs"|pt|p t|ptf|_d|_|S)zT Enable display of debugging messages while doing pattern matching. T)r–ršr›rËrÆ)rÇÚ startActionÚ successActionÚexceptionActionrrrÚsetDebugActions¼ s  zParserElement.setDebugActionscCs|r|jtttƒnd|_|S)a• Enable display of debugging messages while doing pattern matching. Set ``flag`` to True to enable, False to disable. Example:: wd = Word(alphas).setName("alphaword") integer = Word(nums).setName("numword") term = wd | integer # turn on debugging for wd wd.setDebug() OneOrMore(term).parseString("abc 123 xyz 890") prints:: Match alphaword at loc 0(1,1) Matched alphaword -> ['abc'] Match alphaword at loc 3(1,4) Exception raised:Expected alphaword (at char 4), (line:1, col:5) Match alphaword at loc 7(1,8) Matched alphaword -> ['xyz'] Match alphaword at loc 11(1,12) Exception raised:Expected alphaword (at char 12), (line:1, col:13) Match alphaword at loc 15(1,16) Exception raised:Expected alphaword (at char 15), (line:1, col:16) The output shown is that produced by the default debug actions - custom debug actions can be specified using :class:`setDebugActions`. Prior to attempting to match the ``wd`` expression, the debugging message ``"Match at loc (,)"`` is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"`` message is shown. Also note the use of :class:`setName` to assign a human-readable name to the expression, which makes debugging and exception messages easier to understand - for instance, the default name created for the :class:`Word` expression without calling ``setName`` is ``"W:(ABCD...)"``. F)rRr–ršr›rÆ)rÇÚflagrrrrÑÆ s%zParserElement.setDebugcCs|jS)N)r)rÇrrrrÔñ szParserElement.__str__cCst|ƒS)N)r¥)rÇrrrrÕô szParserElement.__repr__cCsd|_d|_|S)NT)rÇr½)rÇrrrr÷ szParserElement.streamlinecCsdS)Nr)rÇrrrrÚcheckRecursionü szParserElement.checkRecursioncCs|jgƒdS)zj Check defined expressions for valid structure, check for infinite recursive definitions. N)rT)rÇÚ validateTracerrrÚvalidateÿ szParserElement.validatecCs y |jƒ}Wn2tk r>t|dƒ�}|jƒ}WdQRXYnXy |j||ƒStk rš}z2tjrh‚n"t|ddƒdk r†|j|j ƒ|_ |‚WYdd}~XnXdS)zÐ Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing. ÚrNrð) ÚreadrÎÚopenrr:rArr°rºrð)rÇÚfile_or_filenamerÚ file_contentsÚfrørrrÚ parseFile s   zParserElement.parseFilecCs>||kr dSt|tƒr |j|ƒSt|tƒr:t|ƒt|ƒkSdS)NTF)ršrr$rAÚvars)rÇrSrrrÚ__eq__ s   zParserElement.__eq__cCs ||k S)Nr)rÇrSrrrÚ__ne__$ szParserElement.__ne__cCst|ƒS)N)Úid)rÇrrrÚ__hash__' szParserElement.__hash__cCs||kS)Nr)rÇrSrrrÚ__req__* szParserElement.__req__cCs ||k S)Nr)rÇrSrrrÚ__rne__- szParserElement.__rne__c Cs0y|jt|ƒ|d�dStk r*dSXdS)aÁ Method for quick testing of a parser against a test string. Good for simple inline microtests of sub expressions while building up larger parser. Parameters: - testString - to test against this expression for a match - parseAll - (default= ``True``) - flag to pass to :class:`parseString` when running tests Example:: expr = Word(nums) assert expr.matches("100") )rTFN)rr¥r:)rÇÚ testStringrrrrr$0 s zParserElement.matchesú#c Csòt|tƒr"tttj|jƒjƒƒƒ}t|tƒr4t|ƒ}|dkrBt j }|j } g} g} d} tdƒj t dƒƒjtƒ} d}�xv|D�]l}|dk r’|j|dƒsœ| r¨| r¨| j|ƒqx|s®qx| rÀddj| ƒnd|g}g} y"| j|j|ƒƒ}|j||d�}Wnôtk �r }z’t|tƒ�rd nd}d|k�rV|jt|j|ƒƒ|jd t|j|ƒd d |ƒn|jd |jd |ƒ|jd t|ƒƒ| �oˆ|} |}WYdd}~X�ntk �râ}z&|jdt|ƒƒ| �oÌ|} |}WYdd}~XnÒX| �oî| } |dk �r¢yR|||ƒ}|dk �rrerÃrWrˆr?rrîrrÞ)rÇÚtestsrÚcommentÚfullDumpÚ printResultsÚ failureTestsròÚfileÚprint_Ú allResultsÚcommentsÚsuccessr�ÚBOMr˜raÚresultrËrÂrøÚpp_valuerërrrÚrunTestsD sn`    $       0 zParserElement.runTests)F)F)F)T)T)TT)TT)r)F)N)T)N)F)T)TrfTTFNN)Srrrràr´rrr¶r¸rárºrÉrRrÒrÕrÓrâr¡rçrèrérírðræròrçrþrÿr rrr rr rrrràrrrrÚ_MAX_INTr'r¢r+r«rTr\r7r8r?r@rBrCrDrErFrGrHr8r rIrJrKrLrMrNrRrÑrÔrÕrrTrVr]r_r`rbrcrdr$ryrrrrrAGsž      1     W    " :J0 &  J     $     +    cs6eZdZd ‡fdd„ Zdd„Zdd„Zdd „Z‡ZS) r2Fcs>tt|ƒjƒt|tƒƒjddƒ|_|j|_||_||_ dS)Nr)z...) Úsuperr2rÉrœr)r­r½rÚanchorrA)rÇr•rA)r®rrrÉê s z_PendingSkip.__init__cs\t|ƒjdƒdƒ}ˆjrNdd„}‡fdd„}ˆj|ƒj|ƒ|ƒj|ƒB|Sˆj||S)Nz...z _skipped*cSs.|j s|jjƒdgkr*|d=|jddƒdS)Nr¶rÚ_skipped)r}rrH)r˜rrrrAô sz'_PendingSkip.__add__..must_skipcs<|jjƒdd…dgkr8|jdƒ}dtˆjƒd|d<dS)Nr”r¶r}z missing .show_skip)rErÒrAr|rç)rÇrSÚskipperrArr)rÇrrTñ s z_PendingSkip.__add__cCs|jS)N)r½)rÇrrrrÕ sz_PendingSkip.__repr__cGs tdƒ‚dS)NzBuse of `...` expression without following SkipTo target expression)rˆ)rÇrÆrrrræ sz_PendingSkip.parseImpl)F)rrrrÉrTrÕræÚ __classcell__rr)r®rr2ç sr2cs eZdZdZ‡fdd„Z‡ZS)rIzYAbstract :class:`ParserElement` subclass, for defining atomic matching patterns. cstt|ƒjdd�dS)NF)rÎ)r{rIrÉ)rÇ)r®rrrÉ szToken.__init__)rrrràrÉr�rr)r®rrI scs eZdZdZ‡fdd„Z‡ZS)r)z'An empty token, will always match. cs$tt|ƒjƒd|_d|_d|_dS)Nr)TF)r{r)rÉrrÃrÈ)rÇ)r®rrrÉ szEmpty.__init__)rrrràrÉr�rr)r®rr) scs*eZdZdZ‡fdd„Zddd„Z‡ZS)r4z#A token that will never match. cs*tt|ƒjƒd|_d|_d|_d|_dS)Nr4TFzUnmatchable token)r{r4rÉrrÃrÈrÉ)rÇ)r®rrrÉ s zNoMatch.__init__TcCst|||j|ƒ‚dS)N)r<rÉ)rÇr”rÃrÛrrrræ$ szNoMatch.parseImpl)T)rrrràrÉrær�rr)r®rr4 s cs*eZdZdZ‡fdd„Zddd„Z‡ZS)r1aÒToken to exactly match a specified string. Example:: Literal('blah').parseString('blah') # -> ['blah'] Literal('blah').parseString('blahfooblah') # -> ['blah'] Literal('blah').parseString('bla') # -> Exception: Expected "blah" For case-insensitive matching, use :class:`CaselessLiteral`. For keyword matching (force word break before and after the matched string), use :class:`Keyword` or :class:`CaselessKeyword`. c s tt|ƒjƒ||_t|ƒ|_y|d|_Wn*tk rVtj dt dd�t |_ YnXdt |jƒ|_d|j|_d|_d|_|jdkrœt|ƒtkrœt|_ dS) Nrz2null string passed to Literal; use Empty() insteadr“)r0z"%s"z Expected Fr”)r{r1rÉÚmatchrÒÚmatchLenÚfirstMatchCharr"r3r4r5r)r®r¥rrÉrÃrÈrÞÚ_SingleCharLiteral)rÇÚ matchString)r®rrrÉ6 s    zLiteral.__init__TcCs@|||jkr,|j|j|ƒr,||j|jfSt|||j|ƒ‚dS)N)r„rr‚rƒr<rÉ)rÇr”rÃrÛrrrræJ szLiteral.parseImpl)T)rrrràrÉrær�rr)r®rr1( s  c@seZdZddd„ZdS)r…TcCs0|||jkr|d|jfSt|||j|ƒ‚dS)Nr”)r„r‚r<rÉ)rÇr”rÃrÛrrrræP sz_SingleCharLiteral.parseImplN)T)rrrrærrrrr…O sr…csLeZdZdZedZd‡fdd„ Zddd „Z‡fd d „Ze d d „ƒZ ‡Z S)r.a�Token to exactly match a specified string as a keyword, that is, it must be immediately followed by a non-keyword character. Compare with :class:`Literal`: - ``Literal("if")`` will match the leading ``'if'`` in ``'ifAndOnlyIf'``. - ``Keyword("if")`` will not; it will only match the leading ``'if'`` in ``'if x=1'``, or ``'if(y==2)'`` Accepts two optional constructor arguments in addition to the keyword string: - ``identChars`` is a string of characters that would be valid identifier characters, defaulting to all alphanumerics + "_" and "$" - ``caseless`` allows case-insensitive matching, default is ``False``. Example:: Keyword("start").parseString("start") # -> ['start'] Keyword("start").parseString("starting") # -> Exception For case-insensitive matching, use :class:`CaselessKeyword`. z_$NFc s®tt|ƒjƒ|dkrtj}||_t|ƒ|_y|d|_Wn$tk r^t j dt dd�YnXd|j|_ d|j |_ d|_d|_||_|r |jƒ|_|jƒ}t|ƒ|_dS)Nrz2null string passed to Keyword; use Empty() insteadr“)r0z"%s"z Expected F)r{r.rÉÚDEFAULT_KEYWORD_CHARSr‚rÒrƒr„r"r3r4r5rrÉrÃrÈÚcaselessÚupperÚ caselessmatchrñÚ identChars)rÇr†r‹rˆ)r®rrrÉs s&    zKeyword.__init__TcCs|jr|||||j…jƒ|jkrò|t|ƒ|jksL|||jjƒ|jkrò|dksj||djƒ|jkrò||j|jfSnv|||jkrò|jdks¢|j|j|ƒrò|t|ƒ|jksÈ|||j|jkrò|dksâ||d|jkrò||j|jfSt |||j |ƒ‚dS)Nrr”) rˆrƒr‰rŠrÒr‹r‚r„rr<rÉ)rÇr”rÃrÛrrrræˆ szKeyword.parseImplcstt|ƒjƒ}tj|_|S)N)r{r.rRr‡r‹)rÇr¹)r®rrrR› sz Keyword.copycCs |t_dS)z,Overrides the default Keyword chars N)r.r‡)rµrrrÚsetDefaultKeywordChars  szKeyword.setDefaultKeywordChars)NF)T) rrrràrQr‡rÉrærRrrŒr�rr)r®rr.X s   cs*eZdZdZ‡fdd„Zddd„Z‡ZS)r$afToken to match a specified string, ignoring case of letters. Note: the matched results will always be in the case of the given match string, NOT the case of the input text. Example:: OneOrMore(CaselessLiteral("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD'] (Contrast with example for :class:`CaselessKeyword`.) cs6tt|ƒj|jƒƒ||_d|j|_d|j|_dS)Nz'%s'z Expected )r{r$rÉr‰Ú returnStringrrÉ)rÇr†)r®rrrɱ s zCaselessLiteral.__init__TcCs@||||j…jƒ|jkr,||j|jfSt|||j|ƒ‚dS)N)rƒr‰r‚r�r<rÉ)rÇr”rÃrÛrrrræ¸ szCaselessLiteral.parseImpl)T)rrrràrÉrær�rr)r®rr$¦ s  cs"eZdZdZd‡fdd„ Z‡ZS)r#zÕ Caseless version of :class:`Keyword`. Example:: OneOrMore(CaselessKeyword("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD'] (Contrast with example for :class:`CaselessLiteral`.) Ncstt|ƒj||dd�dS)NT)rˆ)r{r#rÉ)rÇr†r‹)r®rrrÉÇ szCaselessKeyword.__init__)N)rrrràrÉr�rr)r®rr#½ s cs,eZdZdZd‡fdd„ Zd dd„Z‡ZS) rŠaœA variation on :class:`Literal` which matches "close" matches, that is, strings with at most 'n' mismatching characters. :class:`CloseMatch` takes parameters: - ``match_string`` - string to be matched - ``maxMismatches`` - (``default=1``) maximum number of mismatches allowed to count as a match The results from a successful parse will contain the matched text from the input string and the following named results: - ``mismatches`` - a list of the positions within the match_string where mismatches were found - ``original`` - the original match_string used to compare against the input string If ``mismatches`` is an empty list, then the match was an exact match. Example:: patt = CloseMatch("ATCATCGAATGGA") patt.parseString("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']}) patt.parseString("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1) # exact match patt.parseString("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']}) # close match allowing up to 2 mismatches patt = CloseMatch("ATCATCGAATGGA", maxMismatches=2) patt.parseString("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']}) r”csBtt|ƒjƒ||_||_||_d|j|jf|_d|_d|_dS)Nz&Expected %r (with up to %d mismatches)F) r{rŠrÉrÚ match_stringÚ maxMismatchesrÉrÈrÃ)rÇrŽr�)r®rrrÉë szCloseMatch.__init__TcCsÈ|}t|ƒ}|t|jƒ}||kr´|j}d}g} |j} x|tt|||…|ƒƒD]0\}} | \} } | | krN| j|ƒt| ƒ| krNPqNW|d}t|||…gƒ}||d<| |d<||fSt|||j|ƒ‚dS)Nrr”ÚoriginalÚ mismatches) rÒrŽr�ròr¬rír?r<rÉ)rÇr”rÃrÛÚstartrïÚmaxlocrŽÚmatch_stringlocr‘r�Ús_mÚsrcÚmatÚresultsrrrræô s(   zCloseMatch.parseImpl)r”)T)rrrràrÉrær�rr)r®rrŠÊ s  cs8eZdZdZd ‡fdd„ Zdd d „Z‡fd d „Z‡ZS)rLaX Token for matching words composed of allowed character sets. Defined with string containing all allowed initial characters, an optional string containing allowed body characters (if omitted, defaults to the initial character set), and an optional minimum, maximum, and/or exact length. The default value for ``min`` is 1 (a minimum value < 1 is not valid); the default values for ``max`` and ``exact`` are 0, meaning no maximum or exact length restriction. An optional ``excludeChars`` parameter can list characters that might be found in the input ``bodyChars`` string; useful to define a word of all printables except for one or two characters, for instance. :class:`srange` is useful for defining custom character set strings for defining ``Word`` expressions, using range notation from regular expression character sets. A common mistake is to use :class:`Word` to match a specific literal string, as in ``Word("Address")``. Remember that :class:`Word` uses the string argument to define *sets* of matchable characters. This expression would match "Add", "AAA", "dAred", or any other word made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an exact literal string, use :class:`Literal` or :class:`Keyword`. pyparsing includes helper strings for building Words: - :class:`alphas` - :class:`nums` - :class:`alphanums` - :class:`hexnums` - :class:`alphas8bit` (alphabetic characters in ASCII range 128-255 - accented, tilded, umlauted, etc.) - :class:`punc8bit` (non-alphabetic characters in ASCII range 128-255 - currency, symbols, superscripts, diacriticals, etc.) - :class:`printables` (any non-whitespace character) Example:: # a word composed of digits integer = Word(nums) # equivalent to Word("0123456789") or Word(srange("0-9")) # a word with a leading capital, and zero or more lowercase capital_word = Word(alphas.upper(), alphas.lower()) # hostnames are alphanumeric, with leading alpha, and '-' hostname = Word(alphas, alphanums + '-') # roman numeral (not a strict parser, accepts invalid mix of characters) roman = Word("IVXLCDM") # any string of non-whitespace characters, except for ',' csv_value = Word(printables, excludeChars=",") Nr”rFc sätt|ƒjƒˆrNtˆƒ‰dj‡fdd„|Dƒƒ}|rNdj‡fdd„|Dƒƒ}||_t|ƒ|_|rt||_t|ƒ|_n||_t|ƒ|_|dk|_ |dkržt dƒ‚||_ |dkr´||_ nt |_ |dkrÎ||_ ||_ t|ƒ|_d|j|_d |_||_d |j|jk�rà|dk�rà|dk�rà|dk�rà|j|jk�r@d t|jƒ|_nHt|jƒdk�rnd tj|jƒt|jƒf|_nd t|jƒt|jƒf|_|j�r d|jd|_ytj|jƒ|_Wntk �rÎd|_YnX|jj|_t|_dS)Nr¶c3s|]}|ˆkr|VqdS)Nr)rr¹)Ú excludeCharsrrr§H sz Word.__init__..c3s|]}|ˆkr|VqdS)Nr)rr¹)r™rrr§J srr”zZcannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permittedz Expected Frãz[%s]+z%s[%s]*z [%s][%s]*z\b)r{rLrÉrñr×Ú initCharsOrigÚ initCharsÚ bodyCharsOrigÚ bodyCharsÚ maxSpecifiedr<ÚminLenÚmaxLenrzr¥rrÉrÈÚ asKeywordÚ_escapeRegexRangeCharsÚreStringrÒr�ÚescapeÚcompilerˆr‚Úre_matchÚ _WordRegexr®)rÇr›r�ÚminÚmaxÚexactr¡r™)r®)r™rrÉD sV      0    z Word.__init__Tc Cs|||jkrt|||j|ƒ‚|}|d7}t|ƒ}|j}||j}t||ƒ}x ||krl|||krl|d7}qNWd}|||jkr†d}nV|jr¦||kr¦|||kr¦d}n6|j rÜ|dkrÄ||d|ksØ||krÜ|||krÜd}|rðt|||j|ƒ‚||||…fS)Nr”FTr) r›r<rÉrÒr�r r¨rŸržr¡) rÇr”rÃrÛr’rïÚ bodycharsr“ÚthrowExceptionrrrræ} s,   zWord.parseImplc stytt|ƒjƒStk r"YnX|jdkrndd„}|j|jkr^d||jƒ||jƒf|_nd||jƒ|_|jS)NcSs$t|ƒdkr|dd…dS|SdS)Néz...)rÒ)rªrrrÚ charsAsStr¡ s z Word.__str__..charsAsStrz W:(%s, %s)zW:(%s))r{rLrÔrˆr½ršrœ)rÇr®)r®rrrÔ™ s  z Word.__str__)Nr”rrFN)T)rrrràrÉrærÔr�rr)r®rrL s49 c@seZdZddd„ZdS)r§TcCs4|j||ƒ}|s t|||j|ƒ‚|jƒ}||jƒfS)N)r¦r<rÉÚendÚgroup)rÇr”rÃrÛrwrrrræ¯ s  z_WordRegex.parseImplN)T)rrrrærrrrr§® sr§cs"eZdZdZd‡fdd„ Z‡ZS)rPz“A short-cut class for defining ``Word(characters, exact=1)``, when defining a match of any single character in a string of characters. FNcsZtt|ƒj|d||d�dtdj|jƒƒ|_|r>d|j|_tj|jƒ|_|jj |_ dS)Nr”)rªr¡r™z[%s]r¶z\b%s\b) r{rPrÉr¢r×r›r£r�r¥r‚r¦)rÇÚcharsetr¡r™)r®rrrɽ s  z Char.__init__)FN)rrrràrÉr�rr)r®rrP¸ scsTeZdZdZd‡fdd„ Zddd„Zdd d „Zdd d „Z‡fd d„Zdd„Z ‡Z S)rDahToken for matching strings that match a given regular expression. Defined with string specifying the regular expression in a form recognized by the stdlib Python `re module `_. If the given regex contains named groups (defined using ``(?P...)``), these will be preserved as named parse results. If instead of the Python stdlib re module you wish to use a different RE module (such as the `regex` module), you can replace it by either building your Regex object with a compiled RE that was compiled using regex: Example:: realnum = Regex(r"[+-]?\d+\.\d*") date = Regex(r'(?P\d{4})-(?P\d\d?)-(?P\d\d?)') # ref: https://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression roman = Regex(r"M{0,4}(CM|CD|D?{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})") # use regex module instead of stdlib re module to construct a Regex using # a compiled regular expression import regex parser = pp.Regex(regex.compile(r'[0-9]')) rFc s$tt|ƒjƒt|tƒr†|s,tjdtdd�||_||_ yt j |j|j ƒ|_ |j|_ Wq¾t jk r‚tjd|tdd�‚Yq¾Xn8t|dƒr¶t|dƒr¶||_ |j|_|_ ||_ ntdƒ‚|j j|_t|ƒ|_d|j|_d |_|jd ƒd k |_||_||_|j�r|j|_|j�r |j|_d S) aThe parameters ``pattern`` and ``flags`` are passed to the ``re.compile()`` function as-is. See the Python `re module `_ module for an explanation of the acceptable patterns and flags. z0null string passed to Regex; use Empty() insteadr“)r0z$invalid pattern (%s) passed to RegexÚpatternr‚zCRegex may only be constructed with a string or a compiled RE objectz Expected Fr¶N)r{rDrÉršrr3r4r5r²Úflagsr�r¥r£Ú sre_constantsÚerrorr;r!r‚r¦r¥rrÉrÈrÃÚ asGroupListÚasMatchÚparseImplAsGroupListræÚparseImplAsMatch)rÇr²r³r¶r·)r®rrrÉÞ s<         zRegex.__init__Tc Csf|j||ƒ}|s t|||j|ƒ‚|jƒ}t|jƒƒ}|jƒ}|r^x|jƒD]\}}|||<qJW||fS)N)r¦r<rÉr¯r?r°Ú groupdictr,) rÇr”rÃrÛrwr¤Údr&r#rrrræ s   zRegex.parseImplcCs8|j||ƒ}|s t|||j|ƒ‚|jƒ}|jƒ}||fS)N)r¦r<rÉr¯Úgroups)rÇr”rÃrÛrwr¤rrrr¸ s  zRegex.parseImplAsGroupListcCs4|j||ƒ}|s t|||j|ƒ‚|jƒ}|}||fS)N)r¦r<rÉr¯)rÇr”rÃrÛrwr¤rrrr¹! s  zRegex.parseImplAsMatchc sDytt|ƒjƒStk r"YnX|jdkr>dt|jƒ|_|jS)NzRe:(%s))r{rDrÔrˆr½r r²)rÇ)r®rrrÔ* s z Regex.__str__cslˆjrtjdtdd�tƒ‚ˆjr@tˆƒr@tjdtdd�tƒ‚ˆjrT‡fdd„}n‡‡fdd„}ˆj|ƒS)a‰ Return Regex with an attached parse action to transform the parsed result as if called using `re.sub(expr, repl, string) `_. Example:: make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2") print(make_html.transformString("h1:main title:")) # prints "

main title

" z-cannot use sub() with Regex(asGroupList=True)r“)r0z9cannot use sub() with a callable with Regex(asMatch=True)cs|djˆƒS)Nr)Úexpand)rú)Úreplrrr¿K szRegex.sub..pacsˆjjˆ|dƒS)Nr)r�r')rú)r¾rÇrrr¿N s)r¶r3r4r5Ú SyntaxErrorr·rãrç)rÇr¾r¿r)r¾rÇrr'5 s   z Regex.sub)rFF)T)T)T) rrrràrÉrær¸r¹rÔr'r�rr)r®rrDÆ s- cs8eZdZdZd ‡fdd„ Zd dd„Z‡fd d „Z‡ZS) rBa& Token for matching strings that are delimited by quoting characters. Defined with the following parameters: - quoteChar - string of one or more characters defining the quote delimiting string - escChar - character to escape quotes, typically backslash (default= ``None``) - escQuote - special quote sequence to escape an embedded quote string (such as SQL's ``""`` to escape an embedded ``"``) (default= ``None``) - multiline - boolean indicating whether quotes can span multiple lines (default= ``False``) - unquoteResults - boolean indicating whether the matched text should be unquoted (default= ``True``) - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default= ``None`` => same as quoteChar) - convertWhitespaceEscapes - convert escaped whitespace (``'\t'``, ``'\n'``, etc.) to actual whitespace (default= ``True``) Example:: qs = QuotedString('"') print(qs.searchString('lsjdf "This is the quote" sldjf')) complex_qs = QuotedString('{{', endQuoteChar='}}') print(complex_qs.searchString('lsjdf {{This is the "quote"}} sldjf')) sql_qs = QuotedString('"', escQuote='""') print(sql_qs.searchString('lsjdf "This is the quote with ""embedded"" quotes" sldjf')) prints:: [['This is the quote']] [['This is the "quote"']] [['This is the quote with "embedded" quotes']] NFTc sXttˆƒjƒ|jƒ}|s0tjdtdd�tƒ‚|dkr>|}n"|jƒ}|s`tjdtdd�tƒ‚|ˆ_t |ƒˆ_ |dˆ_ |ˆ_ t |ƒˆ_ |ˆ_|ˆ_|ˆ_|ˆ_|rètjtjBˆ_dtjˆjƒtˆj dƒ|dk rÜt|ƒpÞdfˆ_n.ú)z|(?:%s)z|(?:%s.)z(.)z)*%sz$invalid pattern (%s) passed to Regexz Expected FTr•)'r{rBrÉrØr3r4r5r¿Ú quoteCharrÒÚ quoteCharLenÚfirstQuoteCharrÀÚendQuoteCharLenÚescCharÚescQuoteÚunquoteResultsÚconvertWhitespaceEscapesr�Ú MULTILINEÚDOTALLr³r¤r¢r²r×r)ÚescCharReplacePatternr¥r£r‚r¦r´rµr¥rrÉrÈrÃ)rÇrÂrÆrÇÚ multilinerÈrÀrÉ)r®)rÇrrÉy sd       6    zQuotedString.__init__c CsÖ|||jkr|j||ƒpd}|s2t|||j|ƒ‚|jƒ}|jƒ}|jrÎ||j|j …}t |t ƒrÎd|kr¢|j r¢dddddœ}x |j ƒD]\}}|j ||ƒ}qŠW|jr¸tj|jd|ƒ}|jrÎ|j |j|jƒ}||fS)NrÑú rêú ú )z\tz\nz\fz\rz\g<1>)rÄr¦r<rÉr¯r°rÈrÃrÅršrrÉr,r­rÆr�r'rÌrÇrÀ) rÇr”rÃrÛrwr¤Úws_mapÚwslitÚwscharrrrræº s( zQuotedString.parseImplc sFytt|ƒjƒStk r"YnX|jdkr@d|j|jf|_|jS)Nz.quoted string, starting with %s ending with %s)r{rBrÔrˆr½rÂrÀ)rÇ)r®rrrÔÝ s zQuotedString.__str__)NNFTNT)T)rrrràrÉrærÔr�rr)r®rrBR s &@ #cs8eZdZdZd ‡fdd„ Zd dd„Z‡fd d „Z‡ZS) r%aüToken for matching words composed of characters *not* in a given set (will include whitespace in matched characters if not listed in the provided exclusion set - see example). Defined with string containing all disallowed characters, and an optional minimum, maximum, and/or exact length. The default value for ``min`` is 1 (a minimum value < 1 is not valid); the default values for ``max`` and ``exact`` are 0, meaning no maximum or exact length restriction. Example:: # define a comma-separated-value as anything that is not a ',' csv_value = CharsNotIn(',') print(delimitedList(csv_value).parseString("dkls,lsdkjf,s12 34,@!#,213")) prints:: ['dkls', 'lsdkjf', 's12 34', '@!#', '213'] r”rcs†tt|ƒjƒd|_||_|dkr*tdƒ‚||_|dkr@||_nt|_|dkrZ||_||_t |ƒ|_ d|j |_ |jdk|_ d|_ dS)NFr”zfcannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permittedrz Expected )r{r%rÉrÀÚnotCharsr<rŸr rzr¥rrÉrÃrÈ)rÇrÔr¨r©rª)r®rrrÉý s    zCharsNotIn.__init__TcCs”|||jkrt|||j|ƒ‚|}|d7}|j}t||jt|ƒƒ}x ||krd|||krd|d7}qFW|||jkr„t|||j|ƒ‚||||…fS)Nr”)rÔr<rÉr¨r rÒrŸ)rÇr”rÃrÛr’ÚnotcharsÚmaxlenrrrræs zCharsNotIn.parseImplc sdytt|ƒjƒStk r"YnX|jdkr^t|jƒdkrRd|jdd…|_n d|j|_|jS)Nr­z !W:(%s...)z!W:(%s))r{r%rÔrˆr½rÒrÔ)rÇ)r®rrrÔ&s  zCharsNotIn.__str__)r”rr)T)rrrràrÉrærÔr�rr)r®rr%é s cs`eZdZdZdddddddd d d d d ddddddddddddœZd"‡fdd„ Zd#d d!„Z‡ZS)$rKa™Special matching class for matching whitespace. Normally, whitespace is ignored by pyparsing grammars. This class is included when some whitespace structures are significant. Define with a string containing the whitespace characters to be matched; default is ``" \t\r\n"``. Also takes optional ``min``, ``max``, and ``exact`` arguments, as defined for the :class:`Word` class. zzzzzzzzz z z z zzzzzz z zzzz)rãrÎrêrÐrÏõ u uá Žu uâ€�u u u u u u u u u u​u uâ�Ÿu ú r”rcs’ttˆƒjƒ|ˆ_ˆjdj‡fdd„ˆjDƒƒƒdjdd„ˆjDƒƒˆ_dˆ_dˆjˆ_ |ˆ_ |dkrt|ˆ_ nt ˆ_ |dkrŽ|ˆ_ |ˆ_ dS)Nr¶c3s|]}|ˆjkr|VqdS)N)Ú matchWhite)rr¹)rÇrrr§Ysz!White.__init__..css|]}tj|VqdS)N)rKÚ whiteStrs)rr¹rrrr§[sTz Expected r) r{rKrÉrÙrLr×rÁrrÃrÉrŸr rz)rÇÚwsr¨r©rª)r®)rÇrrÉVs  zWhite.__init__TcCs”|||jkrt|||j|ƒ‚|}|d7}||j}t|t|ƒƒ}x"||krd|||jkrd|d7}qDW|||jkr„t|||j|ƒ‚||||…fS)Nr”)rÙr<rÉr r¨rÒrŸ)rÇr”rÃrÛr’r“rrrræjs  zWhite.parseImpl)rØr”rr)T)rrrràrÚrÉrær�rr)r®rrK4s4cseZdZ‡fdd„Z‡ZS)Ú_PositionTokencs(tt|ƒjƒ|jj|_d|_d|_dS)NTF)r{rÜrÉr®rrrÃrÈ)rÇ)r®rrrÉ{s z_PositionToken.__init__)rrrrÉr�rr)r®rrÜzsrÜcs2eZdZdZ‡fdd„Zdd„Zd dd„Z‡ZS) r,zaToken to advance to a specific column of input text; useful for tabular report scraping. cstt|ƒjƒ||_dS)N)r{r,rÉrW)rÇÚcolno)r®rrrÉ…szGoToColumn.__init__cCs`t||ƒ|jkr\t|ƒ}|jr*|j||ƒ}x0||krZ||jƒrZt||ƒ|jkrZ|d7}q,W|S)Nr”)rWrÒrÅríÚisspace)rÇr”rÃrïrrrrð‰s & zGoToColumn.preParseTcCsDt||ƒ}||jkr"t||d|ƒ‚||j|}|||…}||fS)NzText not in expected column)rWr<)rÇr”rÃrÛÚthiscolÚnewlocr¤rrrræ’s    zGoToColumn.parseImpl)T)rrrràrÉrðrær�rr)r®rr,�s  cs*eZdZdZ‡fdd„Zddd„Z‡ZS)r0a±Matches if current position is at the beginning of a line within the parse string Example:: test = '''\ AAA this line AAA and this line AAA but not this one B AAA and definitely not this one ''' for t in (LineStart() + 'AAA' + restOfLine).searchString(test): print(t) prints:: ['AAA', ' this line'] ['AAA', ' and this line'] cstt|ƒjƒd|_dS)NzExpected start of line)r{r0rÉrÉ)rÇ)r®rrrɱszLineStart.__init__TcCs*t||ƒdkr|gfSt|||j|ƒ‚dS)Nr”)rWr<rÉ)rÇr”rÃrÛrrrræµszLineStart.parseImpl)T)rrrràrÉrær�rr)r®rr0›s cs*eZdZdZ‡fdd„Zddd„Z‡ZS)r/zTMatches if current position is at the end of a line within the parse string cs,tt|ƒjƒ|jtjjddƒƒd|_dS)Nrêr¶zExpected end of line)r{r/rÉrLrAr´r­rÉ)rÇ)r®rrrɾszLineEnd.__init__TcCsb|t|ƒkr6||dkr$|ddfSt|||j|ƒ‚n(|t|ƒkrN|dgfSt|||j|ƒ‚dS)Nrêr”)rÒr<rÉ)rÇr”rÃrÛrrrræÃs     zLineEnd.parseImpl)T)rrrràrÉrær�rr)r®rr/ºs cs*eZdZdZ‡fdd„Zddd„Z‡ZS)rGzLMatches if current position is at the beginning of the parse string cstt|ƒjƒd|_dS)NzExpected start of text)r{rGrÉrÉ)rÇ)r®rrrÉÒszStringStart.__init__TcCs0|dkr(||j|dƒkr(t|||j|ƒ‚|gfS)Nr)rðr<rÉ)rÇr”rÃrÛrrrræÖszStringStart.parseImpl)T)rrrràrÉrær�rr)r®rrGÎs cs*eZdZdZ‡fdd„Zddd„Z‡ZS)rFzBMatches if current position is at the end of the parse string cstt|ƒjƒd|_dS)NzExpected end of text)r{rFrÉrÉ)rÇ)r®rrrÉàszStringEnd.__init__TcCs^|t|ƒkrt|||j|ƒ‚n<|t|ƒkr6|dgfS|t|ƒkrJ|gfSt|||j|ƒ‚dS)Nr”)rÒr<rÉ)rÇr”rÃrÛrrrræäs    zStringEnd.parseImpl)T)rrrràrÉrær�rr)r®rrFÝs cs.eZdZdZef‡fdd„ Zddd„Z‡ZS)rNayMatches if the current position is at the beginning of a Word, and is not preceded by any character in a given set of ``wordChars`` (default= ``printables``). To emulate the ```` behavior of regular expressions, use ``WordStart(alphanums)``. ``WordStart`` will also match at the beginning of the string being parsed, or at the beginning of a line. cs"tt|ƒjƒt|ƒ|_d|_dS)NzNot at the start of a word)r{rNrÉrñÚ wordCharsrÉ)rÇrá)r®rrrÉ÷s zWordStart.__init__TcCs@|dkr8||d|jks(|||jkr8t|||j|ƒ‚|gfS)Nrr”)rár<rÉ)rÇr”rÃrÛrrrræüs zWordStart.parseImpl)T)rrrràrtrÉrær�rr)r®rrNîscs.eZdZdZef‡fdd„ Zddd„Z‡ZS)rMa_Matches if the current position is at the end of a Word, and is not followed by any character in a given set of ``wordChars`` (default= ``printables``). To emulate the ```` behavior of regular expressions, use ``WordEnd(alphanums)``. ``WordEnd`` will also match at the end of the string being parsed, or at the end of a line. cs(tt|ƒjƒt|ƒ|_d|_d|_dS)NFzNot at the end of a word)r{rMrÉrñrárÀrÉ)rÇrá)r®rrrÉ s zWordEnd.__init__TcCsPt|ƒ}|dkrH||krH|||jks8||d|jkrHt|||j|ƒ‚|gfS)Nrr”)rÒrár<rÉ)rÇr”rÃrÛrïrrrræs zWordEnd.parseImpl)T)rrrràrtrÉrær�rr)r®rrMscszeZdZdZd‡fdd„ Zdd„Zdd„Z‡fd d „Z‡fd d „Z‡fd d„Z ddd„Z ‡fdd„Z d‡fdd„ Z ‡Z S)r=z]Abstract subclass of ParserElement, for combining and post-processing parsed tokens. Fc sÈttˆƒj|ƒt|tƒr"t|ƒ}t|tƒr<ˆj|ƒgˆ_n‚t|t ƒrP|gˆ_nnt|t ƒr’t|ƒ}t dd„|Dƒƒr†‡fdd„|Dƒ}t|ƒˆ_n,yt|ƒˆ_Wnt k r¼|gˆ_YnXdˆ_ dS)Ncss|]}t|tƒVqdS)N)ršr)rr•rrrr§*sz+ParseExpression.__init__..c3s&|]}t|tƒrˆj|ƒn|VqdS)N)ršrr·)rrë)rÇrrr§+sF)r{r=rÉršrrrr·ÚexprsrAr r€r!rÌ)rÇrârÎ)r®)rÇrrÉs"      zParseExpression.__init__cCs|jj|ƒd|_|S)N)rârír½)rÇrSrrrrí4s zParseExpression.appendcCs4d|_dd„|jDƒ|_x|jD] }|jƒq W|S)z€Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on all contained expressions.FcSsg|] }|jƒ‘qSr)rR)rrërrrr=sz3ParseExpression.leaveWhitespace..)rÀrârK)rÇrërrrrK9s   zParseExpression.leaveWhitespacecszt|tƒrF||jkrvtt|ƒj|ƒxP|jD]}|j|jdƒq,Wn0tt|ƒj|ƒx|jD]}|j|jdƒq^W|S)Nr”r•r•)ršrHrÅr{r=rNrâ)rÇrSrë)r®rrrNBs    zParseExpression.ignorec sLytt|ƒjƒStk r"YnX|jdkrFd|jjt|jƒf|_|jS)Nz%s:(%s)) r{r=rÔrˆr½r®rr¥râ)rÇ)r®rrrÔNs zParseExpression.__str__cs0tt|ƒjƒx|jD] }|jƒqWt|jƒdk�r|jd}t||jƒr¨|j r¨|jdkr¨|j r¨|jdd…|jdg|_d|_ |j |j O_ |j |j O_ |jd}t||jƒoÖ|j oÖ|jdkoÖ|j �r|jdd…|jdd…|_d|_ |j |j O_ |j |j O_ dt |ƒ|_|S)Nr“rr”z Expected r•r•)r{r=rrârÒršr®r»r¾rÆr½rÃrÈr¥rÉ)rÇrërS)r®rrrXs0         zParseExpression.streamlineNcCsF|dk r |ngdd…|g}x|jD]}|j|ƒq&W|jgƒdS)N)rârVrT)rÇrUÚtmprërrrrVzs zParseExpression.validatecs$tt|ƒjƒ}dd„|jDƒ|_|S)NcSsg|] }|jƒ‘qSr)rR)rrërrrr‚sz(ParseExpression.copy..)r{r=rRrâ)rÇr¤)r®rrrR€szParseExpression.copycsZtjrHx@|jD]6}t|tƒr|jrtjdjd|t |ƒj |jƒdd�qWt t |ƒj ||ƒS)Nz]{0}: setting results name {1!r} on {2} expression collides with {3!r} on contained expressionrr‘)r0)rrrâršrAr¾r3r4rîrÞrr{r=rÓ)rÇrrÔrë)r®rrrÓ…s  zParseExpression._setResultsName)F)N)F)rrrràrÉrírKrNrÔrrVrRrÓr�rr)r®rr=s "  cs`eZdZdZGdd„deƒZd‡fdd„ Z‡fdd„Zdd d „Zd d „Z d d„Z dd„Z ‡Z S)r"a Requires all given :class:`ParseExpression` s to be found in the given order. Expressions may be separated by whitespace. May be constructed using the ``'+'`` operator. May also be constructed using the ``'-'`` operator, which will suppress backtracking. Example:: integer = Word(nums) name_expr = OneOrMore(Word(alphas)) expr = And([integer("id"), name_expr("name"), integer("age")]) # more easily written as: expr = integer("id") + name_expr("name") + integer("age") cseZdZ‡fdd„Z‡ZS)zAnd._ErrorStopcs&ttj|ƒj||Žd|_|jƒdS)Nú-)r{r"r6rÉrrK)rÇrÆrE)r®rrrɦszAnd._ErrorStop.__init__)rrrrÉr�rr)r®rr6¥sr6Tcsät|ƒ}|r’t|kr’g}xlt|ƒD]`\}}|tkrx|t|ƒdkrntƒ||djd}|jt|ƒdƒƒq‚tdƒ‚q"|j|ƒq"W||dd…<t t |ƒj ||ƒt dd„|jDƒƒ|_ |j|jdjƒ|jdj|_d|_dS) Nr”z _skipped*z0cannot construct And with sequence ending in ...css|] }|jVqdS)N)rÃ)rrërrrr§ºszAnd.__init__..rTr•)rr1ròrÒr)rârírErˆr{r"rÉrärÃrLrÁrÀrÌ)rÇrârÎrãrür•Ú skipto_arg)r®rrrÉ«s    z And.__init__csÒ|jrªtdd„|jdd…Dƒƒrªxtt|jdd…ƒD]^\}}|dkrHq6t|tƒr6|jr6t|jd tƒr6|jd |j|d|jd <d|j|d<q6Wdd„|jDƒ|_tt|ƒjƒt dd„|jDƒƒ|_ |S) Ncss.|]&}t|tƒo$|jo$t|jdtƒVqdS)r”Nr•)ršr=râr2)rrërrrr§Âsz!And.streamline..r”cSsg|]}|dk r|‘qS)Nr)rrërrrrËsz"And.streamline..css|] }|jVqdS)N)rÃ)rrërrrr§Îsr•r•r•r•r•) râr€ròršr=r2r{r"rrärÃ)rÇrürë)r®rrr¿s zAnd.streamlinec Cs|jdj|||dd�\}}d}xØ|jdd…D]Æ}t|tjƒrFd}q0|rÐy|j|||ƒ\}}Wqâtk rv‚Yqâtk r¦}zd|_tj|ƒ‚WYdd}~Xqât k rÌt|t |ƒ|j |ƒ‚YqâXn|j|||ƒ\}}|sî|j ƒr0||7}q0W||fS)NrF)rÜr”T) râràršr"r6r@r:rðrÌr"rÒrÉrC) rÇr”rÃrÛÚ resultlistÚ errorStoprëÚ exprtokensrËrrrræÑs(   z And.parseImplcCst|tƒr|j|ƒ}|j|ƒS)N)ršrr·rí)rÇrSrrrrNês  z And.__iadd__cCs8|dd…|g}x |jD]}|j|ƒ|jsPqWdS)N)rârTrÃ)rÇrÚsubRecCheckListrërrrrTïs   zAnd.checkRecursioncCs@t|dƒr|jS|jdkr:ddjdd„|jDƒƒd|_|jS)NrÚ{rãcss|]}t|ƒVqdS)N)r¥)rrërrrr§ûszAnd.__str__..Ú})r;rr½r×râ)rÇrrrrÔös    z And.__str__)T)T) rrrràr)r6rÉrrærNrTrÔr�rr)r®rr"“s  cs^eZdZdZd‡fdd„ Z‡fdd„Zddd „Zd d „Zd d „Zdd„Z d‡fdd„ Z ‡Z S)r9a¿Requires that at least one :class:`ParseExpression` is found. If two expressions match, the expression that matches the longest string will be used. May be constructed using the ``'^'`` operator. Example:: # construct Or using '^' operator number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums)) print(number.searchString("123 3.1416 789")) prints:: [['123'], ['3.1416'], ['789']] Fcs:tt|ƒj||ƒ|jr0tdd„|jDƒƒ|_nd|_dS)Ncss|] }|jVqdS)N)rÃ)rrërrrr§szOr.__init__..T)r{r9rÉrâr€rÃ)rÇrârÎ)r®rrrÉsz Or.__init__cs.tt|ƒjƒtjr*tdd„|jDƒƒ|_|S)Ncss|] }|jVqdS)N)r¿)rrërrrr§sz Or.streamline..)r{r9rr!Úcollect_all_And_tokensr€râr¿)rÇ)r®rrrsz Or.streamlineTcCsÆd}d}g}x¤|jD]š}y|j||ƒ}Wnvtk rd} z d| _| j|krT| }| j}WYdd} ~ Xqtk ržt|ƒ|kršt|t|ƒ|j|ƒ}t|ƒ}YqX|j||fƒqW|�rœ|j t dƒdd�|sè|dd} | j |||ƒSd} x |D]˜\} } | | dk�r | Sy| j |||ƒ\}}Wn@tk �rb} z"d| _| j|k�rR| }| j}WYdd} ~ XqòX|| k�rv||fS|| dkrò||f} qòW| d k�rœ| S|dk �r´|j|_ |‚nt||d|ƒ‚dS) Nr”rT)rIr+z no defined alternatives to matchr•r•)r•Nr•)r•N) rârþr<rðrÃr"rÒrÉríÚsortrràr¾)rÇr”rÃrÛÚ maxExcLocÚ maxExceptionr$rëÚloc2rûÚ best_exprÚlongestÚloc1Úexpr1r™rrrræsT          z Or.parseImplcCst|tƒr|j|ƒ}|j|ƒS)N)ršrr·rí)rÇrSrrrÚ__ixor__[s  z Or.__ixor__cCs@t|dƒr|jS|jdkr:ddjdd„|jDƒƒd|_|jS)Nrrêz ^ css|]}t|ƒVqdS)N)r¥)rrërrrr§eszOr.__str__..rë)r;rr½r×râ)rÇrrrrÔ`s    z Or.__str__cCs0|dd…|g}x|jD]}|j|ƒqWdS)N)rârT)rÇrrérërrrrTis zOr.checkRecursioncsRtj r@tjr@tdd„|jDƒƒr@tjdjd|t |ƒj ƒdd�t t |ƒj ||ƒS)Ncss|]}t|tƒVqdS)N)ršr")rrërrrr§qsz%Or._setResultsName..z–{0}: setting results name {1!r} on {2} expression may only return a single token for an And alternative, in future will return the full list of tokensrr‘)r0)r!rìrrr€râr3r4rîrÞrr{r9rÓ)rÇrrÔ)r®rrrÓnszOr._setResultsName)F)T)F) rrrràrÉrrærõrÔrTrÓr�rr)r®rr9s  = cs^eZdZdZd‡fdd„ Z‡fdd„Zddd „Zd d „Zd d „Zdd„Z d‡fdd„ Z ‡Z S)r3a¸Requires that at least one :class:`ParseExpression` is found. If two expressions match, the first one listed is the one that will match. May be constructed using the ``'|'`` operator. Example:: # construct MatchFirst using '|' operator # watch the order of expressions to match number = Word(nums) | Combine(Word(nums) + '.' + Word(nums)) print(number.searchString("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']] # put more selective expression first number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums) print(number.searchString("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']] Fcs:tt|ƒj||ƒ|jr0tdd„|jDƒƒ|_nd|_dS)Ncss|] }|jVqdS)N)rÃ)rrërrrr§�sz&MatchFirst.__init__..T)r{r3rÉrâr€rÃ)rÇrârÎ)r®rrrÉŒszMatchFirst.__init__cs.tt|ƒjƒtjr*tdd„|jDƒƒ|_|S)Ncss|] }|jVqdS)N)r¿)rrërrrr§–sz(MatchFirst.streamline..)r{r3rr!rìr€râr¿)rÇ)r®rrr“szMatchFirst.streamlineTc CsÄd}d}x¶|jD]ˆ}y|j|||ƒ}|Stk r\}z|j|krL|}|j}WYdd}~Xqtk r–t|ƒ|kr’t|t|ƒ|j|ƒ}t|ƒ}YqXqW|dk r²|j|_|‚nt||d|ƒ‚dS)Nr”z no defined alternatives to matchr•)râràr<rÃr"rÒrÉr¾) rÇr”rÃrÛrîrïrër¤rûrrrræ™s$   zMatchFirst.parseImplcCst|tƒr|j|ƒ}|j|ƒS)N)ršrr·rí)rÇrSrrrÚ__ior__±s  zMatchFirst.__ior__cCs@t|dƒr|jS|jdkr:ddjdd„|jDƒƒd|_|jS)Nrrêz | css|]}t|ƒVqdS)N)r¥)rrërrrr§»sz%MatchFirst.__str__..rë)r;rr½r×râ)rÇrrrrÔ¶s    zMatchFirst.__str__cCs0|dd…|g}x|jD]}|j|ƒqWdS)N)rârT)rÇrrérërrrrT¿s zMatchFirst.checkRecursioncsRtj r@tjr@tdd„|jDƒƒr@tjdjd|t |ƒj ƒdd�t t |ƒj ||ƒS)Ncss|]}t|tƒVqdS)N)ršr")rrërrrr§Çsz-MatchFirst._setResultsName..z–{0}: setting results name {1!r} on {2} expression may only return a single token for an And alternative, in future will return the full list of tokensrr‘)r0)r!rìrrr€râr3r4rîrÞrr{r3rÓ)rÇrrÔ)r®rrrÓÄszMatchFirst._setResultsName)F)T)F) rrrràrÉrrærörÔrTrÓr�rr)r®rr3{s   csHeZdZdZd ‡fdd„ Z‡fdd„Zddd„Zd d „Zd d „Z‡Z S)r(asRequires all given :class:`ParseExpression` s to be found, but in any order. Expressions may be separated by whitespace. May be constructed using the ``'&'`` operator. Example:: color = oneOf("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN") shape_type = oneOf("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON") integer = Word(nums) shape_attr = "shape:" + shape_type("shape") posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn") color_attr = "color:" + color("color") size_attr = "size:" + integer("size") # use Each (using operator '&') to accept attributes in any order # (shape and posn are required, color and size are optional) shape_spec = shape_attr & posn_attr & Optional(color_attr) & Optional(size_attr) shape_spec.runTests(''' shape: SQUARE color: BLACK posn: 100, 120 shape: CIRCLE size: 50 color: BLUE posn: 50,80 color:GREEN size:20 shape:TRIANGLE posn:20,40 ''' ) prints:: shape: SQUARE color: BLACK posn: 100, 120 ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']] - color: BLACK - posn: ['100', ',', '120'] - x: 100 - y: 120 - shape: SQUARE shape: CIRCLE size: 50 color: BLUE posn: 50,80 ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']] - color: BLUE - posn: ['50', ',', '80'] - x: 50 - y: 80 - shape: CIRCLE - size: 50 color: GREEN size: 20 shape: TRIANGLE posn: 20,40 ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']] - color: GREEN - posn: ['20', ',', '40'] - x: 20 - y: 40 - shape: TRIANGLE - size: 20 Tcs>tt|ƒj||ƒtdd„|jDƒƒ|_d|_d|_d|_dS)Ncss|] }|jVqdS)N)rÃ)rrërrrr§ sz Each.__init__..T) r{r(rÉrärârÃrÀÚinitExprGroupsr¿)rÇrârÎ)r®rrrÉ s z Each.__init__cs(tt|ƒjƒtdd„|jDƒƒ|_|S)Ncss|] }|jVqdS)N)rÃ)rrërrrr§sz"Each.streamline..)r{r(rrärârÃ)rÇ)r®rrrszEach.streamlinec sú|jr’tdd„|jDƒƒ|_dd„|jDƒ}dd„|jDƒ}|||_dd„|jDƒ|_dd„|jDƒ|_dd„|jDƒ|_|j|j7_d |_|}|jdd…}|jdd…‰g}d } x¶| �rp|ˆ|j|j} g} x~| D]v} y| j||ƒ}Wn t k �r| j | ƒYqàX|j |jj t | ƒ| ƒƒ| |k�rD|j | ƒqà| ˆkràˆj | ƒqàWt| ƒt| ƒkr¼d } q¼W|�rœd jd d„|Dƒƒ} t ||d | ƒ‚|‡fdd„|jDƒ7}g}x*|D]"} | j|||ƒ\}}|j |ƒ�q¾Wt|tgƒƒ}||fS)Ncss&|]}t|tƒrt|jƒ|fVqdS)N)ršr8rar•)rrërrrr§sz!Each.parseImpl..cSsg|]}t|tƒr|j‘qSr)ršr8r•)rrërrrrsz"Each.parseImpl..cSs&g|]}|jrt|ttfƒ r|‘qSr)rÃršr8rD)rrërrrrscSsg|]}t|tƒr|j‘qSr)ršrOr•)rrërrrrscSsg|]}t|tƒr|j‘qSr)ršr6r•)rrërrrrscSs g|]}t|tttfƒs|‘qSr)ršr8rOr6)rrërrrrsFTz, css|]}t|ƒVqdS)N)r¥)rrërrrr§9sz*Missing one or more required elements (%s)cs$g|]}t|tƒr|jˆkr|‘qSr)ršr8r•)rrë)ÚtmpOptrrr=s)r÷rrâÚopt1mapÚ optionalsÚmultioptionalsÚ multirequiredÚrequiredrþr<rírôraÚremoverÒr×ràÚsumr?)rÇr”rÃrÛÚopt1Úopt2ÚtmpLocÚtmpReqdÚ matchOrderÚ keepMatchingÚtmpExprsÚfailedrëÚmissingrær˜Ú finalResultsr)rørræsP     zEach.parseImplcCs@t|dƒr|jS|jdkr:ddjdd„|jDƒƒd|_|jS)Nrrêz & css|]}t|ƒVqdS)N)r¥)rrërrrr§LszEach.__str__..rë)r;rr½r×râ)rÇrrrrÔGs    z Each.__str__cCs0|dd…|g}x|jD]}|j|ƒqWdS)N)rârT)rÇrrérërrrrTPs zEach.checkRecursion)T)T) rrrràrÉrrærÔrTr�rr)r®rr(Ñs 8  1 csjeZdZdZd‡fdd„ Zddd„Zdd „Z‡fd d „Z‡fd d „Zdd„Z ddd„Z ‡fdd„Z ‡Z S)r;zfAbstract subclass of :class:`ParserElement`, for combining and post-processing parsed tokens. Fcsštt|ƒj|ƒt|tƒr@t|jtƒr2|j|ƒ}n|jt|ƒƒ}||_ d|_ |dk r–|j |_ |j |_ |j |jƒ|j|_|j|_|j|_|jj|jƒdS)N)r{r;rÉršrÚ issubclassr·rIr1r•r½rÈrÃrLrÁrÀr¿rÌrÅrO)rÇr•rÎ)r®rrrÉZs    zParseElementEnhance.__init__TcCs2|jdk r|jj|||dd�Std||j|ƒ‚dS)NF)rÜr¶)r•ràr<rÉ)rÇr”rÃrÛrrrræls zParseElementEnhance.parseImplcCs*d|_|jjƒ|_|jdk r&|jjƒ|S)NF)rÀr•rRrK)rÇrrrrKrs    z#ParseElementEnhance.leaveWhitespacecsrt|tƒrB||jkrntt|ƒj|ƒ|jdk rn|jj|jdƒn,tt|ƒj|ƒ|jdk rn|jj|jdƒ|S)Nr”r•r•)ršrHrÅr{r;rNr•)rÇrS)r®rrrNys    zParseElementEnhance.ignorecs&tt|ƒjƒ|jdk r"|jjƒ|S)N)r{r;rr•)rÇ)r®rrr…s  zParseElementEnhance.streamlinecCsB||krt||gƒ‚|dd…|g}|jdk r>|jj|ƒdS)N)rCr•rT)rÇrrérrrrT‹s  z"ParseElementEnhance.checkRecursionNcCsB|dkr g}|dd…|g}|jdk r4|jj|ƒ|jgƒdS)N)r•rVrT)rÇrUrãrrrrV’s   zParseElementEnhance.validatec sVytt|ƒjƒStk r"YnX|jdkrP|jdk rPd|jjt|jƒf|_|jS)Nz%s:(%s)) r{r;rÔrˆr½r•r®rr¥)rÇ)r®rrrÔšszParseElementEnhance.__str__)F)T)N) rrrràrÉrærKrNrrTrVrÔr�rr)r®rr;Vs   cs*eZdZdZ‡fdd„Zddd„Z‡ZS)r*abLookahead matching of the given parse expression. ``FollowedBy`` does *not* advance the parsing position within the input string, it only verifies that the specified parse expression matches at the current position. ``FollowedBy`` always returns a null token list. If any results names are defined in the lookahead expression, those *will* be returned for access by name. Example:: # use FollowedBy to match a label only if it is followed by a ':' data_word = Word(alphas) label = data_word + FollowedBy(':') attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) OneOrMore(attr_expr).parseString("shape: SQUARE color: BLACK posn: upper left").pprint() prints:: [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']] cstt|ƒj|ƒd|_dS)NT)r{r*rÉrÃ)rÇr•)r®rrrÉ»szFollowedBy.__init__TcCs(|jj|||d�\}}|dd…=||fS)N)rÛ)r•rà)rÇr”rÃrÛÚ_r¤rrrræ¿s zFollowedBy.parseImpl)T)rrrràrÉrær�rr)r®rr*¥s cs,eZdZdZd ‡fdd„ Zd dd„Z‡ZS) r2apLookbehind matching of the given parse expression. ``PrecededBy`` does not advance the parsing position within the input string, it only verifies that the specified parse expression matches prior to the current position. ``PrecededBy`` always returns a null token list, but if a results name is defined on the given expression, it is returned. Parameters: - expr - expression that must match prior to the current parse location - retreat - (default= ``None``) - (int) maximum number of characters to lookbehind prior to the current parse location If the lookbehind expression is a string, Literal, Keyword, or a Word or CharsNotIn with a specified exact or maximum length, then the retreat parameter is not required. Otherwise, retreat must be specified to give a maximum number of characters to look back from the current parse position for a lookbehind match. Example:: # VB-style variable names with type prefixes int_var = PrecededBy("#") + pyparsing_common.identifier str_var = PrecededBy("$") + pyparsing_common.identifier NcsÎtt|ƒj|ƒ|jƒjƒ|_d|_d|_d|_t|t ƒrJt |ƒ}d|_nVt|t t fƒrf|j }d|_n:t|ttfƒrŒ|jtkrŒ|j}d|_nt|tƒr d}d|_||_dt |ƒ|_d|_|jjdd„ƒdS)NTFrznot preceded by cSs|jtddƒƒS)N)r3r$)rªr»r˜rrrr™ùsz%PrecededBy.__init__..)r{r2rÉr•rKrÃrÈrªršrœrÒr1r.rƒrLr%r rzrÜÚretreatrÉrÀr»rí)rÇr•r )r®rrrÉäs*  zPrecededBy.__init__rTc Csä|jr<||jkrt|||jƒ‚||j}|jj||ƒ\}}n |jtƒ}|td||jƒ|…}t|||jƒ} xltdt ||jdƒdƒD]J} y|j|t |ƒ| ƒ\}}Wn&t k rÐ} z | } WYdd} ~ XqŠXPqŠW| ‚||fS)Nrr”) rªr r<rÉr•ràrFr©r)r¨rÒr:) rÇr”rÃrÛr’r r¤Ú test_exprÚinstring_sliceÚ last_exprrVÚpberrrræûs     zPrecededBy.parseImpl)N)rT)rrrràrÉrær�rr)r®rr2Èscs2eZdZdZ‡fdd„Zd dd„Zdd„Z‡ZS) r5a¹Lookahead to disallow matching with the given parse expression. ``NotAny`` does *not* advance the parsing position within the input string, it only verifies that the specified parse expression does *not* match at the current position. Also, ``NotAny`` does *not* skip over leading whitespace. ``NotAny`` always returns a null token list. May be constructed using the '~' operator. Example:: AND, OR, NOT = map(CaselessKeyword, "AND OR NOT".split()) # take care not to mistake keywords for identifiers ident = ~(AND | OR | NOT) + Word(alphas) boolean_term = Optional(NOT) + ident # very crude boolean expression - to support parenthesis groups and # operation hierarchy, use infixNotation boolean_expr = boolean_term + ZeroOrMore((AND | OR) + boolean_term) # integers that are followed by "." are actually floats integer = Word(nums) + ~Char(".") cs0tt|ƒj|ƒd|_d|_dt|jƒ|_dS)NFTzFound unwanted token, )r{r5rÉrÀrÃr¥r•rÉ)rÇr•)r®rrrÉ*szNotAny.__init__TcCs&|jj||ƒrt|||j|ƒ‚|gfS)N)r•rÿr<rÉ)rÇr”rÃrÛrrrræ1szNotAny.parseImplcCs4t|dƒr|jS|jdkr.dt|jƒd|_|jS)Nrz~{rë)r;rr½r¥r•)rÇrrrrÔ6s   zNotAny.__str__)T)rrrràrÉrærÔr�rr)r®rr5s  cs>eZdZd ‡fdd„ Zdd„Zd dd„Zd‡fd d „ Z‡ZS)Ú_MultipleMatchNcs<tt|ƒj|ƒd|_|}t|tƒr.|j|ƒ}|j|ƒdS)NT)r{rrÉr¿ršrr·ÚstopOn)rÇr•rÚender)r®rrrÉ@s   z_MultipleMatch.__init__cCs,t|tƒr|j|ƒ}|dk r"|nd|_|S)N)ršrr·Ú not_ender)rÇrrrrrHs  z_MultipleMatch.stopOnTc CsÂ|jj}|j}|jdk }|r$|jj}|r2|||ƒ||||dd�\}}yZ|j } xJ|rb|||ƒ| rr|||ƒ} n|} ||| |ƒ\}} | s’| jƒrT|| 7}qTWWnttfk r¸YnX||fS)NF)rÜ) r•ràrírrþrÅrCr<r") rÇr”rÃrÛÚself_expr_parseÚself_skip_ignorablesÚ check_enderÚ try_not_enderrúÚhasIgnoreExprsrøÚ tmptokensrrrræNs,      z_MultipleMatch.parseImplFcsjtjrXxP|jgt|jdgƒD]6}t|tƒr|jrtjdj d|t |ƒj |jƒdd�qWt t |ƒj||ƒS)Nrâz]{0}: setting results name {1!r} on {2} expression collides with {3!r} on contained expressionrr‘)r0)rrr•r°ršrAr¾r3r4rîrÞrr{rrÓ)rÇrrÔrë)r®rrrÓks z_MultipleMatch._setResultsName)N)T)F)rrrrÉrrærÓr�rr)r®rr?s rc@seZdZdZdd„ZdS)r6ajRepetition of one or more of the given expression. Parameters: - expr - expression that must match one or more times - stopOn - (default= ``None``) - expression for a terminating sentinel (only required if the sentinel would ordinarily match the repetition expression) Example:: data_word = Word(alphas) label = data_word + FollowedBy(':') attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join)) text = "shape: SQUARE posn: upper left color: BLACK" OneOrMore(attr_expr).parseString(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']] # use stopOn attribute for OneOrMore to avoid reading label string as part of the data attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) OneOrMore(attr_expr).parseString(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] # could also be written as (attr_expr * (1,)).parseString(text).pprint() cCs4t|dƒr|jS|jdkr.dt|jƒd|_|jS)Nrrêz}...)r;rr½r¥r•)rÇrrrrÔ“s   zOneOrMore.__str__N)rrrràrÔrrrrr6yscs8eZdZdZd ‡fdd„ Zd ‡fdd„ Zdd „Z‡ZS) rOakOptional repetition of zero or more of the given expression. Parameters: - expr - expression that must match zero or more times - stopOn - (default= ``None``) - expression for a terminating sentinel (only required if the sentinel would ordinarily match the repetition expression) Example: similar to :class:`OneOrMore` Ncstt|ƒj||d�d|_dS)N)rT)r{rOrÉrÃ)rÇr•r)r®rrrɧszZeroOrMore.__init__Tc s6ytt|ƒj|||ƒSttfk r0|gfSXdS)N)r{rOrær<r")rÇr”rÃrÛ)r®rrræ«szZeroOrMore.parseImplcCs4t|dƒr|jS|jdkr.dt|jƒd|_|jS)Nrr]z]...)r;rr½r¥r•)rÇrrrrÔ±s   zZeroOrMore.__str__)N)T)rrrràrÉrærÔr�rr)r®rrOœs c@s eZdZdd„ZeZdd„ZdS)Ú _NullTokencCsdS)NFr)rÇrrrr6¼sz_NullToken.__bool__cCsdS)Nr¶r)rÇrrrrÔ¿sz_NullToken.__str__N)rrrr6rŒrÔrrrrr»srcs<eZdZdZeƒZef‡fdd„ Zd dd„Zdd„Z‡Z S) r8aGOptional matching of the given expression. Parameters: - expr - expression that must match zero or more times - default (optional) - value to be returned if the optional expression is not found. Example:: # US postal code can be a 5-digit zip, plus optional 4-digit qualifier zip = Combine(Word(nums, exact=5) + Optional('-' + Word(nums, exact=4))) zip.runTests(''' # traditional ZIP code 12345 # ZIP+4 form 12101-0001 # invalid ZIP 98765- ''') prints:: # traditional ZIP code 12345 ['12345'] # ZIP+4 form 12101-0001 ['12101-0001'] # invalid ZIP 98765- ^ FAIL: Expected end of text (at char 5), (line:1, col:6) cs.tt|ƒj|dd�|jj|_||_d|_dS)NF)rÎT)r{r8rÉr•r¿rJrÃ)rÇr•rD)r®rrrÉés zOptional.__init__Tc Cs|y|jj|||dd�\}}WnVttfk rr|j|jk rj|jjr`t|jgƒ}|j||jj<qn|jg}ng}YnX||fS)NF)rÜ)r•ràr<r"rJÚ_Optional__optionalNotMatchedr¾r?)rÇr”rÃrÛrúrrrræïs    zOptional.parseImplcCs4t|dƒr|jS|jdkr.dt|jƒd|_|jS)Nrr]r^)r;rr½r¥r•)rÇrrrrÔýs   zOptional.__str__)T) rrrràrrrÉrærÔr�rr)r®rr8Âs $ cs,eZdZdZd ‡fdd„ Zd dd„Z‡ZS) rEaø Token for skipping over all undefined text until the matched expression is found. Parameters: - expr - target expression marking the end of the data to be skipped - include - (default= ``False``) if True, the target expression is also parsed (the skipped text and target expression are returned as a 2-element list). - ignore - (default= ``None``) used to define grammars (typically quoted strings and comments) that might contain false matches to the target expression - failOn - (default= ``None``) define expressions that are not allowed to be included in the skipped test; if found before the target expression is found, the SkipTo is not a match Example:: report = ''' Outstanding Issues Report - 1 Jan 2000 # | Severity | Description | Days Open -----+----------+-------------------------------------------+----------- 101 | Critical | Intermittent system crash | 6 94 | Cosmetic | Spelling error on Login ('log|n') | 14 79 | Minor | System slow when running too many reports | 47 ''' integer = Word(nums) SEP = Suppress('|') # use SkipTo to simply match everything up until the next SEP # - ignore quoted strings, so that a '|' character inside a quoted string does not match # - parse action will call token.strip() for each matched token, i.e., the description body string_data = SkipTo(SEP, ignore=quotedString) string_data.setParseAction(tokenMap(str.strip)) ticket_expr = (integer("issue_num") + SEP + string_data("sev") + SEP + string_data("desc") + SEP + integer("days_open")) for tkt in ticket_expr.searchString(report): print tkt.dump() prints:: ['101', 'Critical', 'Intermittent system crash', '6'] - days_open: 6 - desc: Intermittent system crash - issue_num: 101 - sev: Critical ['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14'] - days_open: 14 - desc: Spelling error on Login ('log|n') - issue_num: 94 - sev: Cosmetic ['79', 'Minor', 'System slow when running too many reports', '47'] - days_open: 47 - desc: System slow when running too many reports - issue_num: 79 - sev: Minor FNcs`tt|ƒj|ƒ||_d|_d|_||_d|_t|t ƒrF|j |ƒ|_ n||_ dt |j ƒ|_dS)NTFzNo match found for )r{rErÉÚ ignoreExprrÃrÈÚ includeMatchr¿ršrr·ÚfailOnr¥r•rÉ)rÇrSÚincluderNr)r®rrrÉ@s zSkipTo.__init__Tc Cs,|}t|ƒ}|j}|jj}|jdk r,|jjnd}|jdk rB|jjnd} |} xœ| |krÖ|dk rh||| ƒrhP| dk rœx*y| || ƒ} Wqrtk r–PYqrXqrWy||| ddd�Wn tt fk rÐ| d7} YqLXPqLWt|||j |ƒ‚| }|||…} t | ƒ} |j �r$||||dd�\}} | | 7} || fS)NF)rÛrÜr”)rÜ) rÒr•ràrrÿrrþr:r<r"rÉr?r)rÇr”rÃrÛr—rïr•Ú expr_parseÚself_failOn_canParseNextÚself_ignoreExpr_tryParseÚtmplocÚskiptextÚ skipresultr—rrrræMs<    zSkipTo.parseImpl)FNN)T)rrrràrÉrær�rr)r®rrEs9 csneZdZdZd‡fdd„ Zdd„Zdd„Zd d „Zd d „Zdd d„Z dd„Z ‡fdd„Z d‡fdd„ Z ‡Z S)r+a_Forward declaration of an expression to be defined later - used for recursive grammars, such as algebraic infix notation. When the expression is known, it is assigned to the ``Forward`` variable using the '<<' operator. Note: take care when assigning to ``Forward`` not to overlook precedence of operators. Specifically, '|' has a lower precedence than '<<', so that:: fwdExpr << a | b | c will actually be evaluated as:: (fwdExpr << a) | b | c thereby leaving b and c out as parseable alternatives. It is recommended that you explicitly group the values inserted into the ``Forward``:: fwdExpr << (a | b | c) Converting to use the '<<=' operator instead will avoid this problem. See :class:`ParseResults.pprint` for an example of a recursive parser created using ``Forward``. Ncstt|ƒj|dd�dS)NF)rÎ)r{r+rÉ)rÇrS)r®rrrÉ—szForward.__init__cCsjt|tƒr|j|ƒ}||_d|_|jj|_|jj|_|j|jjƒ|jj |_ |jj |_ |j j |jj ƒ|S)N) ršrr·r•r½rÈrÃrLrÁrÀr¿rÅrO)rÇrSrrrÚ __lshift__šs      zForward.__lshift__cCs||>S)Nr)rÇrSrrrÚ __ilshift__§szForward.__ilshift__cCs d|_|S)NF)rÀ)rÇrrrrKªszForward.leaveWhitespacecCs$|js d|_|jdk r |jjƒ|S)NT)rÇr•r)rÇrrrr®s   zForward.streamlinecCsJ|dkr g}||kr<|dd…|g}|jdk r<|jj|ƒ|jgƒdS)N)r•rVrT)rÇrUrãrrrrVµs  zForward.validatec Cslt|dƒr|jS|jdk r |jSd|_d}z&|jdk rJt|jƒdd…}nd}Wd|jjd||_X|jS)Nrz: ...z...ièÚNonez: )r;rr½r•r¥r®r)rÇÚ retStringrrrrÔ¿s   zForward.__str__cs.|jdk rtt|ƒjƒStƒ}||K}|SdS)N)r•r{r+rR)rÇr¤)r®rrrRÓs  z Forward.copyFcs@tjr.|jdkr.tjdjd|t|ƒjƒdd�tt |ƒj ||ƒS)NzR{0}: setting results name {0!r} on {1} expression that has no contained expressionrr‘)r0) rrr•r3r4rîrÞrr{r+rÓ)rÇrrÔ)r®rrrÓÛs  zForward._setResultsName)N)N)F)rrrràrÉr'r(rKrrVrÔrRrÓr�rr)r®rr+|s   cs"eZdZdZd‡fdd„ Z‡ZS)rJzW Abstract subclass of :class:`ParseExpression`, for converting parsed results. Fcstt|ƒj|ƒd|_dS)NF)r{rJrÉr¿)rÇr•rÎ)r®rrrÉêszTokenConverter.__init__)F)rrrràrÉr�rr)r®rrJæscs6eZdZdZd ‡fdd„ Z‡fdd„Zdd „Z‡ZS) r&aÕConverter to concatenate all matching tokens to a single string. By default, the matching patterns must also be contiguous in the input string; this can be disabled by specifying ``'adjacent=False'`` in the constructor. Example:: real = Word(nums) + '.' + Word(nums) print(real.parseString('3.1416')) # -> ['3', '.', '1416'] # will also erroneously match the following print(real.parseString('3. 1416')) # -> ['3', '.', '1416'] real = Combine(Word(nums) + '.' + Word(nums)) print(real.parseString('3.1416')) # -> ['3.1416'] # no match when there are internal spaces print(real.parseString('3. 1416')) # -> Exception: Expected W:(0123...) r¶Tcs8tt|ƒj|ƒ|r|jƒ||_d|_||_d|_dS)NT)r{r&rÉrKÚadjacentrÀÚ joinStringrÌ)rÇr•r,r+)r®rrrÉszCombine.__init__cs(|jrtj||ƒntt|ƒj|ƒ|S)N)r+rArNr{r&)rÇrS)r®rrrN szCombine.ignorecCsP|jƒ}|dd…=|tdj|j|jƒƒg|jd�7}|jrH|jƒrH|gS|SdS)Nr¶)r)rRr?r×r_r,rÊr¾rC)rÇr”rÃrñÚretToksrrrròs  "zCombine.postParse)r¶T)rrrràrÉrNròr�rr)r®rr&îs cs(eZdZdZ‡fdd„Zdd„Z‡ZS)r-aConverter to return the matched tokens as a list - useful for returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions. Example:: ident = Word(alphas) num = Word(nums) term = ident | num func = ident + Optional(delimitedList(term)) print(func.parseString("fn a, b, 100")) # -> ['fn', 'a', 'b', '100'] func = ident + Group(Optional(delimitedList(term))) print(func.parseString("fn a, b, 100")) # -> ['fn', ['a', 'b', '100']] cstt|ƒj|ƒd|_dS)NT)r{r-rÉr¿)rÇr•)r®rrrÉ*szGroup.__init__cCs|gS)Nr)rÇr”rÃrñrrrrò.szGroup.postParse)rrrràrÉròr�rr)r®rr-s cs(eZdZdZ‡fdd„Zdd„Z‡ZS)r'a?Converter to return a repetitive expression as a list, but also as a dictionary. Each element can also be referenced using the first token in the expression as its key. Useful for tabular report scraping when the first column can be used as a item key. Example:: data_word = Word(alphas) label = data_word + FollowedBy(':') attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join)) text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) # print attributes as plain groups print(OneOrMore(attr_expr).parseString(text).dump()) # instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names result = Dict(OneOrMore(Group(attr_expr))).parseString(text) print(result.dump()) # access named fields as dict entries, or output as dict print(result['shape']) print(result.asDict()) prints:: ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap'] [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: light blue - posn: upper left - shape: SQUARE - texture: burlap SQUARE {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'} See more examples at :class:`ParseResults` of accessing fields by results name. cstt|ƒj|ƒd|_dS)NT)r{r'rÉr¿)rÇr•)r®rrrÉXsz Dict.__init__cCsôxÞt|ƒD]Ò\}}t|ƒdkr q |d}t|tƒrBt|dƒjƒ}t|ƒdkr^td|ƒ||<q t|ƒdkrŽt|dtƒ rŽt|d|ƒ||<q |jƒ}|d=t|ƒdksºt|tƒrÊ|j ƒrÊt||ƒ||<q t|d|ƒ||<q W|j rì|gS|SdS)Nrr”r¶r“) ròrÒršr—r¥rØrr?rRrCr¾)rÇr”rÃrñrüÚtokÚikeyÚ dictvaluerrrrò\s$   zDict.postParse)rrrràrÉròr�rr)r®rr'1s& c@s eZdZdZdd„Zdd„ZdS)rHa[Converter for ignoring the results of a parsed expression. Example:: source = "a, b, c,d" wd = Word(alphas) wd_list1 = wd + ZeroOrMore(',' + wd) print(wd_list1.parseString(source)) # often, delimiters that are useful during parsing are just in the # way afterward - use Suppress to keep them out of the parsed output wd_list2 = wd + ZeroOrMore(Suppress(',') + wd) print(wd_list2.parseString(source)) prints:: ['a', ',', 'b', ',', 'c', ',', 'd'] ['a', 'b', 'c', 'd'] (See also :class:`delimitedList`.) cCsgS)Nr)rÇr”rÃrñrrrrò‹szSuppress.postParsecCs|S)Nr)rÇrrrrJŽszSuppress.suppressN)rrrràròrJrrrrrHusc@s(eZdZdZdd„Zdd„Zdd„ZdS) r7zDWrapper for parse actions, to ensure they are only called once. cCst|ƒ|_d|_dS)NF)rÀrãÚcalled)rÇÚ methodCallrrrrÉ•s zOnlyOnce.__init__cCs.|js|j|||ƒ}d|_|St||dƒ‚dS)NTr¶)r1rãr<)rÇrªr»r˜r˜rrrrI˜s zOnlyOnce.__call__cCs d|_dS)NF)r1)rÇrrrÚresetžszOnlyOnce.resetN)rrrràrÉrIr3rrrrr7’sc s:tˆƒ‰‡fdd„}y ˆj|_Wntk r4YnX|S)aqDecorator for debugging parse actions. When the parse action is called, this decorator will print ``">> entering method-name(line:, , )"``. When the parse action completes, the decorator will print ``"<<"`` followed by the returned value, or any exception that the parse action raised. Example:: wd = Word(alphas) @traceParseAction def remove_duplicate_chars(tokens): return ''.join(sorted(set(''.join(tokens)))) wds = OneOrMore(wd).setParseAction(remove_duplicate_chars) print(wds.parseString("slkdjs sld sldd sdlf sdljf")) prints:: >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {})) <>entering %s(line: '%s', %d, %r) z<.z)rÀrrÎ)r\r8r)r\rr€¡s  ú,cCs`t|ƒdt|ƒdt|ƒd}|rBt|t||ƒƒj|ƒS|tt|ƒ|ƒj|ƒSdS)aÎHelper to define a delimited list of expressions - the delimiter defaults to ','. By default, the list elements and delimiters can have intervening whitespace, and comments, but this can be overridden by passing ``combine=True`` in the constructor. If ``combine`` is set to ``True``, the matching tokens are returned as a single token string, with the delimiters included; otherwise, the matching tokens are returned as a list of tokens, with the delimiters suppressed. Example:: delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc'] delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE'] z [rãz]...N)r¥r&rOrÒrH)r•ÚdelimÚcombineÚdlNamerrrr^Ñs$csjtƒ‰‡‡fdd„}|dkr0ttƒjdd„ƒ}n|jƒ}|jdƒ|j|dd�|ˆjd tˆƒd ƒS) a>Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. If ``intExpr`` is specified, it should be a pyparsing expression that produces an integer value. Example:: countedArray(Word(alphas)).parseString('2 ab cd ef') # -> ['ab', 'cd'] # in this parser, the leading integer value is given in binary, # '10' indicating that 2 values are in the array binaryConstant = Word('01').setParseAction(lambda t: int(t[0], 2)) countedArray(Word(alphas), intExpr=binaryConstant).parseString('10 ab cd ef') # -> ['ab', 'cd'] cs.|d}ˆ|r ttˆg|ƒƒp&ttƒ>gS)Nr)r-r"ra)rªr»r˜r9)Ú arrayExprr•rrÚcountFieldParseActionþs"z+countedArray..countFieldParseActionNcSs t|dƒS)Nr)r—)r˜rrrr™szcountedArray..ÚarrayLenT)rÍz(len) z...)r+rLrpr¡rRrÒrçr¥)r•ÚintExprr>r)r=r•rrZæs cCs:g}x0|D](}t|tƒr(|jt|ƒƒq |j|ƒq W|S)N)ršrrOr)rí)ÚLr¤rürrrr) s   r)cs6tƒ‰‡fdd„}|j|dd�ˆjdt|ƒƒˆS)a4Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = matchPreviousLiteral(first) matchExpr = first + ":" + second will match ``"1:1"``, but not ``"1:2"``. Because this matches a previous literal, will also match the leading ``"1:1"`` in ``"1:10"``. If this is not desired, use :class:`matchPreviousExpr`. Do *not* use with packrat parsing enabled. csP|rBt|ƒdkrˆ|d>qLt|jƒƒ}ˆtdd„|Dƒƒ>n ˆtƒ>dS)Nr”rcss|]}t|ƒVqdS)N)r1)rÚttrrrr§*szDmatchPreviousLiteral..copyTokenToRepeater..)rÒr)rr"r))rªr»r˜Útflat)ÚreprrÚcopyTokenToRepeater#s   z1matchPreviousLiteral..copyTokenToRepeaterT)rÍz(prev) )r+rçrÒr¥)r•rEr)rDrrms  csFtƒ‰|jƒ}ˆ|K‰‡fdd„}|j|dd�ˆjdt|ƒƒˆS)aTHelper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = matchPreviousExpr(first) matchExpr = first + ":" + second will match ``"1:1"``, but not ``"1:2"``. Because this matches by expressions, will *not* match the leading ``"1:1"`` in ``"1:10"``; the expressions are evaluated first, and then compared, so ``"1"`` is compared with ``"10"``. Do *not* use with packrat parsing enabled. cs*t|jƒƒ‰‡fdd„}ˆj|dd�dS)Ncs$t|jƒƒ}|ˆkr tdddƒ‚dS)Nr¶r)r)rr<)rªr»r˜Ú theseTokens)Ú matchTokensrrÚmustMatchTheseTokensEs zLmatchPreviousExpr..copyTokenToRepeater..mustMatchTheseTokensT)rÍ)r)rr¡)rªr»r˜rH)rD)rGrrECs  z.matchPreviousExpr..copyTokenToRepeaterT)rÍz(prev) )r+rRrçrÒr¥)r•Úe2rEr)rDrrl1s cCs>xdD]}|j|t|ƒ}qW|jddƒ}|jddƒ}t|ƒS)Nz\^-[]rêz\nrÎz\t)r­Ú_bslashr¥)rªr¹rrrr¢Ns    r¢c sút|tƒrtjddd�|r:dd„}dd„}|r4tnt‰ndd„}dd„}|rRtnt‰g}t|tƒrn|jƒ}n$t|t ƒr‚t |ƒ}ntjd t dd�|sœt ƒS|�s4d }xŒ|t |ƒd k�r2||}xlt||d d …ƒD]L\} } || |ƒ�rþ||| d =PqØ||| ƒrØ||| d =|j|| ƒPqØW|d 7}q¨W|�p<| �rØ|�rØyht |ƒt d j|ƒƒk�rŠtdd jdd„|Dƒƒƒjdj|ƒƒStdjdd„|Dƒƒƒjdj|ƒƒSWn&tk �rÖtjdt dd�YnXt‡fdd„|Dƒƒjdj|ƒƒS)aƒHelper to quickly define a set of alternative Literals, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a :class:`MatchFirst` for best performance. Parameters: - strs - a string of space-delimited literals, or a collection of string literals - caseless - (default= ``False``) - treat all literals as caseless - useRegex - (default= ``True``) - as an optimization, will generate a Regex object; otherwise, will generate a :class:`MatchFirst` object (if ``caseless=True`` or ``asKeyword=True``, or if creating a :class:`Regex` raises an exception) - asKeyword - (default=``False``) - enforce Keyword-style matching on the generated expressions Example:: comp_oper = oneOf("< = > <= >= !=") var = Word(alphas) number = Word(nums) term = var | number comparison_expr = term + comp_oper + term print(comparison_expr.searchString("B = 12 AA=23 B<=AA AA>12")) prints:: [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']] z_More than one string argument passed to oneOf, pass choices as a list or space-delimited stringr“)r0cSs|jƒ|jƒkS)N)r‰)rUÚbrrrr™{szoneOf..cSs|jƒj|jƒƒS)N)r‰r)rUrKrrrr™|scSs||kS)Nr)rUrKrrrr™scSs |j|ƒS)N)r)rUrKrrrr™€sz6Invalid argument to oneOf, expected string or iterablerr”Nr¶z[%s]css|]}t|ƒVqdS)N)r¢)rÚsymrrrr§£szoneOf..z | ú|css|]}tj|ƒVqdS)N)r�r¤)rrLrrrr§¥sz7Exception creating Regex for oneOf, building MatchFirstc3s|]}ˆ|ƒVqdS)Nr)rrL)ÚparseElementClassrrr§«s)ršrr3r4r#r$r.r1r«r rr5r4rÒròrKr×rDrÒrˆr3) ÚstrsrˆÚuseRegexr¡ÚisequalÚmasksÚsymbolsrüÚcurr0rSr)rNrrqVsR           ((cCsttt||ƒƒƒS)aéHelper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the :class:`Dict`, :class:`ZeroOrMore`, and :class:`Group` tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the :class:`Dict` results can include named token fields. Example:: text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) print(OneOrMore(attr_expr).parseString(text).dump()) attr_label = label attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join) # similar to Dict, but simpler call format result = dictOf(attr_label, attr_value).parseString(text) print(result.dump()) print(result['shape']) print(result.shape) # object attribute access works too print(result.asDict()) prints:: [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: light blue - posn: upper left - shape: SQUARE - texture: burlap SQUARE SQUARE {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} )r'r6r-)rIr1rrrr_­s%cCs^tƒjdd„ƒ}|jƒ}d|_|dƒ||dƒ}|r@dd„}ndd„}|j|ƒ|j|_|S) a—Helper to return the original, untokenized text for a given expression. Useful to restore the parsed fields of an HTML start tag into the raw tag text itself, or to revert separate tokens with intervening whitespace back to the original matching input text. By default, returns astring containing the original parsed text. If the optional ``asString`` argument is passed as ``False``, then the return value is a :class:`ParseResults` containing any results names that were originally matched, and a single token containing the original matched text from the input string. So if the expression passed to :class:`originalTextFor` contains expressions with defined results names, you must set ``asString`` to ``False`` if you want to preserve those results name values. Example:: src = "this is test bold text normal text " for tag in ("b", "i"): opener, closer = makeHTMLTags(tag) patt = originalTextFor(opener + SkipTo(closer) + closer) print(patt.searchString(src)[0]) prints:: [' bold text '] ['text'] cSs|S)Nr)rªrÃr˜rrrr™ñsz!originalTextFor..FÚ_original_startÚ _original_endcSs||j|j…S)N)rUrV)rªr»r˜rrrr™öscSs&||jdƒ|jdƒ…g|dd…<dS)NrUrV)rH)rªr»r˜rrrÚ extractTextøsz$originalTextFor..extractText)r)r¡rRrÌrÅ)r•ÚasStringÚ locMarkerÚ endlocMarkerÚ matchExprrWrrrr…Ôs  cCst|ƒjdd„ƒS)zkHelper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty. cSs|dS)Nrr)r˜rrrr™szungroup..)rJrç)r•rrrr†þscCs4tƒjdd„ƒ}t|dƒ|dƒ|jƒjƒdƒƒS)a±Helper to decorate a returned token with its starting and ending locations in the input string. This helper adds the following results names: - locn_start = location where matched expression begins - locn_end = location where matched expression ends - value = the actual parsed results Be careful if the input text contains ```` characters, you may want to call :class:`ParserElement.parseWithTabs` Example:: wd = Word(alphas) for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"): print(match) prints:: [[0, 'ljsdf', 5]] [[8, 'lksdjjf', 15]] [[18, 'lkkjj', 23]] cSs|S)Nr)rªr»r˜rrrr™szlocatedExpr..Ú locn_startr1Úlocn_end)r)r¡r-rRrK)r•Úlocatorrrrrˆsz\[]-*.$+^?()~ )rªcCs |ddS)Nrr”r)rªr»r˜rrrr™(sr™z\\0?[xX][0-9a-fA-F]+cCstt|djdƒdƒƒS)Nrz\0xrâ)Úunichrr—rk)rªr»r˜rrrr™)sz \\0[0-7]+cCstt|ddd…dƒƒS)Nrr”é)r_r—)rªr»r˜rrrr™*sz\]rär]räÚnegateÚbodyr^c sBdd„‰y dj‡fdd„tj|ƒjDƒƒStk r<dSXdS)aHelper to easily define string ranges for use in Word construction. Borrows syntax from regexp '[]' string range definitions:: srange("[0-9]") -> "0123456789" srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" The input string must be enclosed in []'s, and the returned string is the expanded character set joined into a single string. The values enclosed in the []'s may be: - a single character - an escaped character with a leading backslash (such as ``\-`` or ``\]``) - an escaped hex character with a leading ``'\x'`` (``\x21``, which is a ``'!'`` character) (``\0x##`` is also supported for backwards compatibility) - an escaped octal character with a leading ``'\0'`` (``\041``, which is a ``'!'`` character) - a range of any of the above, separated by a dash (``'a-z'``, etc.) - any combination of the above (``'aeiouy'``, ``'a-zA-Z0-9_$'``, etc.) cSs<t|tƒs|Sdjdd„tt|dƒt|dƒdƒDƒƒS)Nr¶css|]}t|ƒVqdS)N)r_)rr¹rrrr§Isz+srange....rr”)ršr?r×r)Úord)Úprrrr™Iszsrange..r¶c3s|]}ˆ|ƒVqdS)Nr)rÚpart)Ú _expandedrrr§Kszsrange..N)r×Ú_reBracketExprrrbrˆ)rªr)rfrr}/s  cs‡fdd„}|S)zoHelper method for defining parse actions that require matching at a specific column in the input text. cs"t||ƒˆkrt||dˆƒ‚dS)Nzmatched token not at column %d)rWr<)rŽÚlocnr™)r9rrÚ verifyColSsz!matchOnlyAtCol..verifyColr)r9rir)r9rrkOs cs ‡fdd„S)aµHelper method for common parse actions that simply return a literal value. Especially useful when used with :class:`transformString` (). Example:: num = Word(nums).setParseAction(lambda toks: int(toks[0])) na = oneOf("N/A NA").setParseAction(replaceWith(math.nan)) term = na | num OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234] csˆgS)Nr)rªr»r˜)ÚreplStrrrr™eszreplaceWith..r)rjr)rjrrzXs cCs|ddd…S)aHelper parse action for removing quotation marks from parsed quoted strings. Example:: # by default, quotation marks are included in parsed results quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] # use removeQuotes to strip quotation marks from parsed results quotedString.setParseAction(removeQuotes) quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"] rr”r•r)rªr»r˜rrrrxgs c sN‡‡fdd„}ytˆdtˆdƒjƒ}Wntk rBtˆƒ}YnX||_|S)aLHelper to define a parse action by mapping a function to all elements of a ParseResults list. If any additional args are passed, they are forwarded to the given function as additional arguments after the token, as in ``hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))``, which will convert the parsed data to an integer using base 16. Example (compare the last to example in :class:`ParserElement.transformString`:: hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16)) hex_ints.runTests(''' 00 11 22 aa FF 0a 0d 1a ''') upperword = Word(alphas).setParseAction(tokenMap(str.upper)) OneOrMore(upperword).runTests(''' my kingdom for a horse ''') wd = Word(alphas).setParseAction(tokenMap(str.title)) OneOrMore(wd).setParseAction(' '.join).runTests(''' now is the winter of our discontent made glorious summer by this sun of york ''') prints:: 00 11 22 aa FF 0a 0d 1a [0, 17, 34, 170, 255, 10, 13, 26] my kingdom for a horse ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE'] now is the winter of our discontent made glorious summer by this sun of york ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York'] cs‡‡fdd„|DƒS)Ncsg|]}ˆ|fˆžŽ‘qSrr)rÚtokn)rÆrœrrr›sz(tokenMap..pa..r)rªr»r˜)rÆrœrrr¿šsztokenMap..parr®)r°rrˆrœ)rœrÆr¿r³r)rÆrœrr‹vs$cCs t|ƒjƒS)N)r¥r‰)r˜rrrr™¦scCs t|ƒjƒS)N)r¥Úlower)r˜rrrr™ªsrhrics~t|tƒr|‰t|| d�}n|j‰tttdƒ}|rŽtjƒj t ƒ}||dƒt t t |tdƒ|ƒƒƒtddgd�dƒj d d „ƒ|}nltjƒj t ƒttd d �B}||dƒt t t |j tƒttdƒ|ƒƒƒƒtddgd�dƒj d d „ƒ|}ttdƒ|d dd�}|jdˆƒ|j‡fdd „ƒ|ddjˆjddƒjƒjƒƒƒjdˆƒ}ˆ|_ˆ|_t|ƒƒ|_||fS)zRInternal helper to construct opening and closing tag expressions, given a tag name)rˆz_-:Útagú=ú/F)rDracSs |ddkS)Nrror)rªr»r˜rrrr™¾sz_makeTags..ri)r™cSs |ddkS)Nrror)rªr»r˜rrrr™Æszcs*|jddjˆjddƒjƒjƒƒ|jƒƒS)Nr’r¶ú:rã)r(r×r­Útitler«rR)r˜)Úresnamerrr™Ìsr¯r¶rprãz)ršrr.rrLrRrQr\rRr¡rxr'rOr-rHr8rwrtr`r&Ú_LrÒrçr×r­rqr«rmrEÚtag_body)ÚtagStrÚxmlÚ suppress_LTÚ suppress_GTÚ tagAttrNameÚ tagAttrValueÚopenTagÚcloseTagr)rrrÚ _makeTags®s$ JR, r}cCs t|dƒS)aKHelper to construct opening and closing tag expressions for HTML, given a tag name. Matches tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values. Example:: text = 'More info at the pyparsing wiki page' # makeHTMLTags returns pyparsing expressions for the opening and # closing tags as a 2-tuple a, a_end = makeHTMLTags("A") link_expr = a + SkipTo(a_end)("link_text") + a_end for link in link_expr.searchString(text): # attributes in the tag (like "href" shown here) are # also accessible as named results print(link.link_text, '->', link.href) prints:: pyparsing -> https://github.com/pyparsing/pyparsing/wiki F)r})rurrrriÓscCs t|dƒS)z»Helper to construct opening and closing tag expressions for XML, given a tag name. Matches tags only in the given upper/lower case. Example: similar to :class:`makeHTMLTags` T)r})rurrrrjëscs8|r|dd…‰n|jƒ‰dd„ˆDƒ‰‡fdd„}|S)a7Helper to create a validating parse action to be used with start tags created with :class:`makeXMLTags` or :class:`makeHTMLTags`. Use ``withAttribute`` to qualify a starting tag with a required attribute value, to avoid false matches on common tags such as ```` or ``
``. Call ``withAttribute`` with a series of attribute names and values. Specify the list of filter attributes names and values as: - keyword arguments, as in ``(align="right")``, or - as an explicit dict with ``**`` operator, when an attribute name is also a Python reserved word, as in ``**{"class":"Customer", "align":"right"}`` - a list of name-value tuples, as in ``(("ns1:class", "Customer"), ("ns2:align", "right"))`` For attribute names with a namespace prefix, you must use the second form. Attribute names are matched insensitive to upper/lower case. If just testing for ``class`` (with or without a namespace), use :class:`withClass`. To verify that the attribute exists, but without specifying a value, pass ``withAttribute.ANY_VALUE`` as the value. Example:: html = '''
Some text
1 4 0 1 0
1,3 2,3 1,1
this has no type
''' div,div_end = makeHTMLTags("div") # only match div tag having a type attribute with value "grid" div_grid = div().setParseAction(withAttribute(type="grid")) grid_expr = div_grid + SkipTo(div | div_end)("body") for grid_header in grid_expr.searchString(html): print(grid_header.body) # construct a match with any div tag having a type attribute, regardless of the value div_any_type = div().setParseAction(withAttribute(type=withAttribute.ANY_VALUE)) div_expr = div_any_type + SkipTo(div | div_end)("body") for div_header in div_expr.searchString(html): print(div_header.body) prints:: 1 4 0 1 0 1 4 0 1 0 1,3 2,3 1,1 NcSsg|]\}}||f‘qSrr)rr&r#rrrr/sz!withAttribute..cs^xXˆD]P\}}||kr&t||d|ƒ‚|tjkr|||krt||d||||fƒ‚qWdS)Nzno matching attribute z+attribute '%s' has value '%s', must be '%s')r<rƒÚ ANY_VALUE)rªr»rúÚattrNameÚ attrValue)Úattrsrrr¿0s zwithAttribute..pa)r,)rÆÚattrDictr¿r)r�rrƒós 8 cCs|r d|nd}tf||iŽS)aÉSimplified version of :class:`withAttribute` when matching on a div class - made difficult because ``class`` is a reserved word in Python. Example:: html = '''
Some text
1 4 0 1 0
1,3 2,3 1,1
this <div> has no class
''' div,div_end = makeHTMLTags("div") div_grid = div().setParseAction(withClass("grid")) grid_expr = div_grid + SkipTo(div | div_end)("body") for grid_header in grid_expr.searchString(html): print(grid_header.body) div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE)) div_expr = div_any_type + SkipTo(div | div_end)("body") for div_header in div_expr.searchString(html): print(div_header.body) prints:: 1 4 0 1 0 1 4 0 1 0 1,3 2,3 1,1 z%s:classÚclass)rƒ)Ú classnameÚ namespaceÚ classattrrrrr‰:s#ú(rÁcCs¶Gdd„dtƒ}tƒ}||||B}�x€t|ƒD�]r\}}|d dd…\} } } } | dkrdd| nd| } | dkr˜| dksˆt| ƒdkr�td ƒ‚| \}}tƒj| ƒ}| tjk�rx| d krÖ||| ƒt|t | ƒƒ}n | dk�r.| dk �r||| |ƒt|t | |ƒƒ}n|||ƒt|t |ƒƒ}nH| dk�rn||||||ƒt|t ||||ƒƒ}ntd ƒ‚nì| tj k�r\| d k�r¾t | t ƒ�s¢t | ƒ} || j |ƒt| |ƒ}nœ| dk�r| dk �rø||| |ƒt|t | |ƒƒ}n|||ƒt|t |ƒƒ}nD| dk�rR||||||ƒt|||||ƒ}ntd ƒ‚ntd ƒ‚| �r�t | ttfƒ�r†|j| Žn |j| ƒ||j| ƒ|BK}|}q2W||K}|S)al Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to operator expressions. The generated parser will also recognize the use of parentheses to override operator precedences (see example below). Note: if you define a deep operator list, you may see performance issues when using infixNotation. See :class:`ParserElement.enablePackrat` for a mechanism to potentially improve your parser performance. Parameters: - baseExpr - expression representing the most basic element for the nested - opList - list of tuples, one for each operator precedence level in the expression grammar; each tuple is of the form ``(opExpr, numTerms, rightLeftAssoc, parseAction)``, where: - opExpr is the pyparsing expression for the operator; may also be a string, which will be converted to a Literal; if numTerms is 3, opExpr is a tuple of two expressions, for the two operators separating the 3 terms - numTerms is the number of terms for this operator (must be 1, 2, or 3) - rightLeftAssoc is the indicator whether the operator is right or left associative, using the pyparsing-defined constants ``opAssoc.RIGHT`` and ``opAssoc.LEFT``. - parseAction is the parse action to be associated with expressions matching this operator expression (the parse action tuple member may be omitted); if the parse action is passed a tuple or list of functions, this is equivalent to calling ``setParseAction(*fn)`` (:class:`ParserElement.setParseAction`) - lpar - expression for matching left-parentheses (default= ``Suppress('(')``) - rpar - expression for matching right-parentheses (default= ``Suppress(')')``) Example:: # simple example of four-function arithmetic with ints and # variable names integer = pyparsing_common.signed_integer varname = pyparsing_common.identifier arith_expr = infixNotation(integer | varname, [ ('-', 1, opAssoc.RIGHT), (oneOf('* /'), 2, opAssoc.LEFT), (oneOf('+ -'), 2, opAssoc.LEFT), ]) arith_expr.runTests(''' 5+3*6 (5+3)*6 -2--11 ''', fullDump=False) prints:: 5+3*6 [[5, '+', [3, '*', 6]]] (5+3)*6 [[[5, '+', 3], '*', 6]] -2--11 [[['-', 2], '-', ['-', 11]]] c@seZdZddd„ZdS)zinfixNotation.._FBTcSs|jj||ƒ|gfS)N)r•rþ)rÇr”rÃrÛrrrræ­sz$infixNotation.._FB.parseImplN)T)rrrrærrrrÚ_FB¬srˆNr­r‘z%s termz %s%s termr“z@if numterms=3, opExpr must be a tuple or list of two expressionsr”z6operator must be unary (1), binary (2), or ternary (3)z2operator must indicate right or left associativity)N)r*r+ròrÒr<rÒrrÚLEFTr-r6ÚRIGHTršr8r•r;rr¡)ÚbaseExprÚopListÚlparÚrparrˆr¤ÚlastExprrüÚoperDefÚopExprÚarityÚrightLeftAssocr¿ÚtermNameÚopExpr1ÚopExpr2ÚthisExprr[rrrr‡dsZH    &        &    z4"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*ú"z string enclosed in double quotesz4'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*ú'z string enclosed in single quotesz*quotedString using single or double quotesÚuzunicode string literalcCsœ||krtdƒ‚|dk�r(t|tƒo,t|tƒ�r t|ƒdkr¦t|ƒdkr¦|dk r€tt|t||tjdd�ƒƒj dd„ƒ}n$t j ƒt||tjƒj dd„ƒ}nx|dk rêtt|t |ƒt |ƒttjdd�ƒƒj dd„ƒ}n4ttt |ƒt |ƒttjdd�ƒƒj d d„ƒ}ntd ƒ‚t ƒ}|dk �rb|tt|ƒt||B|Bƒt|ƒƒK}n$|tt|ƒt||Bƒt|ƒƒK}|jd ||fƒ|S) a— Helper method for defining nested lists enclosed in opening and closing delimiters ("(" and ")" are the default). Parameters: - opener - opening character for a nested list (default= ``"("``); can also be a pyparsing expression - closer - closing character for a nested list (default= ``")"``); can also be a pyparsing expression - content - expression for items within the nested lists (default= ``None``) - ignoreExpr - expression for ignoring opening and closing delimiters (default= :class:`quotedString`) If an expression is not provided for the content argument, the nested expression will capture all whitespace-delimited content between delimiters as a list of separate values. Use the ``ignoreExpr`` argument to define expressions that may contain opening or closing characters that should not be treated as opening or closing characters for nesting, such as quotedString or a comment expression. Specify multiple expressions using an :class:`Or` or :class:`MatchFirst`. The default is :class:`quotedString`, but if no expressions are to be ignored, then pass ``None`` for this argument. Example:: data_type = oneOf("void int short long char float double") decl_data_type = Combine(data_type + Optional(Word('*'))) ident = Word(alphas+'_', alphanums+'_') number = pyparsing_common.number arg = Group(decl_data_type + ident) LPAR, RPAR = map(Suppress, "()") code_body = nestedExpr('{', '}', ignoreExpr=(quotedString | cStyleComment)) c_function = (decl_data_type("type") + ident("name") + LPAR + Optional(delimitedList(arg), [])("args") + RPAR + code_body("body")) c_function.ignore(cStyleComment) source_code = ''' int is_odd(int x) { return (x%2); } int dec_to_hex(char hchar) { if (hchar >= '0' && hchar <= '9') { return (ord(hchar)-ord('0')); } else { return (10+ord(hchar)-ord('A')); } } ''' for func in c_function.searchString(source_code): print("%(name)s (%(type)s) args: %(args)s" % func) prints:: is_odd (int) args: [['int', 'x']] dec_to_hex (int) args: [['char', 'hchar']] z.opening and closing strings cannot be the sameNr”)rªcSs |djƒS)Nr)rØ)r˜rrrr™;sznestedExpr..cSs |djƒS)Nr)rØ)r˜rrrr™@scSs |djƒS)Nr)rØ)r˜rrrr™GscSs |djƒS)Nr)rØ)r˜rrrr™LszOopening and closing arguments must be strings if no content expression is givenznested %s%s expression)r<ršrrÒr&r6r%rAr´r¡rarRr1r+r-rHrOrÒ)ÚopenerÚcloserÚcontentrr¤rrrrnïs6A  , &  *$c s&ˆdd…‰‡‡fdd„‰‡fdd„}‡fdd„}‡fdd „}ttƒjd ƒjƒtƒd �}tƒtƒj|ƒjd ƒ}tƒj|ƒjd ƒ}tƒj|ƒjdƒ} |rÌtt |ƒ|t|t|ƒt |ƒtƒd �| ƒ} n.tt |ƒt|t|ƒt |ƒtƒd �| ƒ} | j ‡fdd„ƒ|j t tƒƒ| jdƒS)aæHelper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code. Parameters: - blockStatementExpr - expression defining syntax of statement that is repeated within the indented block - indentStack - list created by caller to manage indentation stack (multiple statementWithIndentedBlock expressions within a single grammar should share a common indentStack) - indent - boolean indicating whether block must be indented beyond the current level; set to False for block of left-most statements (default= ``True``) A valid block must contain at least one ``blockStatement``. Example:: data = ''' def A(z): A1 B = 100 G = A2 A2 A3 B def BB(a,b,c): BB1 def BBA(): bba1 bba2 bba3 C D def spam(x,y): def eggs(z): pass ''' indentStack = [1] stmt = Forward() identifier = Word(alphas, alphanums) funcDecl = ("def" + identifier + Group("(" + Optional(delimitedList(identifier)) + ")") + ":") func_body = indentedBlock(stmt, indentStack) funcDef = Group(funcDecl + func_body) rvalue = Forward() funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")") rvalue << (funcCall | identifier | Word(nums)) assignment = Group(identifier + "=" + rvalue) stmt << (funcDef | assignment | identifier) module_body = OneOrMore(stmt) parseTree = module_body.parseString(data) parseTree.pprint() prints:: [['def', 'A', ['(', 'z', ')'], ':', [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], 'B', ['def', 'BB', ['(', 'a', 'b', 'c', ')'], ':', [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], 'C', 'D', ['def', 'spam', ['(', 'x', 'y', ')'], ':', [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] Ncsˆˆdd…<dS)Nrr)Ú backup_stackÚ indentStackrrÚ reset_stackªsz"indentedBlock..reset_stackcsN|t|ƒkrdSt||ƒ}|ˆdkrJ|ˆdkr>t||dƒ‚t||dƒ‚dS)Nr”zillegal nestingznot a peer entryr•r•)rÒrWr<)rªr»r˜ÚcurCol)rŸrrÚcheckPeerIndent­s     z&indentedBlock..checkPeerIndentcs2t||ƒ}|ˆdkr"ˆj|ƒn t||dƒ‚dS)Nr”znot a subentryr•)rWrír<)rªr»r˜r¡)rŸrrÚcheckSubIndentµs   z%indentedBlock..checkSubIndentcsJ|t|ƒkrdSt||ƒ}ˆo$|ˆks2t||dƒ‚|ˆdkrFˆjƒdS)Nznot an unindentr”r•)rÒrWr<rH)rªr»r˜r¡)rŸrrÚ checkUnindent¼s     z$indentedBlock..checkUnindentz )rÚINDENTr¶ÚUNINDENTcsˆƒS)Nr)rUrKr¹r»)r rrr™ÑszindentedBlock..zindented block) r6r/rLrJrFr)r¡rÒr-r8rérNrJ) ÚblockStatementExprrŸrmr¢r£r¤r�r¥ÚPEERÚUNDENTÚsmExprr)ržrŸr rr„Ws"Q    2,z#[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]z[\0xa1-\0xbf\0xd7\0xf7]z_:zany tagzgt lt amp nbsp quot aposz><& "'z &(?PrMz);zcommon HTML entitycCs tj|jƒS)zRHelper parser action to replace common HTML entities with their special characters)Ú_htmlEntityMaprôÚentity)r˜rrrryÛsz/\*(?:[^*]|\*(?!/))*z*/zC style commentzz HTML commentz.*z rest of linez//(?:\\\n|[^\n])*z // commentzC++ style commentz#.*zPython style comment)r™z Ú commaItem)rDc@s¨eZdZdZeeƒZeeƒZe e ƒj dƒj eƒZ e eƒj dƒj eedƒƒZedƒj dƒj eƒZeƒj eƒdeƒj eƒj dƒZejd d „ƒeeeed ƒjƒeƒBj d ƒZejeƒed ƒj dƒj eƒZedƒj dƒj eƒZeeBeBjƒZedƒj dƒj eƒZe ededƒj dƒZedƒj dƒZ edƒj dƒZ!e!de!dj dƒZ"ee!de!d>ƒdee!de!d?ƒj dƒZ#e#j$d d „ƒd!e j d"ƒZ%e&e"e%Be#Bj d#ƒƒj d#ƒZ'ed$ƒj d%ƒZ(e)d@d'd(„ƒZ*e)dAd*d+„ƒZ+ed,ƒj d-ƒZ,ed.ƒj d/ƒZ-ed0ƒj d1ƒZ.e/jƒe0jƒBZ1e)d2d3„ƒZ2e&e3e4d4ƒe5ƒe e6d4d5�ee7d6ƒƒƒƒjƒj d7ƒZ8e9ee:j;ƒe8Bd8d9�ƒj d:ƒZd=S)BrŒa Here are some common low-level expressions that may be useful in jump-starting parser development: - numeric forms (:class:`integers`, :class:`reals`, :class:`scientific notation`) - common :class:`programming identifiers` - network addresses (:class:`MAC`, :class:`IPv4`, :class:`IPv6`) - ISO8601 :class:`dates` and :class:`datetime` - :class:`UUID` - :class:`comma-separated list` Parse actions: - :class:`convertToInteger` - :class:`convertToFloat` - :class:`convertToDate` - :class:`convertToDatetime` - :class:`stripHTMLTags` - :class:`upcaseTokens` - :class:`downcaseTokens` Example:: pyparsing_common.number.runTests(''' # any int or real number, returned as the appropriate type 100 -100 +100 3.14159 6.02e23 1e-12 ''') pyparsing_common.fnumber.runTests(''' # any int or real number, returned as float 100 -100 +100 3.14159 6.02e23 1e-12 ''') pyparsing_common.hex_integer.runTests(''' # hex numbers 100 FF ''') pyparsing_common.fraction.runTests(''' # fractions 1/2 -3/4 ''') pyparsing_common.mixed_integer.runTests(''' # mixed fractions 1 1/2 -3/4 1-3/4 ''') import uuid pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID)) pyparsing_common.uuid.runTests(''' # uuid 12345678-1234-5678-1234-567812345678 ''') prints:: # any int or real number, returned as the appropriate type 100 [100] -100 [-100] +100 [100] 3.14159 [3.14159] 6.02e23 [6.02e+23] 1e-12 [1e-12] # any int or real number, returned as float 100 [100.0] -100 [-100.0] +100 [100.0] 3.14159 [3.14159] 6.02e23 [6.02e+23] 1e-12 [1e-12] # hex numbers 100 [256] FF [255] # fractions 1/2 [0.5] -3/4 [-0.75] # mixed fractions 1 [1] 1/2 [0.5] -3/4 [-0.75] 1-3/4 [1.75] # uuid 12345678-1234-5678-1234-567812345678 [UUID('12345678-1234-5678-1234-567812345678')] Úintegerz hex integerrâz[+-]?\d+zsigned integerroÚfractioncCs|d|dS)Nrr”r•r)r˜rrrr™¤szpyparsing_common.räz"fraction or mixed integer-fractionz[+-]?(?:\d+\.\d*|\.\d+)z real numberz@[+-]?(?:\d+(?:[eE][+-]?\d+)|(?:\d+\.\d*|\.\d+)(?:[eE][+-]?\d+)?)z$real number with scientific notationz[+-]?\d+\.?\d*([eE][+-]?\d+)?Úfnumberr Ú identifierzK(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}z IPv4 addressz[0-9a-fA-F]{1,4}Ú hex_integerrpézfull IPv6 addressrr¨z::zshort IPv6 addresscCstdd„|DƒƒdkS)Ncss|]}tjj|ƒrdVqdS)r”N)rŒÚ _ipv6_partr$)rrBrrrr§Äsz,pyparsing_common...r`)rÿ)r˜rrrr™Äsz::ffff:zmixed IPv6 addressz IPv6 addressz:[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}z MAC addressú%Y-%m-%dcs‡fdd„}|S)aÝ Helper to create a parse action for converting parsed date string to Python datetime.date Params - - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``) Example:: date_expr = pyparsing_common.iso8601_date.copy() date_expr.setParseAction(pyparsing_common.convertToDate()) print(date_expr.parseString("1999-12-31")) prints:: [datetime.date(1999, 12, 31)] csLytj|dˆƒjƒStk rF}zt||t|ƒƒ‚WYdd}~XnXdS)Nr)rÚstrptimeÚdater<r<rœ)rªr»r˜Úve)ÚfmtrrÚcvt_fnÞsz.pyparsing_common.convertToDate..cvt_fnr)r¹rºr)r¹rÚ convertToDateÌs zpyparsing_common.convertToDateú%Y-%m-%dT%H:%M:%S.%fcs‡fdd„}|S)aHelper to create a parse action for converting parsed datetime string to Python datetime.datetime Params - - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%dT%H:%M:%S.%f"``) Example:: dt_expr = pyparsing_common.iso8601_datetime.copy() dt_expr.setParseAction(pyparsing_common.convertToDatetime()) print(dt_expr.parseString("1999-12-31T23:59:59.999")) prints:: [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)] csHytj|dˆƒStk rB}zt||t|ƒƒ‚WYdd}~XnXdS)Nr)rr¶r<r<rœ)rªr»r˜r¸)r¹rrrº÷sz2pyparsing_common.convertToDatetime..cvt_fnr)r¹rºr)r¹rÚconvertToDatetimeås z"pyparsing_common.convertToDatetimez7(?P\d{4})(?:-(?P\d\d)(?:-(?P\d\d))?)?z ISO8601 datez†(?P\d{4})-(?P\d\d)-(?P\d\d)[T ](?P\d\d):(?P\d\d)(:(?P\d\d(\.\d*)?)?)?(?PZ|[+-]\d\d:?\d\d)?zISO8601 datetimez2[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}ÚUUIDcCstjj|dƒS)aParse action to remove HTML tags from web page HTML source Example:: # strip HTML links from normal text text = 'More info at the
pyparsing wiki page' td, td_end = makeHTMLTags("TD") table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end print(table_text.parseString(text).body) Prints:: More info at the pyparsing wiki page r)rŒÚ_html_stripperr¢)rªr»rúrrrÚ stripHTMLTagsszpyparsing_common.stripHTMLTagsr9)r™z r­r¶)rDzcomma separated listcCs t|ƒjƒS)N)r¥r‰)r˜rrrr™#scCs t|ƒjƒS)N)r¥rl)r˜rrrr™&sN)rr¨)rr¨)rµ)r¼)?rrrràr‹r—ÚconvertToIntegerÚfloatÚconvertToFloatrLrprÒr¡r®rbr²rDÚsigned_integerr¯rçr8rJÚ mixed_integerrÿÚrealÚsci_realrÚnumberr°rRrQr±Ú ipv4_addressr´Ú_full_ipv6_addressÚ_short_ipv6_addressrèÚ_mixed_ipv6_addressr&Ú ipv6_addressÚ mac_addressrr»r½Ú iso8601_dateÚiso8601_datetimeÚuuidrUrTr¿rÀr6r1r/rtrKÚ _commasepitemr^rwrRÚcomma_separated_listr‚r`rrrrrŒþsT"" ,   8 c@seZdZdd„Zdd„ZdS)Ú_lazyclasspropertycCs||_|j|_|j|_dS)N)r½ràr)rÇr½rrrrÉ+sz_lazyclassproperty.__init__csnˆdkrt|ƒ‰tˆdƒ s.r”)rÞr;r€Ú__mro__rÕr½r)rÇr£rÊÚattrnamer)rÊrÚ__get__0s z_lazyclassproperty.__get__N)rrrrÉrÙrrrrrÔ*srÔc@sPeZdZdZgZedd„ƒZedd„ƒZedd„ƒZ edd „ƒZ ed d „ƒZ d S) rŽa× A set of Unicode characters, for language-specific strings for ``alphas``, ``nums``, ``alphanums``, and ``printables``. A unicode_set is defined by a list of ranges in the Unicode character set, in a class attribute ``_ranges``, such as:: _ranges = [(0x0020, 0x007e), (0x00a0, 0x00ff),] A unicode set can also be defined using multiple inheritance of other unicode sets:: class CJK(Chinese, Japanese, Korean): pass cCs`g}xD|jD]:}|tkrPx*|jD] }|jt|d|ddƒƒq"Wq Wdd„tt|ƒƒDƒS)Nrr”cSsg|] }t|ƒ‘qSr)r_)rr¹rrrrTsz5unicode_set._get_chars_for_ranges..r•)r×rŽÚ_rangesrOr)r~rñ)rÊr¤ÚccÚrrrrrÚ_get_chars_for_rangesLs  $z!unicode_set._get_chars_for_rangescCsdjttj|jƒƒƒS)z+all non-whitespace characters in this ranger¶)r×rr›rÞrÝ)rÊrrrrtVszunicode_set.printablescCsdjttj|jƒƒƒS)z'all alphabetic characters in this ranger¶)r×Úfilterr›ÚisalpharÝ)rÊrrrrR[szunicode_set.alphascCsdjttj|jƒƒƒS)z*all numeric digit characters in this ranger¶)r×rÞr›ÚisdigitrÝ)rÊrrrrp`szunicode_set.numscCs |j|jS)z)all alphanumeric characters in this range)rRrp)rÊrrrrQeszunicode_set.alphanumsN) rrrràrÚrárÝrÔrtrRrprQrrrrrŽ<s    c@sðeZdZdZdejfgZGdd„deƒZGdd„deƒZ Gdd„deƒZ Gd d „d eƒZ Gd d „d eƒZ Gd d„deƒZ Gdd„deƒZGdd„deƒZGdd„de eeƒZGdd„deƒZGdd„deƒZGdd„deƒZGdd„deƒZdS)r�zF A namespace class for defining common language unicode_sets. é c@seZdZdZddgZdS) zpyparsing_unicode.Latin1z/Unicode set for Latin-1 Unicode Character Rangeráé~é éÿN)rárâ)rãrä)rrrràrÚrrrrÚLatin1qsråc@seZdZdZdgZdS)zpyparsing_unicode.LatinAz/Unicode set for Latin-A Unicode Character RangeééN)rærç)rrrràrÚrrrrÚLatinAusrèc@seZdZdZdgZdS)zpyparsing_unicode.LatinBz/Unicode set for Latin-B Unicode Character Rangeé€éON)rérê)rrrràrÚrrrrÚLatinBysrëc@s6eZdZdZd"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2gZd!S)3zpyparsing_unicode.Greekz.Unicode set for Greek Unicode Character Rangesépéÿééééé éEéHéMéPéWéYé[é]é_é}é€é´é¶éÄéÆéÓéÖéÛéÝéïéòéôéöéþN)rìrí)rîrï)rðrñ)ròró)rôrõ)rör÷)rø)rù)rú)rûrü)rýrþ)rÿr)rr)rr)rr)rr)r r )rrrràrÚrrrrÚGreek}s r c@seZdZdZdgZdS)zpyparsing_unicode.Cyrillicz0Unicode set for Cyrillic Unicode Character RangeééÿN)r r )rrrràrÚrrrrÚCyrillic…src@seZdZdZddgZdS) zpyparsing_unicode.Chinesez/Unicode set for Chinese Unicode Character RangeéNéÿŸé0é?0N)rr)rr)rrrràrÚrrrrÚChinese‰src@sDeZdZdZgZGdd„deƒZGdd„deƒZGdd„deƒZdS) zpyparsing_unicode.Japanesez`Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana rangesc@seZdZdZddgZdS) z pyparsing_unicode.Japanese.Kanjiz-Unicode set for Kanji Unicode Character RangeéN鿟é0é?0N)rr)rr)rrrràrÚrrrrÚKanji‘src@seZdZdZdgZdS)z#pyparsing_unicode.Japanese.Hiraganaz0Unicode set for Hiragana Unicode Character Rangeé@0éŸ0N)rr)rrrràrÚrrrrÚHiragana•src@seZdZdZdgZdS)z#pyparsing_unicode.Japanese.Katakanaz1Unicode set for Katakana Unicode Character Rangeé 0éÿ0N)rr)rrrràrÚrrrrÚKatakana™srN) rrrràrÚrŽrrrrrrrÚJapanese�s rc@s eZdZdZddddddgZdS)zpyparsing_unicode.Koreanz.Unicode set for Korean Unicode Character Rangeé¬é¯×ééÿé01é�1é`©é©é°×éÿ×é0é?0N)r r!)r"r#)r$r%)r&r')r(r))r*r+)rrrràrÚrrrrÚKorean�sr,c@seZdZdZdS)zpyparsing_unicode.CJKzTUnicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character RangeN)rrrràrrrrÚCJK¡sr-c@seZdZdZddgZdS) zpyparsing_unicode.Thaiz,Unicode set for Thai Unicode Character Rangeéé:é?é[N)r.r/)r0r1)rrrràrÚrrrrÚThai¥sr2c@seZdZdZd d d gZdS) zpyparsing_unicode.Arabicz.Unicode set for Arabic Unicode Character RangeééééÿééN)r3r4)r5r6)r7r8)rrrràrÚrrrrÚArabic©sr9c@seZdZdZdgZdS)zpyparsing_unicode.Hebrewz.Unicode set for Hebrew Unicode Character Rangeé�éÿN)r:r;)rrrràrÚrrrrÚHebrew­sr<c@seZdZdZddgZdS) zpyparsing_unicode.Devanagariz2Unicode set for Devanagari Unicode Character Rangeé é éà¨éÿ¨N)r=r>)r?r@)rrrràrÚrrrrÚ Devanagari±srAN)rrrràrŸÚ maxunicoderÚrŽrårèrër rrrr,r-r2r9r<rArrrrr�ks uالعربيةu中文uкириллицаuΕλληνικάuעִברִיתu 日本語u漢字u カタカナu ã�²ã‚‰ã�Œã�ªu 한국어u ไทยuदेवनागरीc@s,eZdZdZGdd„dƒZGdd„dƒZdS)Úpyparsing_testzB namespace class for classes useful in writing unit tests c@s8eZdZdZdd„Zdd„Zdd„Zdd „Zd d „Zd S) z&pyparsing_test.reset_pyparsing_contextax Context manager to be used when writing unit tests that modify pyparsing config values: - packrat parsing - default whitespace characters. - default keyword characters - literal string auto-conversion class - __diag__ settings Example: with reset_pyparsing_context(): # test that literals used to construct a grammar are automatically suppressed ParserElement.inlineLiteralsUsing(Suppress) term = Word(alphas) | Word(nums) group = Group('(' + term[...] + ')') # assert that the '()' characters are not included in the parsed tokens self.assertParseAndCheckLisst(group, "(abc 123 def)", ['abc', '123', 'def']) # after exiting context manager, literals are converted to Literal expressions again cCs i|_dS)N)Ú _save_context)rÇrrrrÉåsz/pyparsing_test.reset_pyparsing_context.__init__cCsftj|jd<tj|jd<tj|jd<tj|jd<tj|jd<dd„tj Dƒ|jd<d t j i|jd <|S) NÚdefault_whitespaceÚdefault_keyword_charsÚliteral_string_classÚpackrat_enabledÚ packrat_parsecSsi|]}tt|ƒ|“qSr)r°r)rrrrrú ðsz?pyparsing_test.reset_pyparsing_context.save..rrìr!) rAr´rDr.r‡r·rràrÚ _all_namesr!rì)rÇrrrÚsaveès     z+pyparsing_test.reset_pyparsing_context.savecCsŒtj|jdkr tj|jdƒ|jdt_tj|jdƒx&|jdjƒD]\}}tt ||ƒqLW|jdt_ |jdt_ |jdt _ dS)NrErFrGrrHrIr!)rAr´rDr¶r.r‡r¸r,Úsetattrrrràr!rì)rÇrr1rrrÚrestoreøs      z.pyparsing_test.reset_pyparsing_context.restorecCs|jƒS)N)rL)rÇrrrÚ __enter__ sz0pyparsing_test.reset_pyparsing_context.__enter__cGs|jƒS)N)rN)rÇrÆrrrÚ__exit__sz/pyparsing_test.reset_pyparsing_context.__exit__N) rrrràrÉrLrNrOrPrrrrÚreset_pyparsing_contextÎs rQc@sJeZdZdZddd„Zddd„Zddd „Zdd d „Zee dfd d „ƒZ dS)z&pyparsing_test.TestParseResultsAssertszk A mixin class to add parse results assertion methods to normal unittest.TestCase classes. NcCs<|dk r|j||jƒ|d�|dk r8|j||jƒ|d�dS)zÀ Unit test assertion to compare a ParseResults object with an optional expected_list, and compare any defined results names with an optional expected_dict. N)r¾)Ú assertEqualrrd)rÇrwÚ expected_listÚ expected_dictr¾rrrÚassertParseResultsEqualssz?pyparsing_test.TestParseResultsAsserts.assertParseResultsEqualsTcCs2|j|dd�}|rt|jƒƒ|j|||d�dS)z¾ Convenience wrapper assert to test a parser element and input string, and assert that the resulting ParseResults.asList() is equal to the expected_list. T)r)rSr¾N)rr“rrU)rÇr•Ú test_stringrSr¾ÚverboserwrrrÚassertParseAndCheckList!s z>pyparsing_test.TestParseResultsAsserts.assertParseAndCheckListcCs2|j|dd�}|rt|jƒƒ|j|||d�dS)z¾ Convenience wrapper assert to test a parser element and input string, and assert that the resulting ParseResults.asDict() is equal to the expected_dict. T)r)rTr¾N)rr“rrU)rÇr•rVrTr¾rWrwrrrÚassertParseAndCheckDict-s z>pyparsing_test.TestParseResultsAsserts.assertParseAndCheckDictc Cs|\}}|dk rðdd„t||ƒDƒ}xÊ|D]Â\}}} tdd„| Dƒdƒ} tdd„| Dƒdƒ} | dk r’|j| | pp|d��t|tƒr†|‚WdQRXq*tdd„| Dƒdƒ} td d„| Dƒdƒ} | | fdkrÞ|j|| | | pÖ|d �q*td j|ƒƒq*W|j||dk �r|nd d �dS)aP Unit test assertion to evaluate output of ParserElement.runTests(). If a list of list-dict tuples is given as the expected_parse_results argument, then these are zipped with the report tuples returned by runTests and evaluated using assertParseResultsEquals. Finally, asserts that the overall runTests() success value is True. :param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests :param expected_parse_results (optional): [tuple(str, list, dict, Exception)] NcSs"g|]\}}|d|d|f‘qS)rr”r)rÚrptÚexpectedrrrrIszOpyparsing_test.TestParseResultsAsserts.assertRunTestResults..css|]}t|tƒr|VqdS)N)ršrœ)rÚexprrrr§QszNpyparsing_test.TestParseResultsAsserts.assertRunTestResults..css&|]}t|tƒrt|tƒr|VqdS)N)ršrÞr rˆ)rr\rrrr§Us)Úexpected_exceptionr¾css|]}t|tƒr|VqdS)N)ršr)rr\rrrr§cscss|]}t|tƒr|VqdS)N)ršr)rr\rrrr§fs)rSrTr¾zno validation for {!r}zfailed runTests)r¾)NN) r¬rwÚ assertRaisesršrˆrUr“rîÚ assertTrue)rÇÚrun_tests_reportÚexpected_parse_resultsr¾Úrun_test_successÚrun_test_resultsÚmergedrVrwr[Úfail_msgr]rSrTrrrÚassertRunTestResults9s:   z;pyparsing_test.TestParseResultsAsserts.assertRunTestResultsc cs$|j||d�� dVWdQRXdS)N)r¾)r^)rÇr¼r¾rrrÚassertRaisesParseExceptionxszApyparsing_test.TestParseResultsAsserts.assertRaisesParseException)NNN)NT)NT)NN) rrrràrUrXrYrfrr<rgrrrrÚTestParseResultsAssertss >rhN)rrrràrQrhrrrrrCÉsCrCÚ__main__ÚselectÚfromz_$r4)r;ÚcolumnsrÖZtablesÚcommandaK # '*' as column list and dotted table name select * from SYS.XYZZY # caseless match on "SELECT", and casts back to "select" SELECT * from XYZZY, ABC # list of column names, and mixed case SELECT keyword Select AA,BB,CC from Sys.dual # multiple tables Select A, B, C from Sys.dual, Table2 # invalid SELECT keyword - should fail Xelect A, B, C from Sys.dual # incomplete command - should fail Select # invalid column name - should fail Select ^^^ frox Sys.dual z] 100 -100 +100 3.14159 6.02e23 1e-12 z 100 FF z6 12345678-1234-5678-1234-567812345678 )NF)r“)r9F)N)FTF)T)r¶)T(ràrrr r·Úweakrefrr%rRrŸr3r�r´r r‚r¢rrÚoperatorrÚ itertoolsÚ functoolsrÚ contextlibrrÚ ImportErrorrÚ_threadr Ú threadingÚcollections.abcr r r r rZ ordereddictrr!rìrrrrrrÐr^rKrÚenable_all_warningsÚ__all__r;Ú version_infor¡reÚmaxsizerzrœrÚchrr_r›r¥rÿrÒr~Úreversedrrñr€rär¨r©r¯ZmaxintÚxranger)Ú __builtin__r«Úfnamerír°rÎrÞrr³Úascii_uppercaseÚascii_lowercaserRrprbrQrJr×Ú printablertr�rˆr:r<r>r@rCr rr?ÚregisterrWrhrer–ršr›rorÀrAr2rIr)r4r1r…rsr·r.r$r#rŠrLr§rPrDrBr%rKrÜr,r0r/rGrFrNrMr=r"r9r3r(r;r*r2r5rr6rOrr8rEr+rJr&r-r'rHr7r€r^rZr)rmrlr¢rqr_r…r†rˆrÒrargrfrr~r¡Ú _escapedPuncÚ_escapedHexCharÚ_escapedOctCharÚ _singleCharÚ _charRangerÕrgr}rkrzrxr‹r‚r`r}rirjrƒr~r‰rrr‰rŠr‡rsr\r|rwr�rnr„rSrurUrTrr¬r«r?rYryrVrcrKr{r]r[rdrvrrÒrXrŒrÔrŽr�rrrÚrrrMr9rrr r<r,r2rArCrZ selectTokenZ fromTokenÚidentZ columnNameZcolumnNameListZ columnSpecZ tableNameZ tableNameListZ simpleSQLryrÈr°r²rÑr¾rrrrÚ`s\                        ?]  H    D+! 'N E   KFym{VO#K,:#Dvj-D0  $  W' *     :   0#   E&h~   (  0 ./L"6  ,