Re+ dZdZdZdZddlZddlmZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlmZddlmZddlZdd lmZdd lmZ dd lmZn#e$r dd lmZYnwxYw dd lmZn#e$r dd lmZYnwxYw ddlm Z ddlm!Z!m"Z"n#e$rddl m Z ddl m!Z!m"Z"YnwxYw ddl m#Z$n #e$r ddl%m#Z$n #e$rdZ$YnwxYwYnwxYw ddlm&Z&n#e$rGddZ&YnwxYwe&Z'de'_de'_(e&Z)de)_de)_*de)_+de)_,de)_-de)_.de/e)De)_0dZ1e1e)_2gdZ3e4e j5ddZ6e6ddkZ7e7re j8Z9e:Z;ee:Z?e@eAeBeCeDe4eEeFeGeHeIg ZJnTe jKZ9eLZMdZ?gZJddlNZNdOD]-ZP eJQeReNeP##eS$rY*wxYweTdeMdDZUd ZVejWejXzZYd!ZZeZd"zZ[eYeZzZ\ed?ehZtGd@dAetZuGdBdCetZvGdDdEevZwGdFdGevZxGdHdIevZyGdJdKeyZzeyZ{eyet_|GdLdMevZ}GdNdOeyZ~GdPdQe}ZGdRdSevZGdTdUevZGdVdWeZGdXdYeZGdZd[evZGd\d]evZGd^d_evZGd`daevZGdbdcevZGdddeeZGdfdgeZGdhdieZGdjdkeZGdldmeZGdndoeZGdpdqeZGdrdsetZGdtdueZGdvdweZGdxdyeZGdzd{eZGd|d}etZGd~deZGddeZGddeZGddeZGddeZGddeZGddehZGddeZGddeZGddeZGddeZGddeZGddeZGddeZGddeZGddehZdZddZddZdZdZdZdZddZdZddZdZdZewdZedZedZedZedZee]dd<dZeddZeddZeezezeddzZeeedzezZeydeddzeeeezdzdzZdZdZdZdZd„ZedÄZ edĄZ edŦedƦfdDŽZdȄZdɄZdʄZehe_d d˄Ze&Zehe_ehe_ed̦edͦfd΄ZeZ eedϦdzdѦZeedҦdzdԦZeedϦdzedҦdzzdզZee{d֦eԠzdצZdddeԠfd؄Z֐ddلZedڦZedۦZeeeYe\dzdݦ\ZZeedޠOdߦZedd^eޠzdzdZdZeeddzdZ eddZ eddZeddZ eeddzezdZ eZ eddZ eeee`deedeydzezzdZeeeԠezd$dZ GddZGddehZGddehZGddeZejjjejjjzejjjzej_e7reedejeedejeedejeedejeedejeedejeejdejjeejdejjeejdejjeedejeedejeed ejGd d Zed kre~d Ze~dZeeYe\dzZeeddeŦZeeedZdezZeeddeŦZeeedZededzezedzZ e  dej  dej  dej  dddlZejeĐejej ddSdS(!a 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)MutableMappingMapping) OrderedDict)SimpleNamespaceceZdZdS)rN)__name__ __module__ __qualname__/builddir/build/BUILDROOT/alt-python311-pip-21.3.1-3.el8.x86_64/opt/alt/python311/lib/python3.11/site-packages/pip/_vendor/pyparsing.pyrrsrraA 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() Fcfg|].}|ds|d,|/S)enable_warn_ startswith).0nms r rs>iiibbmmI6N6NiRTR_R_`gRhRhiriiircfdt_dt_dt_dt_dSNT)__diag__)warn_multiple_tokens_in_named_alternation)warn_ungrouped_named_tokens_in_collectionwarn_name_set_on_empty_Forward%warn_on_multiple_string_args_to_oneofrrr_enable_all_warningsr&s(9=H69=H6.2H+59H222r)t __version____versionTime__ __author__ __compat__r!AndCaselessKeywordCaselessLiteral CharsNotInCombineDictEachEmpty FollowedByForward GoToColumnGroupKeywordLineEnd LineStartLiteral PrecededBy MatchFirstNoMatchNotAny OneOrMoreOnlyOnceOptionalOrParseBaseExceptionParseElementEnhanceParseExceptionParseExpressionParseFatalException ParseResultsParseSyntaxException ParserElement QuotedStringRecursiveGrammarExceptionRegexSkipTo StringEnd StringStartSuppressTokenTokenConverterWhiteWordWordEnd WordStart ZeroOrMoreChar alphanumsalphas alphas8bit anyCloseTag anyOpenTag cStyleCommentcolcommaSeparatedListcommonHTMLEntity countedArraycppStyleCommentdblQuotedStringdblSlashComment delimitedListdictOfdowncaseTokensemptyhexnums htmlCommentjavaStyleCommentlinelineEnd lineStartlineno makeHTMLTags makeXMLTagsmatchOnlyAtColmatchPreviousExprmatchPreviousLiteral nestedExprnullDebugActionnumsoneOfopAssocoperatorPrecedence printablespunc8bitpythonStyleComment quotedString removeQuotesreplaceHTMLEntity replaceWith restOfLinesglQuotedStringsrange stringEnd stringStarttraceParseAction unicodeString upcaseTokens withAttribute indentedBlockoriginalTextForungroup infixNotation locatedExpr withClass CloseMatchtokenMappyparsing_commonpyparsing_unicode unicode_setconditionAsParseActionrecLt|tr|S t|S#t$rqt|t jd}td}|d| |cYSwxYw)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+;cldtt|dddddzS)Nz\ur)hexintts rz_ustr..s.C!QrT OO8L8LQRR8P0Pr) isinstanceunicodestrUnicodeEncodeErrorencodesysgetdefaultencodingrMsetParseActiontransformString)objret xmlcharrefs r_ustrrs c7 # # J 3s88O! 3 3 3#,,%%c&<&>&>@STTCy))J  % %&P&P Q Q Q--c22 2 2 2  3s(A8B#"B#z6sum len sorted reversed list tuple set any all min maxc#K|]}|VdSNr)rys r r s"++Qq++++++rcd}ddD}t||D]\}}|||}|S)z/Escape &, <, >, ", ', etc. in a string of data.z&><"'c3&K|] }d|zdzV dS)&;Nr)rss rrz_xml_escape..s*GGA#'C-GGGGGGrzamp gt lt quot apos)splitzipreplace)data from_symbols to_symbolsfrom_to_s r _xml_escapers`LGG)>)D)D)F)FGGGJ, 33(( s||E3'' Kr 0123456789 ABCDEFabcdef\c#6K|]}|tjv|VdSr)string whitespacercs rrrs/OO1AV=N4N4NQ4N4N4N4NOOrc||nd|rtntttfd}|S)Nzfailed user-defined conditioncVt|||s ||dSr)bool)rlrexc_typefnmsgs rpaz"conditionAsParseAction..pa%s=BBq!QKK   &(1a%% % & &r)rGrE _trim_arityr)rmessagefatalrrrs` @@rrr si(''.MC&+?""H RB 2YY&&&&&&Y& IrcPeZdZdZd dZedZdZdZdZ d d Z d Z dS)rCz7base exception class for all parsing runtime exceptionsrNct||_|||_d|_n||_||_||_|||f|_dSNr)locrpstr parserElementargs)selfrrrelems r__init__zParseBaseException.__init__0sF ;DHDIIDHDI!3$ rcF||j|j|j|jS)z internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses )rrrr)clspes r_from_exceptionz"ParseBaseException._from_exception;s# s27BFBFB,<===rc|dkrt|j|jS|dvrt|j|jS|dkrt |j|jSt |)zsupported 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 rq)r`columnrn)rqrrr`rnAttributeError)ranames r __getattr__zParseBaseException.__getattr__Csn H  $(DI.. . ' ' 'tx++ + f__$),, , '' 'rc|jrT|jt|jkrd}n6d|j|j|jdzzdd}nd}d|j||j|j|jfzS)Nz, found end of textz , found %rrz\\\rz%%s%s (at char %d), (line:%d, col:%d))rrlenrrrqr)rfoundstrs r__str__zParseBaseException.__str__Rs 9 x3ty>>))0(49TXdhl5J+KKTTUZ\`aaH7Hh$+t{KL Mrc t|Srrrs r__repr__zParseBaseException.__repr__\T{{r>!>[> ( ( ( M M M     ;;;;;rrCc*eZdZdZeddZdS)rEa: Exception thrown when parse expressions don't match class; 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 Example:: try: Word(nums).setName("integer").parseString("ABC") except ParseException as pe: print(pe) print("column: {}".format(pe.col)) prints:: Expected integer (at char 0), (line:1, col:1) column: 1 cddl}|tj}g}t|tr=||j|d|jdz zdz|dt|j ||dkr|| |j |}t}t|| dD]8\}}|d}|jdd} t| t"rm|jjd vrM| |vrR|| t| } |d | j| j | n| Ct| } |d | j| j n?|j} | jd vr|d | j|dz}|sn:d|S)ap Method to take an exception and translate the Python internal traceback into a list of the pyparsing expressions that caused the exception to be raised. Parameters: - exc - exception raised during parsing (need not be a ParseException, in support of Python exceptions that might be raised in a parse action) - depth (default=16) - number of levels back in the stack trace to list expression and function names; if None, the full stack trace names will be listed; if 0, only the failing input line, marker, and exception string will be shown Returns a multi-line string listing the ParserElements and/or function names in the exception's stack trace. Note: the diagnostic output will include string representations of the expressions that failed to parse. These representations will be more helpful if you use `setName` to give identifiable names to your expressions. Otherwise they will use the default string forms, which may be cryptic to read. explain() is only supported under Python 3. rN r^z{0}: {1})contextr) parseImpl _parseNoCachez {0}.{1} - {2}z{0}.{1})wrapperzz{0} )inspectrgetrecursionlimitrrCappendrnr`formatrrgetinnerframes __traceback__set enumeratef_localsgetrJf_codeco_nameaddrr) excdepthrrcallersseenifffrmf_self self_typecodes rexplainzParseException.explainsN0  =)++E c- . . 2 JJsx JJscgk*S0 1 1 1 :$$T#YY%7==>>> 199,,S->,NNG55D"7E677#344  2e))&$77fm44;z)1OOO ~~ HHV$$$ $V IJJ55i6J6?6H6< > >????' $V IJJy// 0D090B D DEEEE:D|'>>> JJu||DL99::: Eyy~~rN)r)rrrr staticmethodr%rrrrErEksD,BBB\BBBrrEceZdZdZdS)rGznuser-throwable exception thrown when inconsistent parse content is found; stops all parsing immediatelyNrrrrrrrrGrGs22DrrGceZdZdZdS)rIzjust 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. Nr(rrrrIrIs  DrrIceZdZdZdZdZdS)rLziexception thrown by :class:`ParserElement.validate` if the grammar could be improperly recursive c||_dSrparseElementTracerparseElementLists rrz"RecursiveGrammarException.__init__s!1rcd|jzS)NzRecursiveGrammarException: %sr,rs rrz!RecursiveGrammarException.__str__s.1GGGrN)rrrrrrrrrrLrLsA222HHHHHrrLc&eZdZdZdZdZdZdS)_ParseResultsWithOffsetc||f|_dSrtup)rp1p2s rrz _ParseResultsWithOffset.__init__s8rc|j|Srr4rrs r __getitem__z#_ParseResultsWithOffset.__getitem__sx{rc6t|jdSNr)reprr5rs rrz _ParseResultsWithOffset.__repr__sDHQK   rc.|jd|f|_dSr<r4r9s r setOffsetz!_ParseResultsWithOffset.setOffsetsHQK#rN)rrrrr:rr?rrrr2r2sP!!!$$$$$rr2cleZdZdZd2dZddddefdZdZefdZdZ d Z d Z d Z e Z d Zd ZdZdZdZer eZ eZ eZneZ eZ eZ dZdZdZdZdZd3dZdZdZdZdZ dZ!dZ"dZ#dZ$dZ%d Z&d4d"Z'd#Z(d$Z)d%Z*d5d'Z+d(Z,d)Z-d6d+Z.d,Z/d-Z0d.Z1d/Z2d0Z3e4d3d1Z5dS)7rHaSStructured parse results, to provide multiple means of access to the parsed data: - as a list (``len(results)``) - by list index (``results[0], results[1]``, etc.) - by attribute (``results.`` - 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 NTclt||r|St|}d|_|Sr )robject__new___ParseResults__doinit)rtoklistnameasListmodalretobjs rrCzParseResults.__new__!s6 gs # # N$$ rcn|jrd|_d|_d|_i|_||_||_|g}||t r|dd|_n.||trt ||_n|g|_t|_ ||r|s d|j|<||trt|}||_||tdtt fr|ddgfvs||tr|g}|rl||tr&t!t|jd||<n&t!t|dd||<|||_dS |d||<dS#t"t$t&f$r |||<YdSwxYwdSdSdS)NFrr)rD_ParseResults__name_ParseResults__parent_ParseResults__accumNames_ParseResults__asList_ParseResults__modallist_ParseResults__toklist_generatorTypedict_ParseResults__tokdictrrr basestringrHr2KeyError TypeError IndexError)rrErFrGrHrs rrzParseResults.__init__*s = $!DMDK DM "D "DM DLz'4(( +!(G^44 +!%g")!VVDN    ,*+!$'z$$$ #T{{DKJwdZ(FGG -GX\^`bdWeLeLe:gz22(&iG -!z'<88Z%<\'J[=\=\^_%`%`T %<\'RS*=U=UWX%Y%YT (,DJ%%%-%,QZT $i<---%,T -%     MfLes FF.-F.ct|ttfr |j|S||jvr|j|ddSt d|j|DS)Nrrcg|] }|d Srr)rvs rrz,ParseResults.__getitem__..Xs$E$E$EaQqT$E$E$Er)rrslicerQrMrTrHr9s rr:zParseResults.__getitem__Qso a#u & & G>!$ $)))~a(,Q//#$E$E4>!3D$E$E$EFFFrc||tr<|j|t|gz|j|<|d}nh||tt fr ||j|<|}nC|j|tt|dgz|j|<|}||trt||_ dSdSr<) r2rTrrPrr]rQrHwkrefrL)rkr\rsubs r __setitem__zParseResults.__setitem__Zs :a0 1 1  $ 2 21dff = = CDN1 A$CC ZC< ( (  !DN1 CC $ 2 21dff = =AXYZ\]A^A^@_ _DN1 C :c< ( ( ' ;;CLLL ' 'rc t|ttfrt|j}|j|=t|tr|dkr||z }t||dz}t t ||}||j D]<\}}|D]4}t|D]"\}\}} t|| | |kz ||<#5=dS|j |=dSNrr) rrr]rrQrPrangeindicesreverserTitemsrr2) rrmylenremovedrF occurrencesjr`valuepositions r __delitem__zParseResults.__delitem__gs9 a#u & & "''Eq!!S!! $q55JA!QUOO5!))E"2"2344G OO   %)^%9%9%;%; c c!k ccA09+0F0Fcc,,E8)@T\_`T`Ha)b)b Acc c c q!!!rc||jvSr)rT)rr`s r __contains__zParseResults.__contains__|sDN""rc*t|jSr)rrQrs r__len__zParseResults.__len__s4>"""rc|j SrrQrs r__bool__zParseResults.__bool__s&&'rc*t|jSriterrQrs r__iter__zParseResults.__iter__sDN###rc<t|jdddSNrrxrs r __reversed__zParseResults.__reversed__sDN44R4()))rct|jdr|jSt|jS)Niterkeys)hasattrrTrryrs r _iterkeyszParseResults._iterkeyss: 4>: . . (>**,, ,'' 'rcDfdDS)Nc3(K|] }|V dSrrrr`rs rrz+ParseResults._itervalues..s'22AQ222222rrrs`r _itervalueszParseResults._itervaluess'2222!1!12222rcDfdDS)Nc3,K|]}||fVdSrrrs rrz*ParseResults._iteritems..s+77DG 777777rrrs`r _iteritemszParseResults._iteritemss'7777dnn&6&67777rcDt|S)zVReturns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x).)rPrrs rkeyszParseResults.keyss (( (rcDt|S)zXReturns all named result values (as a list in Python 2.x, as an iterator in Python 3.x).)rP itervaluesrs rvalueszParseResults.valuess))** *rcDt|S)zfReturns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x).)rP iteritemsrs rrhzParseResults.itemss(()) )rc*t|jS)zSince keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.)rrTrs rhaskeyszParseResults.haskeyssDN###rc2|sdg}|D]'\}}|dkr |d|f}td|zt|dtst |dks |d|vr|d}||}||=|S|d}|S)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'] rdefaultrz-pop() got an unexpected keyword argument '%s'r)rhrWrrr)rrkwargsr`r\indexr defaultvalues rpopzParseResults.popsJ 4DLLNN U UDAqI~~Q| ORS STTT tAw $ $ t99>>7d??GEu+CU J7L rc||vr||S|S)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 r)rkey defaultValues rrzParseResults.gets$ $;;9  rc|j|||jD]7\}}t |D]"\}\}}t ||||kz||<#8dS)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)rQinsertrTrhrr2)rrinsStrrFrkr`rmrns rrzParseResults.insert s eV,,,!%!5!5!7!7 _ _ D+(1+(>(> _ _$$E8!8HW\L\@]!^!^ A _ _ _rc:|j|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)rQr)ritems rrzParseResults.append s  d#####rct|tr||dS|j|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)rrH__iadd__rQextend)ritemseqs rrzParseResults.extend/sJ g| , , + MM' " " " " " N ! !' * * * * *rcL|jdd=|jdS)z7 Clear all elements and results names. N)rQrTclearrs rrzParseResults.clearBs, N111  rc6 ||S#t$rYdSwxYwr)rVrrFs rrzParseResults.__getattr__Is3 :    22 s  c8|}||z }|Srcopy)rotherrs r__add__zParseResults.__add__Osiikk u  rc|jrt|jfd|j}fd|D}|D]?\}}|||<t |dt rt ||d_@|xj|jz c_|j |j|S)Nc|dkrn|zSr<r)aoffsets rrz'ParseResults.__iadd__..WsAEE&&q6zrc ng|]1\}}|D])}|t|d|df*2Srr)r2)rr`vlistr\ addoffsets rrz)ParseResults.__iadd__..YsjIII"*!U%II=> !"9!A$ !A$"P"PQIIIIrr) rTrrQrhrrHr_rLrMupdate)rr otheritemsotherdictitemsr`r\rrs @@rrzParseResults.__iadd__Ts ? 0((FAAAAI..00JIIII.8IIIN& 0 01QadL110$)$KKAaDM %/)   !3444 rcjt|tr|dkr|S||zSr<)rrrrrs r__radd__zParseResults.__radd__ds6 eS ! ! eqjj99;; 4< rc\dt|jdt|jdS)N(, ))r=rQrTrs rrzParseResults.__repr__ls/!$.111143G3G3G3GHHrcVddd|jDzdzS)N[rc3|K|]7}t|trt|nt|V8dSr)rrHrr=)rrs rrz'ParseResults.__str__..psCllXY:a+F+FSuQxxxDQRGGllllllr])rrQrs rrzParseResults.__str__os2TYYll]a]kllllllorrrrrcg}|jD]j}|r|r||t|tr||z }H|t |k|Sr)rQrrrH _asStringListr)rsepoutrs rrzParseResults._asStringListrsN ( (D s  3$ -- (t))+++ 5;;'''' rc$d|jDS)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'] cdg|]-}t|tr|n|.Sr)rrHrG)rress rrz'ParseResults.asList..s3aaa3 3 = =F 3aaarrurs rrGzParseResults.asList}sbaRVR`aaaarctr|j}n|j}fdtfd|DS)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"} ct|tr6|r|Sfd|DS|S)Nc&g|] }|Srr)rr\toItems rrz7ParseResults.asDict..toItem..s!333!FF1II333r)rrHrasDict)rrs rrz#ParseResults.asDict..toItemsR#|,, ;;==4::<<'3333s3333 rc38K|]\}}||fVdSrr)rr`r\rs rrz&ParseResults.asDict..s399tq!Qq N999999r)PY_3rhrrS)ritem_fnrs @rrzParseResults.asDictsa(  %jGGnG     9999wwyy999999rct|j}t|j|_|j|_|j|j|j|_|S)zG Returns a new copy of a :class:`ParseResults` object. ) rHrQrSrTrhrLrMrrK)rrs rrzParseResults.copysa4>**T^113344 }   1222[  rFc d}g}td|jD}|dz}|sd}d}d}d} ||} n|jr|j} | s|rdSd} |||d| dgz }t |jD]\} } t | trL| |vr'|| || |o|du||gz }E|| d|o|du||gz }fd} | |vr|| } | s|ryd} tt| } |||d| d| d | dg z }|||d | dgz }d |S) z (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names. r c3:K|]\}}|D]}|d|fVdSrNr)rr`rr\s rrz%ParseResults.asXML..sV** E#(**Q4)*******r rNITEM<>K|]\}}t||fVdSr)rrr`r\s rrz$ParseResults.dump..Gs0DDtq!A{DDDDDDrrz- : r)rfull include_list_depthc3@K|]}t|tVdSr)rrH)rvvs rrz$ParseResults.dump..Ss,AAbZL11AAAAAArz %s%s[%d]: %s%s%s) rrrGrsortedrhrrHdumpr=anyrr) rrrrrrNLrhr`r\rrs rrzParseResults.dump)s*    JJvdkkmm 4 44 5 5 5 5 JJrNNN ! H||~~ HDDtzz||DDDDD! , ,DAq' 2JJvvv JKKK!!\22,1JJqvvV$Uajpstjtv'u'uvvvvJJuQxx0000 477++++ ,AADAAAAA H&q\\HHEAr!"l33H #8F=AV_<=GG6IMQ]KQTU:=D=W=W `_ 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)pprintrG)rrrs rrzParseResults.pprintjs22  dkkmm5d555f55555rc|j|j|jdur|pd|j|jffSr)rQrTrrLrMrKrs r __getstate__zParseResults.__getstate__sN$$&&d*>t}}F$" rc|d|_|d\|_}}|_i|_|j||t ||_dSd|_dSrd)rQrTrKrMrr_rL)rstater inAccumNamess r __setstate__zParseResults.__setstate__scq9>q6\4;   ... ?!#JJDMMM DMMMrc6|j|j|j|jfSr)rQrKrNrOrs r__getnewargs__zParseResults.__getnewargs__s~t{DM4<GGrc~tt|t|zSr)rrrPrrs rrzParseResults.__dir__s)4::diikk!2!222rc  d}|g}|D]P\}}t|tr||||z }5|||g|||z }Q|||g|}|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 t|trt|ttf St|t  S#t $rYdSwxYwNF)ryrrrbytesrU Exception)rs r is_iterablez+ParseResults.from_dict..is_iterablesj ;S ;)#U|<<<<)#z::::    uu sA AArF)rFrG)rhrr from_dict)rrrFr rr`r\s rr zParseResults.from_dicts ; ; ;c"ggKKMM ? ?DAq!W%% ?s}}QQ}///ssA3Q{{1~~>>>>  #se$'''C r)NNTTrr)NFrT)rTTr)6rrrrrCrrr:rbrorqrsrv __nonzero__rzr}rrrrrrrhrrrrrrrrrrrrrrrrrrGrrrrrrrrrrrrr rrrrHrHsD))T $$t4T^%-%-%-%-NGGG,6 ' ' ' '"""*######(((K$$$***((( 333888 *;=GM O Y ) ) ) + + + * * *$$$ 5 5 5 n    .___* $ $ $+++&      IIIsss    bbb"":":":H   ;;;;z&&&P????B6668!!!HHH333[rrHc|}d|cxkrt|krnn||dz dkrdn||dd|z S)aReturns 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. rrr )rrfind)rstrgrs rr`r`sb AC    #a&&     Qs1uX%5%5113qRUAVAV;VVrc6|dd|dzS)aReturns 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)rrs rrqrqs ::dAs # #a ''rc|dd|}|d|}|dkr ||dz|S||dzdS)zfReturns the line of text containing loc within a string, counting newlines as line separators. r rrN)rfind)rrlastCRnextCRs rrnrns\ZZa % %F YYtS ! !F {{FQJv%&&FQJKK  rc tdt|zdzt|zdt||t||fzzdS)NzMatch z at loc z(%d,%d))printrrqr`)instringrexprs r_defaultStartDebugActionrsY 8eDkk !J .s ;i6RUW_K`K`befiksbtbtJu>u uwwwwwrctdt|zdzt|zdS)NzMatched z -> )rrrrG)rstartlocendlocrtokss r_defaultSuccessDebugActionr"s; *uT{{ "V +c$++--.@.@ @AAAAArcDtdt|zdS)NzException raised:)rr)rrrrs r_defaultExceptionDebugActionr$s" c *+++++rcdS)zG'Do-nothing' debug action, to suppress debugging output during parsing.Nr)rs rrxrxsDrrc tvrfdSdg dgtdddkr dd}ddntj}tjd}|d d }|d|d |zf   fd }d } t dt dj}n#t$rt}YnwxYw||_|S)Nc|Srr)rrrfuncs rrz_trim_arity..sttAwwrrFr)rcztdkrdnd}tj| |zdz |}|ddgS)N)rr)rrlimitr)system_version traceback extract_stack)r.r frame_summarys rr1z"_trim_arity..extract_stack sJ)Y66RRBF%36'E/A:MNNNvVM!"1"%& &rcTtj||}|d}|ddgS)Nr-rr)r0 extract_tb)tbr.framesr2s rr4z_trim_arity..extract_tbs2)"E:::F"2JM!"1"%& &rr-rrcr |dd}dd<|S#t$rdr tjd}|ddddks ~n'#t$rYnwxYw# ~w#t$rYwwxYwxYwdkrdxxdz cc<YwxYw)NrrTrrr-)rWrexc_info NameError) rrr5r4 foundArityr(r.maxargspa_call_line_synths rr z_trim_arity..wrapper!s*  dDqO, $ 1     a= !! \^^B/)z"A666r:2A2>BTTT! U! "(!!! D!! "(!!! D!8w&&!HHHMHHHH% shB69A?-A/.B6/ A<9B6;A<<B6?BBB B BB BB64B6zr __class__r[) singleArgBuiltinsr/r0r1r4getattrrr r) r(r<r1 LINE_DIFF this_liner  func_namer4r;r.r=s `` @@@@rrrsZ    &&&&& CEJbqbV## ' ' ' '  ' ' ' ' ' "/ ) I A&&&r*I#A, ! y(@A6!ID*#D+66?AA II  G Ns$B((CCceZdZdZdZdZedZedZe dZ dNdZ dZ d Z dNd ZdNd ZdOd ZdZdZdZdZdZdZdOdZdZdPdZdZdZGddeZeGddeZnGddeZiZ e!Z"ddgZ#dPd Z$eZ%ed!Z&dZ'edQd#Z(dNd$Z)e*dfd%Z+d&Z,e*fd'Z-e*dfd(Z.d)Z/d*Z0d+Z1d,Z2d-Z3d.Z4d/Z5d0Z6d1Z7d2Z8d3Z9d4Z:d5Z;d6Zd9Z?d:Z@d;ZAd<ZBd=ZCd>ZDdOd?ZEd@ZFdAZGdBZHdCZIdRdDZJdNdEZKdFZLdGZMdHZNdIZOdJZPdOdKZQ dSdMZRdS)TrJz)Abstract base level parser element class.z Fc|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)rJDEFAULT_WHITE_CHARScharss rsetDefaultWhitespaceCharsz'ParserElement.setDefaultWhitespaceCharsLs-2 )))rc|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)rJ_literalStringClassrs rinlineLiteralsUsingz!ParserElement.inlineLiteralsUsing\s(-0 )))rc0|jr|j}|j|Sr)tb_next)rr5s r_trim_tracebackzParserElement._trim_tracebackrs$j Bj  rc|t|_d|_d|_d|_||_d|_ttj |_ d|_ d|_ d|_ t|_d|_d|_d|_d|_d|_d|_d|_d|_d|_dS)NTFrNNN)rP parseAction failActionstrRepr resultsName saveAsListskipWhitespacerrJrF whiteCharscopyDefaultWhiteCharsmayReturnEmptykeepTabs ignoreExprsdebug streamlined mayIndexErrorerrmsg modalResults debugActionsr callPreparse callDuringTry)rsavelists rrzParserElement.__init__xs66 ""m?@@%)"# 66  !  . "rctj|}|jdd|_|jdd|_|jrtj|_|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)rrSr]rZrJrFrY)rcpys rrzParserElement.copysQ,ioo*111-*111-  % ?*>CN rcr||_d|jz|_tjr||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) Expected )rFrar!!enable_debug_on_named_expressionssetDebugrs rsetNamezParserElement.setNames6 !DI-  5  MMOOO rc.|||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)rrFlistAllMatchess rsetResultsNamezParserElement.setResultsNames*##D.999rc|}|dr |dd}d}||_| |_|S)N*rT)rendswithrVrb)rrFrpnewselfs rrozParserElement._setResultsNamesM))++ ==   "9D!N"#11rTc|r|jdfd }|_||_n&t|jdr|jj|_|S)zMethod to invoke the Python pdb debugger when this element is about to be parsed. Set ``breakFlag`` to True to enable, False to disable. TcPddl}|||||Sr<)pdb set_trace)rr doActions callPreParserx _parseMethods rbreakerz'ParserElement.setBreak..breakers/  #|Hc9lKKKr_originalParseMethodTT)_parser~r)r breakFlagr}r|s @rsetBreakzParserElement.setBreaksq  ?;L L L L L L L ,8G (!DKKt{$:;; ?"k>  rc,t|dgkrg|_nwtd|Dstdtt t t||_|dd|_|S)a Define one or more actions to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as ``fn(s, loc, toks)`` , ``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a :class:`ParseResults` object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. If None is passed as the parse action, all previously added parse actions for this expression are cleared. Optional keyword arguments: - callDuringTry = (default= ``False``) indicate if parse action should be run during lookaheads and alternate testing Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See :class:`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. 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] Nc34K|]}t|VdSr)callable)rrs rrz/ParserElement.setParseAction..s(22x||222222rzparse actions must be callablereF)rPrSallrWmaprrrerfnsrs rrzParserElement.setParseActionsP 99  !D  22c22222 B @AAA#C T#YY$?$?@@D !'OU!C!CD  rc |xjtttt|z c_|jp|dd|_|S)z Add one or more parse actions to expression's list of parse actions. See :class:`setParseAction`. See examples in :class:`copy`. reF)rSrPrrrerrs raddParseActionzParserElement.addParseActionsS D[$s))!= 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) rrF)rrre)rSrrrre)rrrrs r addConditionzParserElement.addCondition)s$ ^ ^B   # #$:2vzzR[G\G\AGGUZA[A[%]%]%] ^ ^ ^ ^"/U6::ou3U3U rc||_|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.)rTrrs r setFailActionzParserElement.setFailActionBs rcd}|r;d}|jD]/} |||\}}d}#t$rY,wxYw|;|SNTF)r]rrE)rrr exprsFoundedummys r_skipIgnorableszParserElement._skipIgnorablesOs  J%  *%&XXh%<%< U%) *&D  s . ;;c|jr|||}|jr;|j}t |}||kr|||vr|dz }||kr |||v|SNr)r]rrXrYr)rrrwtinstrlens rpreParsezParserElement.preParse\s   6&&x55C   B8}}H..Xc]b%8%8q..Xc]b%8%8 rc |gfSrrrrrrzs rr zParserElement.parseImplhs Bwrc|Srrrrr tokenlists r postParsezParserElement.postParseksrc Ld\}}}|j}|s|jr%|j|r|j|||| |r|jr|||} n|} | } |js| t |krN ||| |\}} nL#t$r%t|t ||j |wxYw||| |\}} n#t$rK} |j|r|j||| || |jr||| || d} ~ wwxYw|r|jr|||} n|} | } |js| t |krN ||| |\}} nL#t$r%t|t ||j |wxYw||| |\}} | ||| } t| |j|j|j} |jrU|s|jrK|r |jD]} ||| | } n*#t$r}td}||_|d}~wwxYw| B| | ur>t| |j|jot)| tt*f|j} n#t$r,} |j|r|j||| || d} ~ wwxYw|jD]} ||| | } n*#t$r}td}||_|d}~wwxYw| B| | ur>t| |j|jot)| tt*f|j} |r'|j|r|j||| ||| || fS)N)rrr)rGrHz exception raised in parse action)r^rTrcrdrr`rr rXrErar rrHrVrWrbrSre __cause__rrP)rrrrzr{TRYMATCHFAIL debuggingpreloc tokensStarttokenserr retTokensrparse_action_excrs rr zParserElement._parseNoCacheos"UDZ $ J$ J % <&!#&xd;;; !D$5!!]]8S99FF F$ %N3x==)@)@Y&*nnXvy&Q&Q VV%YYY,Xs8}}dkSWXXXY#'..69"M"MKC   $T*N+D%d+Hk4MMM?FOOHk4EEE    1 x55 K! JVs8}}%<%<U"&..69"M"MKC!UUU(3x==$+tTTTU#nnXvyII V#v66 )9$/Y]Yjkkk  " K" Kd.@" K! K". O O&%'R+y%I%IFF)&&&"01S"T"TC,C%=BC%/CC%% D:/AD55D:<F/G1 J9; I J9 I0I++I00AJ99 K/'K**K/< L  L1L,,L1c |||ddS#t$rt|||j|wxYw)NFrzr)rrGrErarrrs rtryParsezParserElement.tryParsesZ C;;x;>>qA A" C C C 3 TBB B Cs  "Acd |||dS#ttf$rYdSwxYwr)rrErXrs r canParseNextzParserElement.canParseNextsK  MM(C ( ( (4 +   55 s //ceZdZdZdS)ParserElement._UnboundedCachec2itx|_fd}fd}fd}fd}tj|||_tj|||_tj|||_tj|||_dS)Nc0|Srrrrcache not_in_caches rrz3ParserElement._UnboundedCache.__init__..getsyyl333rc||<dSrr)rrrmrs rrz3ParserElement._UnboundedCache.__init__..sets"c rc0dSrrrrs rrz5ParserElement._UnboundedCache.__init__..clears rc"tSrrrs r cache_lenz9ParserElement._UnboundedCache.__init__..cache_lens5zz!r)rBrtypes MethodTyperrrrs)rrrrrrrs @@rrz&ParserElement._UnboundedCache.__init__sE/5xx 7D   4 4 4 4 4 4 # # # # #      " " " " "'T22DH'T22DH)%66DJ +It<.get 99S,777rc||<tkr< dn#t$rYnwxYwtk:dSdSr)rpopitemrV)rrrmrsizes rrz.ParserElement._FifoCache.__init__..setsv!&E#Je**t++!!MM%0000'!!! D!e**t++++++s 1 >>c0dSrrrs rrz0ParserElement._FifoCache.__init__..clearsKKMMMMMrc"tSrrrs rrz4ParserElement._FifoCache.__init__..cache_lenu::%r) rBr _OrderedDictrrrrrrs)rrrrrrrrs ` @@rrz!ParserElement._FifoCache.__init__s3988;!L$888888!!!!!!"""""&&&&&!+C66 +C66"-eT:: $/ 4@@ rNrrrr _FifoCacher( A A A A ArrceZdZdZdS)rcftx|_itjgfd}fd}fd}fd}t j|||_t j|||_t j|||_t j|||_ dS)Nc0|Srrrs rrz.ParserElement._FifoCache.__init__..getrrc||<tkr;dtk;|dSr)rrpopleftr)rrrmrkey_fifors rrz.ParserElement._FifoCache.__init__..setsh!&E#Jh--$.. ("2"2"4"4d;;;h--$..OOC(((((rcXdSrr)rrrs rrz0ParserElement._FifoCache.__init__..clears&KKMMMNN$$$$$rc"tSrrrs rrz4ParserElement._FifoCache.__init__..cache_lenrr) rBr collectionsdequerrrrrrs) rrrrrrrrrs ` @@@rrz!ParserElement._FifoCache.__init__ s3988;!L&,R66888888))))))) %%%%%%&&&&&!+C66 +C66"-eT:: $/ 4@@ rNrrrrrzParserElement._FifoCacherrrcd\}}|||||f}tj5tj}||} | |jurtj|xxdz cc< |||||} ||| d| df| cdddS#t$r)} ||| j | j d} ~ wwxYwtj|xxdz cc<t| tr| | d| dfcdddS#1swxYwYdS)Nrrr)rJpackrat_cache_lock packrat_cacherrpackrat_cache_statsr rrrCr>rrr ) rrrrzr{HITMISSlookuprrmrs r _parseCachezParserElement._parseCache+s T#|Y?  - 1 1!/EIIf%%E***1$7771<777! ..xiVVE IIfuQxq&ABBB  1 1 1 1 1 1 1 1*IIflblBG&<===1#666!;666eY// KQxq0% 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1s7AEB;77E; C.$C))C..AEEEctjdgttjztjdd<dSr<)rJrrrrrrr resetCachezParserElement.resetCacheDs@#))+++01sS9Z5[5[/[ )!!!,,,rctjsndt_|$tt_n$t|t_tjt_dSdS)aEnables "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)rJ_packratEnabledrrrrr)cache_size_limits r enablePackratzParserElement.enablePackratJsf6, =,0M )'.;.K.K.M.M ++.;.F.FGW.X.X +#0# ['aaaaa'] Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text rrN)rJrr_ streamliner]r\ expandtabsrrr2rOrCverbose_stacktracer@rPr)rrparseAllrrrsers r parseStringzParserElement.parseStringms3B   """  OO   !  A LLNNNN} -**,,H ++h22KC )mmHc22WWy{{* (C(((M"   / 366B(,(<(  OO   !  A LLNNNN} 4X1133Hx==] +  """ //g &:&:)'Z#66F&-ghU&S&S&SOGV}}1 $fg5555"*&0j3&?&?G&}}&- #q")CC$qj&%%% 1*CCC% //g &:&:&:&://&:&://("   / 366B(,(<(.s'''Q'1'''rrr)r\rrrrHrGrPrrr_flattenrCrJrr@rPr)rrrlastErrrrs rrzParserElement.transformStringsh(  ??844  1a 8E!G,---&!!\22&qxxzz)#At,,&q 1  JJx' ( ( (''c'''C773uhsmm4455 5!   / 366B(,(<(.7s X X Xwq!Q X X XrrN)rHrrCrJrr@rPr)rrrrs r searchStringzParserElement.searchString!s*  X X$//(J2W2W X X XYY Y!   / 366B(,(<(", 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. 4Cannot combine element of type %s with ParserElementr stacklevelN) Ellipsis _PendingSkiprrUrKrJwarningswarnr SyntaxWarningr+rs rrzParserElement.__add__Zs6 H  %% % eZ ( ( 4,,U33E%//  MPSWX]S^S^^'A 7 7 7 74D%=!!!rc.|turt|d|zSt|tr||}t|t s.t jdt|ztddS||zS)z` Implementation of + operator when left operand is not a :class:`ParserElement` _skipped*rrrN) rrNrrUrKrJrrrrrs rrzParserElement.__radd__s H  6$<< ,,t3 3 eZ ( ( 4,,U33E%//  MPSWX]S^S^^'A 7 7 7 74t|rct|tr||}t|ts.t jdt |ztddS|t z|zS)zT Implementation of - operator, returns :class:`And` with error stop rrrN) rrUrKrJrrrrr+ _ErrorStoprs r__sub__zParserElement.__sub__s eZ ( ( 4,,U33E%//  MPSWX]S^S^^'A 7 7 7 74cnn&&&..rct|tr||}t|ts.t jdt |ztddS||z S)z` Implementation of - operator when left operand is not a :class:`ParserElement` rrrNrrUrKrJrrrrrs r__rsub__zParserElement.__rsub__z eZ ( ( 4,,U33E%//  MPSWX]S^S^^'A 7 7 7 74t|rc|turd}nAt|tr,|ddtfkrd|ddzdzdd}t|tr|d}}nWt|tr$td|D}|d zdd}|d d|df}t|dtrY|dQ|ddkrt S|ddkrt S|dzt zSt|dtr&t|dtr |\}}||z}nTt d t|dt|dt d t||dkrtd |dkrtd ||cxkrdkrnntd|rIfd|r5|dkr|z}nHtg|z|z}n(|}n|dkr}ntg|z}|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`` )rNNrr[rrrc30K|]}|tur|ndVdSr)rrs rrz(ParserElement.__mul__..s0JJqq00!!dJJJJJJrNNz8cannot 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)cj|dkrt|dz zStSr)rA)nmakeOptionalListrs rr$z/ParserElement.__mul__..makeOptionalLists;q55#D+;+;AE+B+B$BCCC#D>>)r) rrtuplerrXr?rWr ValueErrorr+)rr minElements optElementsrr$s` @r__mul__zParserElement.__mul__s( H  EE u % % 6%){*B*BU122Y&0"1"5E eS ! ! ]',aKK u % % ]JJEJJJJJE\)2A2.EQxE!H %(C(( |U1X-=8q==%d+++8q==$T??*%(?Z-=-===E!Hc** |z%(C/H/H |+0( [{*  Z\`afghai\j\jlpqvwxqylzlz{{{NPTUZP[P[\\ \ ??NOO O ??_`` ` + * * * * * * * * *KLL L  0 * * * * * *  4!##!1!1+!>!>>CCtf{2336F6F{6S6SSCC&&{33a4&;.// rc,||Sr)r)rs r__rmul__zParserElement.__rmul__s||E"""rc2|turt|dSt|tr||}t|t s.t jdt|ztddSt||gS)zL Implementation of | operator - returns :class:`MatchFirst` T) must_skiprrrN) rrrrUrKrJrrrrr<rs r__or__zParserElement.__or__s H  555 5 eZ ( ( 4,,U33E%//  MPSWX]S^S^^'A 7 7 7 744-(((rct|tr||}t|ts.t jdt |ztddS||zS)z` Implementation of | operator when left operand is not a :class:`ParserElement` rrrNrrs r__ror__zParserElement.__ror__ rrct|tr||}t|ts.t jdt |ztddSt||gS)zD Implementation of ^ operator - returns :class:`Or` rrrN) rrUrKrJrrrrrBrs r__xor__zParserElement.__xor__ s eZ ( ( 4,,U33E%//  MPSWX]S^S^^'A 7 7 7 744-   rct|tr||}t|ts.t jdt |ztddS||z S)z` Implementation of ^ operator when left operand is not a :class:`ParserElement` rrrNrrs r__rxor__zParserElement.__rxor__ rrct|tr||}t|ts.t jdt |ztddSt||gS)zF Implementation of & operator - returns :class:`Each` rrrN) rrUrKrJrrrrr1rs r__and__zParserElement.__and__' s eZ ( ( 4,,U33E%//  MPSWX]S^S^^'A 7 7 7 74T5M"""rct|tr||}t|ts.t jdt |ztddS||zS)z` Implementation of & operator when left operand is not a :class:`ParserElement` rrrNrrs r__rand__zParserElement.__rand__3 rrc t|S)zH Implementation of ~ operator - returns :class:`NotAny` )r>rs r __invert__zParserElement.__invert__? sd||rc:td|jjz)Nz%r object is not iterable)rWr>rrs rrzzParserElement.__iter__E s3dn6MMNNNrc  t|tr|f}t|n#t$r||f}YnwxYwt |dkret jd|ddt |dkr"dt |nd|t|ddz}|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``. rz.only 1 or 2 index arguments supported ({0}{1})Nr)z ... [{0}]r) rrryrWrrrrr%)rrrs rr:zParserElement.__getitem__J s( #s## f IIII   *CCC  s88a<< MJQQRUVXWXVXRYSVWZS[S[^_S_S_Q\PbPbcfgjckckPlPlPlegii j j j U3rr7^^# s '*;;cX|||S|S)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") )rorrs r__call__zParserElement.__call__n s,  ''-- -99;; rc t|S)z Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from cluttering up returned output. )rQrs rsuppresszParserElement.suppress s ~~rcd|_|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. FrXrs rleaveWhitespacezParserElement.leaveWhitespace s $ rc0d|_||_d|_|S)z8 Overrides the default whitespace chars TF)rXrYrZ)rrHs rsetWhitespaceCharsz ParserElement.setWhitespaceChars s #%*" rcd|_|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\rs r parseWithTabszParserElement.parseWithTabs s   rc2t|trt|}t|tr$||jvr|j|n9|jt||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'] )rrUrQr]rrrs rignorezParserElement.ignore s eZ ( ( $UOOE eX & & <D,,, ''...   # #HUZZ\\$:$: ; ; ; rcR|pt|pt|ptf|_d|_|S)zT Enable display of debugging messages while doing pattern matching. T)rr"r$rcr^)r startAction successActionexceptionActions rsetDebugActionszParserElement.setDebugActions s8)D,D*H.H,L0LN  rcf|r'|tttnd|_|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)rNrr"r$r^)rflags rrlzParserElement.setDebug s7J    !9;UWs t t t tDJ rc|jSrr rs rrzParserElement.__str__ s yrc t|Srrrs rrzParserElement.__repr__ rrc"d|_d|_|Sr )r_rUrs rrzParserElement.streamline s  rcdSrrr.s rcheckRecursionzParserElement.checkRecursion s rc0|gdS)zj Check defined expressions for valid structure, check for infinite recursive definitions. N)rU)r validateTraces rvalidatezParserElement.validate s Brc |}nL#t$r?t|d5}|}dddn #1swxYwYYnwxYw |||S#t$rD}t jrt|dd||j |_ |d}~wwxYw)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) readropenrrCrJrr@rPr)rfile_or_filenamer file_contentsfrs r parseFilezParserElement.parseFile s!  ),1133MM ) ) )&,, ) !  ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ##M8<< <!   / 366B(,(<(>> #9#@#@ASUYZ[U\U\Uegh#i#ijjjjjjjjkJJv{{{99::::=&   %/4G%H%HP b199JJtBFA///JJsc"&!nnq&89C?%GHHHHJJsRV|c1E9::: 8c"gg-...!2l    -C8999!2l , '#JJrNNNtyy~~&&&   q&k * * * * ""s??K BH## J"-A*JJ" O)CN'' O)4+O$$O)FTr)rr)TrqTTFNN)SrrrrrFrr&rIrMrrPrrrmrqrorrrrrrrr rr rrrBrrrrr rrrrrrrr_MAX_INTrrrrrrrrr)r+r.r0r2r4r6r8r:rzr:r>r@rCrErGrIrNrlrrrrUrXr`rcrerirkrmrrrrrrJrJGs33# 2 2\ 200\0*[ ####.:   ::::.&///b2         UUUUnCCC =====&===, A A A A A A A A A: A A A A A A A A:Ma&1111.F\\\\O = = =\ =D8888t/7HHHHT...`19@(052$"$"$"L    / / /   HHHT### ) ) )    ! ! !    # # #    OOO """H(0))))V        ,######(69QU`#`#`#`#`#`#rrJc2eZdZdfd ZdZdZdZxZS)rFctt|t|t zdd|_|j|_||_||_ dS)Nr2...) superrrrr2rrUrFanchorr-)rrr-r>s rrz_PendingSkip.__init__ sa lD!!**,,,4%''>**227EBB L  "rct|dd}jrNd}fd}j||z||z|zSj|z|zS)Nrrc|jr|jdgkr|d=|dddSdS)Nrr_skipped)rrGrrs rr-z'_PendingSkip.__add__..must_skip sPz,QZ%6%6%8%8RD%@%@!EE*d+++++&A%@rc|jdddgkr4|d}dtjzdz|d<dSdS)Nrrrz missing .show_skip sa:$$&&rss+t33eeJ//G$/$t{2C2C$Cc$IAjMMM43r)rNrmr-rr)rrskipperr-rs` rrz_PendingSkip.__add__ s.&--''..{;; > C , , , J J J J JK''))":":9"E"EEgii..y99:=BC C{W$u,,rc|jSr)rUrs rrz_PendingSkip.__repr__ s |rc td)NzBuse of `...` expression without following SkipTo target expression)r rrs rr z_PendingSkip.parseImpl s\]]]rr)rrrrrrr  __classcell__r>s@rrr sq######--- ^^^^^^^rrc"eZdZdZfdZxZS)rRzYAbstract :class:`ParserElement` subclass, for defining atomic matching patterns. cZtt|ddSNFrf)rrRrrr>s rrzToken.__init__ s* eT##U#33333rrrrrrrrs@rrRrR sB444444444rrRc"eZdZdZfdZxZS)r2z'An empty token, will always match. ctt|d|_d|_d|_dS)Nr2TF)rr2rrFr[r`rs rrzEmpty.__init__ s< eT##%%% ""rrrs@rr2r2 sB#########rr2c*eZdZdZfdZddZxZS)r=z#A token that will never match. ctt|d|_d|_d|_d|_dS)Nr=TFzUnmatchable token)rr=rrFr[r`rars rrzNoMatch.__init__ sA gt%%''' "") rTc0t|||j|r)rErars rr zNoMatch.parseImpl$ sXsDK>>>rrrrrrrr rrs@rr=r= sV*****????????rr=c*eZdZdZfdZddZxZS)r:aToken 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`. ctt|||_t ||_ |d|_n8#t$r+tj dtdt|_ YnwxYwdt|jz|_d|jz|_d|_d|_|jdkr$t%|turt&|_ dSdSdS) Nrz2null string passed to Literal; use Empty() insteadrr"%s"rjFr)rr:rmatchrmatchLenfirstMatchCharrXrrrr2r>rrFrar[r`r_SingleCharLiteralr matchStringr>s rrzLiteral.__init__6 s gt%%'''  K((  #"-a.D   # # # MN)a 9 9 9 9"DNNN #U4:... !DI- #" =A  $t**"7"7/DNNN  "7"7s A2BBTc|||jkr,||j|r||jz|jfSt |||j|r)rrrrrErars rr zLiteral.parseImplJ sV C=D/ / /H4G4G TW4X4X /& 2 2XsDK>>>rrrrs@rr:r:( sV  00000(????????rr:ceZdZddZdS)rTcj|||jkr |dz|jfSt|||j|r)rrrErars rr z_SingleCharLiteral.parseImplP s; C=D/ / /7DJ& &XsDK>>>rNrrrrr rrrrrO s(??????rrcVeZdZdZedzZd fd Zd dZfdZe d Z xZ S) r7aToken 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`. _$NFc tt|| tj}||_t ||_ |d|_n,#t$rtj dtdYnwxYwd|jz|_ d|j z|_ d|_d|_||_|r-||_|}t'||_dS)Nrz2null string passed to Keyword; use Empty() insteadrrrrjF)rr7rDEFAULT_KEYWORD_CHARSrrrrrXrrrrFrar[r`caselessupper caselessmatchr identChars)rrrrr>s rrzKeyword.__init__s s gt%%'''   6J  K((  7"-a.D   7 7 7 MN'A 7 7 7 7 7 7 7TZ' !DI- #"   ,!,!2!2!4!4D #))++Jj//s A!!&B  B Tc|jr||||jz|jkr|t ||jz ks)|||jz|jvr;|dks$||dz |jvr||jz|jfSn|||jkr|jdks||j|r[|t ||jz ks|||jz|jvr)|dks||dz |jvr||jz|jfSt|||j |rd) rrrrrrrrrrErars rr zKeyword.parseImpl se = ;#cDM11288::d>PPPH  ===$S4=%89??AAXX$S1W-3355T_LLT]*DJ66} 333]a''8+>+>tz3+O+O' CMMDM$AAA (t})< =T_ T T AXX#'):$/)Q)Q. ::XsDK>>>rcxtt|}tj|_|Sr)rr7rrr)rrr>s rrz Keyword.copy s- '4 % % ' '4 rc|t_dS)z,Overrides the default Keyword chars N)r7rrGs rsetDefaultKeywordCharszKeyword.setDefaultKeywordChars s).%%%rrr) rrrrrZrrr rr&rrrs@rr7r7X s0&,*******????& ..\.....rr7c*eZdZdZfdZddZxZS)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`.) ctt||||_d|jz|_d|jz|_dS)Nz'%s'rj)rr-rr returnStringrFrars rrzCaselessLiteral.__init__ sV ot$$--k.?.?.A.ABBB'T.. !DI- rTc||||jz|jkr||jz|jfSt |||j|r)rrrrrErars rr zCaselessLiteral.parseImpl sW Cdm++ , 2 2 4 4 B B&(99 9XsDK>>>rrrrs@rr-r- sV  .....????????rr-c$eZdZdZdfd ZxZS)r,z Caseless version of :class:`Keyword`. Example:: OneOrMore(CaselessKeyword("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD'] (Contrast with example for :class:`CaselessLiteral`.) Nc^tt|||ddS)NTr)rr,r)rrrr>s rrzCaselessKeyword.__init__ s/ ot$$--k:PT-UUUUUrrrrs@rr,r, sQVVVVVVVVVVrr,c,eZdZdZdfd ZddZxZS)raA 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']}) rctt|||_||_||_d|j|jfz|_d|_d|_dS)Nz&Expected %r (with up to %d mismatches)F) rrrrF match_string maxMismatchesrar`r[)rrrr>s rrzCloseMatch.__init__ sd j$((***  (*>$BSUYUgAhh "#rTc|}t|}|t|jz}||kr|j}d}g} |j} tt ||||D]:\}} | \} } | | kr*| |t| | krn,;|dz}t |||g}||d<| |d<||fSt|||j|)Nrroriginal mismatches) rrrrrrrHrEra)rrrrzstartrmaxlocrmatch_stringlocrrs_msrcmatresultss rr zCloseMatch.parseImpl sx==T./// X  ,LOJ .M(1#hs6z6JL2Y2Y(Z(Z $ $$S#::%%o666:66%)&s(;'<==&2 #(2 %G|#XsDK>>>r)rrrrs@rrr s\@$$$$$$????????rrc6eZdZdZd fd Zd dZfd ZxZS) rUaX 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=",") NrrFcJtt|rStdfd|D}|r!dfd|D}||_t||_|r||_t||_n||_t||_|dk|_ |dkrtd||_ |dkr||_ n t|_ |dkr||_ ||_ t||_d|jz|_d|_||_d |j|jzvr2|dkr-|dkr(|dkr#|j|jkrd t'|jz|_nt+|jdkr7t-j|jd t'|jd |_n2d t'|jd t'|jd |_|jrd|jzdz|_ t-j|j|_|jj|_t6|_dS#t:$r d|_YdSwxYwdSdSdSdS)Nrc3$K|] }|v|V dSrrrr excludeCharss rrz Word.__init__..H s-NNa8M8M8M8M8M8MNNrc3$K|] }|v|V dSrrrs rrz Word.__init__..J s-#R#R!A\r ) rrrminmaxexactrrr>s `rrz Word.__init__D s dD""$$$  S|,,LNNNN9NNNNNI SGG#R#R#R#Ry#R#R#RRR &Y  ,!*D  ^^DNN!*D  ^^DN!G 77yzz z 77DKK"DK 199DKDK$KK !DI- "" d(4+== = =3!88PSWXPXPX]bfg]g]g!T%777 '*@AS*T*T T T'((A---/Yt7I-J-J-J-J-CDDV-W-W-W-W!Z .0FdFX/Y/Y/Y/Y/EdFX/Y/Y/Y/Y!\ ~ > % 5 =  ,*T]33!%  !+      > =88PXPX]g]gsJJJTc|||jvrt|||j||}|dz }t|}|j}||jz}t ||}||kr|||vr|dz }||kr |||vd}||z |jkrd}nF|jr||kr |||vrd}n,|j r%|dkr ||dz |vs||kr |||vrd}|rt|||j|||||fS)NrFTr) rrErarrrrrrr) rrrrzrr bodycharsrthrowExceptions rr zWord.parseImpl} sY C= . . 3 TBB B qx==N $VX&&Fllx} 99 1HCFllx} 99 ; $ $!NN   &3>>hsmy6P6P!NN ^ & huqy1Y>>X~~(3-9*D*D!%  C 3 TBB BHU3Y'''rc< tt|S#t$rYnwxYw|jVd}|j|jkr+d||jd||jd|_nd||jz|_|jS)NcFt|dkr |dddzS|S)Nrr)rs r charsAsStrz Word.__str__..charsAsStr s(q66A::RaR55=(HrzW:(rrzW:(%s))rrUrr rUrr)rrr>s rrz Word.__str__ s t$$,,.. .    D  <     !T%7777/9z$:L/M/M/M/MzzZ^ZlOmOmOmOmn '**T5G*H*HH | &* 77)NrrrFNrrrrrrr rrrs@rrUrU sv33h7,7,7,7,7,7,r((((8rrUceZdZddZdS)rTc|||}|st|||j||}||fSr)rrEraendgroup)rrrrzrs rr z_WordRegex.parseImpl sTx-- C 3 TBB BjjllFLLNN""rNrrrrrrr s(######rrc$eZdZdZdfd ZxZS)rYzA short-cut class for defining ``Word(characters, exact=1)``, when defining a match of any single character in a string of characters. FNc>tt||d||dtd|jz|_|rd|jz|_tj|j|_|jj |_ dS)Nr)rrr[%s]rz\b%s\b) rrYrrrrrrrrr)rcharsetrrr>s rrz Char.__init__ s dD""7!yWc"ddd!78O8O!P!PP  6% 5DM*T]++  r)FNrrs@rrYrY sG&&&&&&&&&&rrYcLeZdZdZd fd Zd dZd dZd dZfd Zd Z xZ S) rMahToken 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^tt|t|tr|st jdtd||_||_ tj |j|j |_ |j|_ n#tj$r!t jd|ztdwxYwt|dr2t|dr"||_ |jx|_|_ ||_ nt!d|j j|_t'||_d|jz|_d |_|d d u|_||_||_|jr |j|_|jr|j|_d Sd 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() insteadrr$invalid pattern (%s) passed to RegexpatternrzCRegex may only be constructed with a string or a compiled RE objectrjFrN)rrMrrrUrrrrflagsrrr sre_constantserrorrrWrrrrFrar`r[ asGroupListasMatchparseImplAsGroupListr parseImplAsMatch)rrrrrr>s rrzRegex.__init__ s eT##%%% gz * * c ; P+;;;;#DLDJ *T\4:>> $   &    DwN+;;;;  Wi ( ( cWWg-F-F cDG+2? :DL4=DJJabb b  $KK !DI- ""mmB//t;&   7!6DN < 3!2DNNN 3 3s +0B0C Tc<|||}|st|||j||}t |}|}|r|D] \}}|||< ||fSr)rrErarrHr groupdictrh) rrrrzrrdr`r\s rr zRegex.parseImpl sx-- C 3 TBB Bjjll6<<>>**          1ACxrc|||}|st|||j||}|}||fSr)rrErargroupsrrrrzrrs rrzRegex.parseImplAsGroupList sWx-- C 3 TBB BjjllmmooCxrc|||}|st|||j||}|}||fSr)rrErarr s rrzRegex.parseImplAsMatch! sOx-- C 3 TBB BjjllCxrc tt|S#t$rYnwxYw|jdt |jz|_|jS)NzRe:(%s))rrMrr rUr=rrs rrz Regex.__str__* sl %%--// /    D  < $tDL'9'99DL|rc8jr*tjdtdt jr9t r*tjdtdt jrfd}nfd}|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)rrz9cannot use sub() with a callable with Regex(asMatch=True)c:|dSr<)expand)rrepls rrzRegex.sub..paK say''---rcFj|dSr<)rra)rrrs rrzRegex.sub..paN sw{{4333r)rrrr SyntaxErrorrrr)rrrs`` rraz Regex.sub5 s   MI'A 7 7 7 7--  < HTNN MU'A 7 7 7 7--  < 4 . . . . . . 4 4 4 4 4 4""2&&&r)rFFr) rrrrrr rrrrarrs@rrMrM s.+3+3+3+3+3+3Z         '''''''rrMc:eZdZdZ dfd Zd dZfdZxZS) rKa& 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 "tt|}|s*t jdt dt||}n@|}|s*t jdt dt|_t|_ |d_ |_ t|_ |_|_|_|_|rpt$jt$jz_t%jjdt/j d|durt/|pdd_nYd_t%jjdt/j dd |durt/|pdd_tj d krYxjd d fd t5tj d z ddDzdzz c_|r%xjdt%j|zz c_|rFxjdt%j|zz c_t%jjdz_xjdt%jj zz c_ t%jjj_j_jj_n8#t@j!$r&t jdjzt dwxYwtE_#dj#z_$d_%d_&dS)Nz$quoteChar cannot be the empty stringrrz'endQuoteChar cannot be the empty stringrz(?:[^rrz\n\rrz|(?:z)|(?:c3K|]C}tjjd|dtj|dVDdS)Nz[^r)rr endQuoteCharr)rrrs rrz(QuotedString.__init__.. s|&Y&Y*+469T=NrPQr=R3S3S3S3S3I$J[\]J^3_3_3_3_'a&Y&Y&Y&Y&Y&Yrrrz|(?:%s)z|(?:%s.)z(.)z)*%srrjFT)'rrKrrrrrr quoteCharr quoteCharLenfirstQuoteCharrendQuoteCharLenescCharescQuoteunquoteResultsconvertWhitespaceEscapesr MULTILINEDOTALLrrrrrreescCharReplacePatternrrrrrrrrFrar`r[) rrrr multiliner rr!r>s ` rrzQuotedString.__init__y s lD!!**,,,OO%%  M@-\] ^ ^ ^ ^--   $LL'--//L $ Gcdeeee!mm#" NN'l("<00   ,(@%  s 1DJ.0i.G.G.G.G.DTEVWXEY.Z.Z.Z/6d/B/fG]^eGfGf/ljl/l/loDLLDJ24)DN2K2K2K2K2HIZ[\I]2^2^2^2^3:$3F3jKabiKjKj3pnp3p3psDL t ! !A % % LL&Y&Y&Y&Y/4S9J5K5Ka5OQRTV/W/W&Y&Y&YYYY[^_ `LL  ? LLZ")H*=*== >LL  I LL[29W+=+== >LL)+4<)@)@5)HD & 29T->#?#??@  jtz::DG LDM GMDMM"    M@4<O'A 7 7 7 7   $KK !DI- ""s $AL&&5McV|||jkr|||pd}|st|||j||}|}|jr||j|j }t|trd|vr>|j r7ddddd}| D]\}}| ||}|jrtj|jd|}|jr | |j|j}||fS)Nr r   )\trsz\fz\rz\g<1>)rrrErarrr rrrrUr!rhrrrrar$rr) rrrrzrrws_mapwslitwschars rr zQuotedString.parseImpl sJ#$"55V$--RU:V:V^Z^ C 3 TBB Bjjllllnn   Hd'$*>)>>?C#z** H3;;4#@;#### F *099 v!kk%88<L&!;XsKKC=H++dmT5FGGCCxrc tt|S#t$rYnwxYw|jd|jd|j|_|jS)Nzquoted string, starting with z ending with )rrKrr rUrrrs rrzQuotedString.__str__ sr t,,4466 6    D  <  OS~~~_c_p_pqDL|r)NNFTNTrrrs@rrKrKR s%%LJORV?#?#?#?#?#?#B!!!!F         rrKc6eZdZdZdfd Zd dZfdZxZS) r.aToken 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'] rrcztt|d|_||_|dkrt d||_|dkr||_n t|_|dkr||_||_t||_ d|j z|_ |jdk|_ d|_ dS)NFrzfcannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permittedrrj)rr.rrXnotCharsr&rrrrrFrar[r`)rr1rrrr>s rrzCharsNotIn.__init__ s j$((***#  77]^^ ^ 77DKK"DK 199DKDK$KK !DI- #{a/"rTc`|||jvrt|||j||}|dz }|j}t||jzt |}||kr|||vr|dz }||kr |||v||z |jkrt|||j|||||fSr)r1rErarrrr)rrrrzrnotcharsmaxlens rr zCharsNotIn.parseImpls C=DM ) ) 3 TBB B q=UT[(#h--88Fllx}H<< 1HCFllx}H<< ; $ $ 3 TBB BHU3Y'''rc tt|S#t$rYnwxYw|j?t |jdkrd|jddz|_nd|jz|_|jS)Nrz !W:(%s...)z!W:(%s))rr.rr rUrr1rs rrzCharsNotIn.__str__&s T**2244 4    D  < 4=!!A%%+dmBQB.?? (4=8 |r)rrrrrrs@rr.r. st&######2((((         rr.ceZdZdZidddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*Zd1fd. Zd2d0ZxZS)3rTaSpecial 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. rzr'zr zr)zr(z zu zu᠎zu z u z u z u z u zu zu zu zu zz z zzzz)u u u​u u u  rrctt|_dfdjDddjD_d_djz_ |_ |dkr|_ n t_ |dkr|_ |_ dSdS)Nrc3.K|]}|jv |VdSr) matchWhite)rrrs rrz!White.__init__..Ys/'_'_aatF^F^F^F^F^F^'_'_rc3:K|]}tj|VdSr)rT whiteStrsrs rrz!White.__init__..[s)IIAU_Q/IIIIIIrTrjr) rrTrr;rErrYrFr[rarrr)rwsrrrr>s` rrzWhite.__init__Vs eT##%%% '_'_'_'_4?'_'_'_ _ _```WWIIIIIII "!DI-  77DKK"DK 199DKDKKK 9rTcj|||jvrt|||j||}|dz }||jz}t |t |}||kr)|||jvr|dz }||kr|||jv||z |jkrt|||j|||||fSr)r;rErarrrr)rrrrzrrs rr zWhite.parseImpljs C= / / 3 TBB B q$VS]]++Fllx}?? 1HCFllx}?? ; $ $ 3 TBB BHU3Y'''r)r8rrrr)rrrrr=rr rrs@rrTrT4sT  f  g  f  f  f  8   '  0  ;  ;  <  <  )  (  ' #! " (# $"!'(/   I2      ( ( ( ( ( ( ( ( (rrTceZdZfdZxZS)_PositionTokenctt||jj|_d|_d|_dSr)rrArr>rrFr[r`rs rrz_PositionToken.__init__{sA nd##,,...N+ ""rrrrrrrs@rrArAzs8#########rrAc0eZdZdZfdZdZddZxZS)r5zaToken to advance to a specific column of input text; useful for tabular report scraping. cdtt|||_dSr)rr5rr`)rcolnor>s rrzGoToColumn.__init__s* j$((***rc~t|||jkrt|}|jr|||}||krq||rWt|||jkr>|dz }||kr3||rt|||jk>|Sr)r`rr]risspace)rrrrs rrzGoToColumn.preParses sH   ) )8}}H :**8S99..Xc]%:%:%<%<.S(ASASW[W_A_A_q..Xc]%:%:%<%<.S(ASASW[W_A_A_ rTct||}||jkrt||d|||jz|z }|||}||fS)NzText not in expected columnr`rE)rrrrzthiscolnewlocrs rr zGoToColumn.parseImpls[c8$$ TX   30MtTT Ttx')sF{#s{rr)rrrrrrr rrs@rr5r5serr5c*eZdZdZfdZddZxZS)r9aMatches 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'] cdtt|d|_dS)NzExpected start of line)rr9rrars rrzLineStart.__init__s* i''))). rTc`t||dkr|gfSt|||j|r)r`rErars rr zLineStart.parseImpls6 sH   " "7NXsDK>>>rrrrs@rr9r9sV*/////????????rr9c*eZdZdZfdZddZxZS)r8zTMatches if current position is at the end of a line within the parse string ctt||tjddd|_dS)Nr rzExpected end of line)rr8rrErJrFrrars rrzLineEnd.__init__sR gt%%'''  A I I$PR S STTT, rTc|t|kr*||dkr|dzdfSt|||j||t|kr|dzgfSt|||j|)Nr rrrErars rr zLineEnd.parseImpls{ X  }$$Qw}$$XsDKFFF CMM ! !7B;  3 TBB Brrrrs@rr8r8s^----- C C C C C C C Crr8c*eZdZdZfdZddZxZS)rPzLMatches if current position is at the beginning of the parse string cdtt|d|_dS)NzExpected start of text)rrPrrars rrzStringStart.__init__s* k4  ))+++. rTcx|dkr1|||dkrt|||j||gfSr<)rrErars rr zStringStart.parseImplsC !88dmmHa0000$XsDKFFFBwrrrrs@rrPrPsV/////rrPc*eZdZdZfdZddZxZS)rOzBMatches if current position is at the end of the parse string cdtt|d|_dS)NzExpected end of text)rrOrrars rrzStringEnd.__init__s* i''))), rTc|t|krt|||j||t|kr|dzgfS|t|kr|gfSt|||j|rrSrs rr zStringEnd.parseImplsx X   3 TBB B CMM ! !7B;  3x== 7N 3 TBB Brrrrs@rrOrOs^-----CCCCCCCCrrOc.eZdZdZeffd ZddZxZS)rWayMatches 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. ctt|t||_d|_dS)NzNot at the start of a word)rrWrr wordCharsrarr\r>s rrzWordStart.__init__s7 i'')))Y2 rTc|dkr8||dz |jvs|||jvrt|||j||gfSrd)r\rErars rr zWordStart.parseImplsQ !88q!T^33}DN::$XsDKFFFBwrrrrrrr}rr rrs@rrWrWs`",333333 rrWc.eZdZdZeffd ZddZxZS)rVa_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. ctt|t||_d|_d|_dS)NFzNot at the end of a word)rrVrrr\rXrar]s rrzWordEnd.__init__ s? gt%%'''Y#0 rTct|}|dkr>||kr8|||jvs||dz |jvrt|||j||gfSrd)rr\rEra)rrrrzrs rr zWordEnd.parseImplsdx== a<.*s,BBD:dJ//BBBBBBrc3pK|]0}t|tr|n|V1dSr)rrUrK)rrrs rrz+ParseExpression.__init__..+sGhh]^ 1j8Q8QX11!444WXhhhhhhrF)rrFrrrRrPrUrKexprsrJr rrWrdrrgrfr>s` rrzParseExpression.__init__s8 ot$$--h777 e^ , , KKE eZ ( ( %22599:DJJ } - - %DJJ x ( ( %KKEBBEBBBBB ihhhhbghhheDJJ %!%[[  % % %#W  %!s?DD)(D)cH|j|d|_|Sr)rgrrUrs rrzParseExpression.append4s$ %     rc|d|_d|jD|_|jD]}||S)zExtends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on all contained expressions.Fc6g|]}|Srrrrs rrz3ParseExpression.leaveWhitespace..=s 3331affhh333r)rXrgrC)rrs rrCzParseExpression.leaveWhitespace9sN$33 333   A       rct|tr\||jvrRtt|||jD]"}||jd#nRtt|||jD]"}||jd#|Sr|)rrQr]rrFrIrg)rrrr>s rrIzParseExpression.ignoreBs eX & & /D,,,ot,,33E:::33AHHT-b12222 /4 ( ( / / 6 6 6Z / /)"-.... rc tt|S#t$rYnwxYw|j)|jjdt|jd|_|jSNz:(r) rrFrr rUr>rrrgrs rrzParseExpression.__str__Ns} $//7799 9    D  < (,(?(?(?tzARARARARSDL|rc tt||jD]}|t |jdkr|jd}t ||jri|jsb|j[|j sT|jdd|jdgz|_d|_ |xj |j zc_ |xj |j zc_ |jd}t ||jrj|jsc|j\|j sU|jdd|jddz|_d|_ |xj |j zc_ |xj |j zc_ dt|z|_|S)Nrrrrrj)rrFrrgrrr>rSrVr^rUr[r`rra)rrrr>s rrzParseExpression.streamlineXs ot$$//111  A LLNNNN tz??a  JqME5$.11 ;!- ;)1!K2"[^tz!}o= # ##u';;##""u'::""JrNE5$.11 ;!- ;)1!K2!Z_u{111~= # ##u';;##""u'::""!E$KK/  rNc||ngdd|gz}|jD]}|||gdSr)rgrXrU)rrWtmprs rrXzParseExpression.validatezs\ - 9}}r111EN  A JJsOOOO Brctt|}d|jD|_|S)Nc6g|]}|Srrrls rrz(ParseExpression.copy..s 222!QVVXX222r)rrFrrgrrr>s rrzParseExpression.copys:OT**//1122tz222  rc @tjri|jD]a}t|trJ|jrCt jdd|t|j |jdbtt| ||S)N]{0}: setting results name {1!r} on {2} expression collides with {3!r} on contained expressionr#rr)r!r#rgrrJrVrrrrrrrFrorrFrprr>s rrozParseExpression._setResultsNames  = 0Z 0 0a//0AM0M#PPVPVXCW[W[\`WaWaWjWXWdQfQf./ 0000_d++;;D.QQQrrr)rrrrrrrCrIrrrXrrorrs@rrFrFs"""""",           D     R R R R R R R R R RrrFcdeZdZdZGddeZd fd ZfdZd dZdZ d Z d Z xZ 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") ceZdZfdZxZS)And._ErrorStopcttj|j|i|d|_|dS)N-)rr+rrrFrC)rrrr>s rrzAnd._ErrorStop.__init__sF 0E#.$ ' ' 0$ A& A A ADI  " " " " "rrCrs@rrr{s8 # # # # # # # # #rrTct|}|rt|vrg}t|D]\}}|turv|t|dz krQt ||dzzjd}|t|dutd||||dd<tt| ||td|jD|_ ||jdj|jdj|_d|_dS)Nrrrz0cannot construct And with sequence ending in ...c3$K|] }|jV dSrr[rls rrzAnd.__init__..%!G!Gq!"2!G!G!G!G!G!GrrT)rPrrrr2rgrrNr rr+rrr[rErYrXrd)rrgrfrrrr skipto_argr>s rrz And.__init__sTU   X&&C$U++ % %48##3u::>))&+gga!e &<%CB%G  #56*#5#5k#B#BCCCC'(Z[[[JJt$$$$E!!!H c4!!%222!!G!GDJ!G!G!GGG  1 8999"jm: rcJ|jrtd|jddDrt|jddD]w\}}|t|trZ|jrSt|jdt r3|jd|j|dzz|jd<d|j|dz<xd|jD|_t t|td|jD|_ |S)Nc3K|]@}t|to&|jot|jdtVAdSrN)rrFrgrrls rrz!And.streamline..s^--a11gagg*QWUW[ZfBgBg------rrrcg|]}||Srrrls rrz"And.streamline..sEEEAq}a}}}rc3$K|] }|jV dSrrrls rrz!And.streamline..rr) rgrrrrFrrr+rrr[)rrrr>s rrzAnd.streamlines3 : F-- JssO----- F%dj"o6611DAqy "1o661 !1,6qwr{L,Q,Q1&'gbkDJq1u4E&E ,0 1q5)EEEEE  c4##%%%!!G!GDJ!G!G!GGG rc4|jd|||d\}}d}|jddD]}t|tjrd}|r ||||\}}n#t $rt $r&}d|_t |d}~wt$r%t |t||j |wxYw||||\}}|s| r||z }||fS)NrFrrT) rgrrr+rrIrCrrrXrrar) rrrrz resultlist errorStopr exprtokensrs rr z And.parseImpls`*Q-..xiV[.\\Z ABB ) )A!S^,,   E[&'hhxi&H&HOC+)CCC'+B$.>>rBBB![[[.xX UYZZZ[#$((8S)"D"DZ )Z//11 )j( JsA66C !B++2Cct|tr||}||SrrrUrKrrs rrz And.__iadd__9 eZ ( ( 4,,U33E{{5!!!rct|dd|gz}|jD]!}|||jsdS"dSr)rgrUr[rr/subRecCheckListrs rrUzAnd.checkRecursions]*111-6  A  _ - - -#    rct|dr|jS|j/ddd|jDzdz|_|jS)NrF{rc34K|]}t|VdSrrrls rrzAnd.__str__..s()G)Gq%(()G)G)G)G)G)Gr}rrFrUrrgrs rrz And.__str__sZ 4  9  < )G)GDJ)G)G)G!G!GG#MDL|rr) rrrrr2rrrr rrUrrrs@rr+r+s"#####U### !!!!!!($2""" rr+cTeZdZdZd fd ZfdZd dZdZdZd Z d fd Z xZ S) rBaRequires 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']] Fctt||||jr%t d|jD|_dSd|_dS)Nc3$K|] }|jV dSrrrls rrzOr.__init__..%%K%K1a&6%K%K%K%K%K%KrT)rrBrrgrr[rhs rrz Or.__init__s` b$  111 : '"%%K%K %K%K%K"K"KD   "&D   rctt|tjr#t d|jD|_|S)Nc3$K|] }|jV dSrrWrls rrz Or.streamline..$!C!C1!,!C!C!C!C!C!Cr)rrBrr*collect_all_And_tokensrrgrWrs rrz Or.streamlinesN b$""$$$  , D!!C!C !C!C!CCCDO rTcxd}d}g}|jD]} |||}|||f1#t$r%} d| _| j|kr | }| j}Yd} ~ [d} ~ wt $rIt||kr3t|t||j|}t|}YwxYw|r| tdd|s%|dd} | |||Sd} |D]~\} } | | dkr| cS | |||\}}|| kr||fcS|| dkr||f} M#t$r%} d| _| j|kr | }| j}Yd} ~ wd} ~ wwxYw| dkr| S||j|_ |t||d|)NrrT)rrgrr no defined alternatives to match) rgrrrErrrXrrasortrrr)rrrrz maxExcLoc maxExceptionrrloc2r best_exprlongestloc1expr1r!s rr z Or.parseImplsG   * *A *zz(C00ay))))" ( ( ($(!7Y&&#&L #I . . .x==9,,#1(CMM18UY#Z#ZL #H I .   LLZ]]DL 9 9 9 B$AJqM  ''#yAAAG& - - e71:%%"NNN -!&hY!G!GJD$t||#Tz))) **"&*&,,,(,C%w**'* $'G ,*$$  ##{L   30RTXYY Ys4? B? A))AB?>B?)E  F*F  Fct|tr||}||Srrrs r__ixor__z Or.__ixor__[rrct|dr|jS|j/ddd|jDzdz|_|jS)NrFrz ^ c34K|]}t|VdSrrrls rrzOr.__str__..e(+I+IE!HH+I+I+I+I+I+Irrrrs rrz Or.__str__`Z 4  9  < +I+Idj+I+I+I!I!IICODL|rc`|dd|gz}|jD]}||dSrrgrUrs rrUzOr.checkRecursioniI*111-6 . .A  _ - - - - . .rc <tjsgtjr[t d|jDr=t jdd|t|j dtt| ||S)Nc3@K|]}t|tVdSrrr+rls rrz%Or._setResultsName..q,::!:a%%::::::r{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 tokensr"rr)r*rr!r"rrgrrrrrrrBrorrFrpr>s rrozOr._setResultsNamens1 "F "::tz::::: " NNTf?tDzzGZO\O\ """" R..t^DDDrrr) rrrrrrr rrrUrorrs@rrBrBs '''''' :Z:Z:Z:Zz""" ... E E E E E E E E E ErrBcTeZdZdZd fd ZfdZd dZdZdZd Z d fd Z xZ S) r<aRequires 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']] Fctt||||jr%t d|jD|_dSd|_dS)Nc3$K|] }|jV dSrrrls rrz&MatchFirst.__init__..rrT)rr<rrgrr[rhs rrzMatchFirst.__init__sb j$((999 : '"%%K%K %K%K%K"K"KD   "&D   rctt|tjr#t d|jD|_|S)Nc3$K|] }|jV dSrrrls rrz(MatchFirst.streamline..rr)rr<rr*rrrgrWrs rrzMatchFirst.streamlinesP j$**,,,  , D!!C!C !C!C!CCCDO rTcd}d}|jD]} ||||}|cS#t$r}|j|kr |}|j}Yd}~Ad}~wt$rIt ||kr3t|t ||j|}t |}YwxYw||j|_|t||d|)Nrr)rgrrErrXrrar) rrrrzrrrrrs rr zMatchFirst.parseImpls   ^ ^A .hhxi88 ! ( ( (7Y&&#&L #I . . .x==9,,#1(CMM18UY#Z#ZL #H I .'#';  ""$Xs4VX\]]]s* B#A  AB#"B#ct|tr||}||Srrrs r__ior__zMatchFirst.__ior__rrct|dr|jS|j/ddd|jDzdz|_|jS)NrFr | c34K|]}t|VdSrrrls rrz%MatchFirst.__str__..rrrrrs rrzMatchFirst.__str__rrc`|dd|gz}|jD]}||dSrrrs rrUzMatchFirst.checkRecursionrrc <tjsgtjr[t d|jDr=t jdd|t|j dtt| ||S)Nc3@K|]}t|tVdSrrrls rrz-MatchFirst._setResultsName..rrrr"rr)r*rr!r"rrgrrrrrrr<rors rrozMatchFirst._setResultsNames1 "F "::tz::::: " NNTf?tDzzGZO\O\ """" Z&&66t^LLLrrr) rrrrrrr rrrUrorrs@rr<r<{s '''''' ^^^^0""" ... M M M M M M M M M Mrr<cBeZdZdZdfd ZfdZddZdZdZxZ S) r1asRequires 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 Tctt|||td|jD|_d|_d|_d|_dS)Nc3$K|] }|jV dSrrrls rrz Each.__init__.. rrT) rr1rrrgr[rXinitExprGroupsrWrhs rrz Each.__init__ s_ dD""5(333!!G!GDJ!G!G!GGG""rctt|td|jD|_|S)Nc3$K|] }|jV dSrrrls rrz"Each.streamline..rr)rr1rrrgr[rs rrzEach.streamlinesE dD$$&&&!!G!GDJ!G!G!GGG rc|jrtd|jD|_d|jD}d|jD}||z|_d|jD|_d|jD|_d|jD|_|xj|jz c_d|_|}|jdd}|jddg}d} | r|z|jz|jz} g} | D]} | ||}| |j t| | | |vr| | n| vr | #t$r| | YwxYwt| t| krd} | |r3d d |D} t||d | z|fd |jDz }g}|D]1} | |||\}}| |2t#|t%g}||fS) Nc3lK|]/}t|tt|j|fV0dSr)rrArhrrls rrz!Each.parseImpl..s?__AzRSU]G^G^_AFQ______rcFg|]}t|t|jSrrrArrls rrz"Each.parseImpl..s)JJJq*Q2I2IJAFJJJrcXg|]'}|j t|ttf%|(Sr)r[rrArMrls rrz"Each.parseImpl..s7ggg!Q-=gjQRU]_dTeFfFfgAgggrcFg|]}t|t|jSr)rrXrrls rrz"Each.parseImpl..s)"["["[aAzAZAZ"[16"["["[rcFg|]}t|t|jSr)rr?rrls rrz"Each.parseImpl..s)!Y!Y!YQ 1i@X@X!Y!&!Y!Y!YrcVg|]&}t|tttf$|'Sr)rrArXr?rls rrz"Each.parseImpl..s0kkk1*QS]_hHi:j:jkQkkkrFTrc34K|]}t|VdSrrrls rrz!Each.parseImpl..9s(::Qa::::::rz*Missing one or more required elements (%s)cPg|]"}t|t|jv |#Srr)rrtmpOpts rrz"Each.parseImpl..=s5]]]Q 1h0G0G]AFV\L\L\qL\L\L\r)rrSrgopt1map optionalsmultioptionals multirequiredrequiredrrrrhremoverErrrsumrH)rrrrzopt1opt2tmpLoctmpReqd matchOrder keepMatchingtmpExprsfailedrmissingrr finalResultsrs @rr zEach.parseImpls   (_______DLJJDJJJJDggtzgggD!D[DN"["[4:"["["[D !Y!Y$*!Y!Y!YD kk kkkDM MMT/ /MM"'D -".#   %'$*==@RRHF ) ) )ZZ&99F%%dl&6&6r!uua&@&@AAAG||q))))f a(((&%%%MM!$$$$$%6{{c(mm++$  %"  hii::':::::G 30\_f0fgg g ]]]]$*]]]]   ' 'A88Hc9==LC   g & & & &:|B'7'788 L  s8E==FFct|dr|jS|j/ddd|jDzdz|_|jS)NrFrz & c34K|]}t|VdSrrrls rrzEach.__str__..Lrrrrrs rrz Each.__str__Grrc`|dd|gz}|jD]}||dSrrrs rrUzEach.checkRecursionPrrr) rrrrrrr rrUrrs@rr1r1s77p /!/!/!/!b.......rr1c^eZdZdZd fd ZddZdZfdZfdZd Z dd Z fd Z xZ S)rDzfAbstract subclass of :class:`ParserElement`, for combining and post-processing parsed tokens. Fc4tt||t|trRt |jtr||}n"|t|}||_ d|_ |w|j |_ |j |_ | |j|j|_|j|_|j|_|j|jdSdSr)rrDrrrU issubclassrKrRr:rrUr`r[rErYrXrWrdr]rrrrfr>s rrzParseElementEnhance.__init__Zs !4((11(;;; dJ ' ' ?$2E:: ?//55// >>   !%!3D "&"5D   # #DO 4 4 4"&"5D "oDO $ 1D    # #D$4 5 5 5 5 5  rTcz|j|j|||dStd||j|)NFrr)rrrErars rr zParseElementEnhance.parseImplls? 9 9##Hc95#QQ Q S$+t<< #INN$$ 9 I % % ' ' ' rct|tr^||jvrTtt|||j%|j|jdnTtt|||j%|j|jd|Sr|)rrQr]rrDrIrrrr>s rrIzParseElementEnhance.ignoreys eX & & 7D,,,)40077>>>9(I$$T%5b%9::: %t , , 3 3E : : :y$   !1"!5666 rctt||j|j|Sr)rrDrrrs rrzParseElementEnhance.streamlinesA !4((33555 9 I " " " rc||vrt||gz|dd|gz}|j|j|dSdSr)rLrrU)rr/rs rrUz"ParseElementEnhance.checkRecursionse # # #+,<v,EFF F*111-6 9 I $ $_ 5 5 5 5 5 ! rNc|g}|dd|gz}|j|j||gdSrrrXrUrrWrrs rrXzParseElementEnhance.validatesZ  MAAA$' 9 I  s # # # Brc tt|S#t$rYnwxYw|j0|j)|jjdt|jd|_|jSro) rrDrr rUrr>rrrs rrzParseElementEnhance.__str__s ,d33;;== =    D  < DI$9(,(?(?(?tyAQAQAQAQRDL|rrrr) rrrrrr rCrIrrUrXrrrs@rrDrDVs666666$====       666    rrDc*eZdZdZfdZddZxZS)r3abLookahead 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']] cftt||d|_dSr )rr3rr[rrr>s rrzFollowedBy.__init__s/ j$((..."rTcT|j|||\}}|dd=||fS)Nr)rr)rrrrz_rs rr zFollowedBy.parseImpls8!!(C9!EE3 FCxrrrrs@rr3r3sV*#####rr3c,eZdZdZdfd ZddZxZS) r;apLookbehind 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 Nctt||||_d|_d|_d|_t|trt|}d|_nt|ttfr|j }d|_nYt|ttfr|jt"kr|j}d|_nt|t$r d}d|_||_dt|z|_d|_|jddS)NTFrznot preceded by cH|tddSr)ror]rrrs rrz%PrecededBy.__init__..s eD$>O>O0P0Pr)rr;rrrCr[r`rrrrr:r7rrUr.rrrAretreatrarXrSr)rrrr>s rrzPrecededBy.__init__s3 j$((...IIKK//11 "" dC $iiGDJJ w0 1 1 mGDJJ tZ0 1 1 dkX6M6MkGDJJ n - - GDJ (3t994 #  P PQQQQQrrTc(|jrJ||jkrt|||j||jz }|j||\}}n|jt z}|td||jz |}t|||j} tdt||jdzdzD]F} ||t|| z \}}n#t$r } | } Yd} ~ ?d} ~ wwxYw| ||fSrd) rrrErarrrOrrerrrC) rrrrzrrr test_exprinstring_slice last_exprrpbes rr zPrecededBy.parseImpls= : T\!!$XsDK@@@$,&EY%%h66FAss IKK/I%c!S4<-?&@&@&DEN&xdkBBI3sDL1,<#=#=a#?@@ &--nc.>Q>QTZ>Z[[FAsE*$$$ #IIIIII$  Cxs )C55 D ?DD r)rTrrs@rr;r;sa6RRRRRR.rr;c0eZdZdZfdZddZdZxZS)r>aLookahead 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(".") ctt||d|_d|_dt |jz|_dS)NFTzFound unwanted token, )rr>rrXr[rrrars rrzNotAny.__init__*sK fd$$T***#".ty1A1AA rTcn|j||rt|||j||gfSr)rrrErars rr zNotAny.parseImpl1s< 9 ! !(C 0 0 C 3 TBB BBwrct|dr|jS|jdt|jzdz|_|jS)NrFz~{rrrFrUrrrs rrzNotAny.__str__6sG 4  9  < % "2"22S8DL|rrrrs@rr>r>sj,BBBBB rr>c:eZdZdfd ZdZd dZd fd ZxZS) _MultipleMatchNctt||d|_|}t |t r||}||dSr )rrrrWrrUrKstopOn)rrrenderr>s rrz_MultipleMatch.__init__@sj nd##,,T222 eZ ( ( 4,,U33E Ercrt|tr||}||nd|_|Sr)rrUrK not_ender)rrs rrz_MultipleMatch.stopOnHs> eZ ( ( 4,,U33E#(#4%$ rTcx|jj}|j}|jdu}|r |jj}|r |||||||d\}} |j } |r |||| r |||} n|} ||| |\}} | s| r|| z }K#ttf$rYnwxYw||fSNFr) rrrrrr]rrErX) rrrrzself_expr_parseself_skip_ignorables check_ender try_not_enderrhasIgnoreExprsr tmptokenss rr z_MultipleMatch.parseImplNs2)*#3nD0  4 N3M  ) M(C ( ( (%ohYUSSS V &*&6"66N (1!M(C000!!11(C@@FF F!069!M!MY( 1 1 3 3(i'F ( +    D F{s AB!!B54B5Fc ptjr|jgt|jdgzD]a}t |t rJ|jrCtjd d|t|j |jdbtt|||S)Nrgrwr#rr)r!r#rr@rrJrVrrrrrrrrorxs rroz_MultipleMatch._setResultsNameks  = 0i[749gr#B#BB 0 0a//0AM0M#PPVPVXCW[W[\`WaWaWjWXWdQfQf./ 0000^T**::4PPPrrrr)rrrrrr rorrs@rrr?s : Q Q Q Q Q Q Q Q Q QrrceZdZdZdZdS)r?ajRepetition 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() ct|dr|jS|jdt|jzdz|_|jS)NrFrz}...r rs rrzOneOrMore.__str__G 4  9  < ty!1!11F:DL|rN)rrrrrrrrr?r?ys-2rr?c6eZdZdZdfd Zdfd ZdZxZS) rXakOptional 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` Ncjtt|||d|_dS)NrT)rrXrr[)rrrr>s rrzZeroOrMore.__init__s4 j$((f(==="rTc tt||||S#ttf$r|gfcYSwxYwr)rrXr rErX)rrrrzr>s rr zZeroOrMore.parseImplsW T**44XsINN N +   7NNN s)-AAct|dr|jS|jdt|jzdz|_|jS)NrFr]...r rs rrzZeroOrMore.__str__r rrrrrs@rrXrXst  ###### rrXceZdZdZeZdZdS) _NullTokencdSrrrs rrvz_NullToken.__bool__surcdSrrrs rrz_NullToken.__str__srrN)rrrrvrrrrrr(r(s7Krr(cHeZdZdZeZeffd ZddZdZxZ S)rAaGOptional 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) ctt||d|jj|_||_d|_dS)NFrT)rrArrrWrr[)rrrr>s rrzOptional.__init__sH h&&te&<<<).#"rTc |j|||d\}}nf#ttf$rR|j|jur?|jjr*t|jg}|j||jj<n |jg}ng}YnwxYw||fSr)rrrErXr_Optional__optionalNotMatchedrVrH)rrrrzrs rr zOptional.parseImpls )**8S)RW*XXKC +    (AAA9(1)4+<*=>>F484EF49011"/0FF F{s!$A BBct|dr|jS|jdt|jzdz|_|jS)NrFrrr rs rrzOptional.__str__sG 4  9  < ty!1!11C7DL|rr) rrrrr(r.rr rrrs@rrArAs|##H&:<<%9######    rrAc,eZdZdZdfd ZddZxZS) rNa 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 FNcDtt||||_d|_d|_||_d|_t|tr| ||_ n||_ dt|j z|_dS)NTFzNo match found for )rrNr ignoreExprr[r` includeMatchrWrrUrKfailOnrrra)rrincluderIr4r>s rrzSkipTo.__init__@s fd$$U+++ ""# fj ) ) !226::DKK DK+eDI.>.>> rTc|}t|}|j}|jj}|j |jjnd}|j |jjnd} |} | |krd| ||| rnl| | || } n#t$rYnwxYw ||| ddn9#ttf$r| dz } YnwxYw| |kdt|||j || }|||} t| } |j r||||d\}} | | z } || fS)NrF)rzr{r) rrrr4rr2rrCrErXrarHr3)rrrrzrrr expr_parseself_failOn_canParseNextself_ignoreExpr_tryParsetmplocskiptext skipresultrs rr zSkipTo.parseImplMsx==yY% ?C{?V4;#;#;\` ?C?Z4?#;#;`d   '3++Hf=='3!9!9(F!K!K-   8Vu5QQQQ  #J/   !  !  2!3 TBB BHSL)!(++   !z(COOOHC # JJs$* A77 BB BB21B2)FNNrrrs@rrNrNs\88r ? ? ? ? ? ?--------rrNc`eZdZdZd fd ZdZdZdZdZd dZ d Z fd Z dfd Z xZ S)r4a_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``. Nc\tt||ddSr)rr4rrs rrzForward.__init__s, gt%%ee%<<<<r)r retStrings rrzForward.__str__s 4  9  < #<    Fy$!$),,UdU3 " >2T9IEDLL4>2T9IEDL E E E E|s &A..Bc|j'tt|St}||z}|Sr)rrr4rrus rrz Forward.copys> 9 $'',,.. .))C DLCJrFc tjrD|j=tjdd|t |jdtt| ||S)NzR{0}: setting results name {0!r} on {1} expression that has no contained expressionr$rr) r!r$rrrrrrrr4rors rrozForward._setResultsNames  2 ,y  AAGHhHLHLT H[B]B]*+ ,,,, Wd##33D.IIIrrr)rrrrrr@rBrCrrXrrrorrs@rr4r4|s4======       ( J J J J J J J J J Jrr4c$eZdZdZdfd ZxZS)rSzW Abstract subclass of :class:`ParseExpression`, for converting parsed results. Fcftt||d|_dSr)rrSrrWrs rrzTokenConverter.__init__s, nd##,,T222rrrrs@rrSrSsG          rrSc4eZdZdZdfd ZfdZdZxZS)r/aConverter 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...) rTctt|||r|||_d|_||_d|_dSr )rr/rrCadjacentrX joinStringrd)rrrPrOr>s rrzCombine.__init__s_ gt%%d+++  #  " " "  "$ rc|jrt||n(tt|||Sr)rOrJrIrr/rs rrIzCombine.ignore sI = /  u - - - - '4 ' ' . . . rc|}|dd=|td||jg|jz }|jr|r|gS|S)Nr)rH)rrHrrrPrbrVr)rrrrretTokss rrzCombine.postParses.."" AAAJ<)@)@)Q)Q!R!R S[_[lmmmm    1 1 9 Nr)rT)rrrrrrIrrrs@rr/r/so"!!!!!!rr/c(eZdZdZfdZdZxZS)r6aConverter 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']] cftt||d|_dSr )rr6rrWrs rrzGroup.__init__*s, eT##D)))rc|gSrrrs rrzGroup.postParse.s {rrrrrrrrrs@rr6r6sQ  rr6c(eZdZdZfdZdZxZS)r0a?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. cftt||d|_dSr )rr0rrWrs rrz Dict.__init__Xs, dD""4(((rct|D]N\}}t|dkr|d}t|tr't |d}t|dkrt d|||<t|dkr5t|dtst |d|||<|}|d=t|dks)t|tr)| rt ||||<5t |d|||<P|j r|gS|S)Nrrrr) rrrrrrr2rHrrrV)rrrrrtokikey dictvalues rrzDict.postParse\sR ** O OFAs3xx1}}q6D$$$ -SV}}**,,3xx1}}"9"a"@"@ $SQz#a&,'G'G"9#a&!"D"D $HHJJ aLy>>Q&&:i+N+N&S\SdSdSfSf&&=i&K&KIdOO&=ilA&N&NIdOO   ;  rrWrs@rr0r01sR%%Lrr0ceZdZdZdZdZdS)rQa[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`.) cgSrrrs rrzSuppress.postParses rc|Srrrs rr@zSuppress.suppresss rN)rrrrrr@rrrrQrQus<*rrQc$eZdZdZdZdZdZdS)r@zDWrapper for parse actions, to ensure they are only called once. c<t||_d|_dSr)rrcalled)r methodCalls rrzOnlyOnce.__init__s#J//  rcr|js ||||}d|_|St||d)NTr)rcrrE)rrrrrs rr>zOnlyOnce.__call__s?{ mmAq!,,GDKNQ2&&&rcd|_dSr)rcrs rresetzOnlyOnce.resets  rN)rrrrrr>rgrrrr@r@sK''' rr@cltfd} j|_n#t$rYnwxYw|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 <rstderrrwrnr )paArgsthisFuncrrrrrr_s rzztraceParseAction..zs:+1a v;;??ay*3c9HDH >(DQRTUJJXY[\A]]^^^ !V*CC    J   333O P P P   xxxEFFF s7A== B3'B..B3)rrr)r_rns` rrrs^2 AA      Z      Hs $ 11,cJt|dzt|zdzt|zdz}|r5t|t||zz|S|tt ||zz|S)aHelper 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 [rr&)rr/rXrmrQ)rdelimcombinedlNames rrgrgs4[[4 %,, . 4uT{{ BV KFKtj66677??GGGz(5//D"8999BB6JJJrcZtfd}|)ttd}n|}|d||d|zdtzdzS) 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'] c|d}|r ttg|zpttzgSr<)r6r+rj)rrrr# arrayExprrs rcountFieldParseActionz+countedArray..countFieldParseActions@ aDa2E#tfqj//22BeEllCC rNc,t|dSr<)rrs rrzcountedArray..sc!A$iirarrayLenTrez(len) r)r4rUryrrrmrr)rintExprrwrvs` @rrcrcs. It**++,?,?@@,,.. OOJ 0EEE i  ( (E$KK)?%)G H HHrcg}|D]O}t|tr#|t|:||P|Sr)rrPrrr)Lrrs rrr sY C  a    JJx{{ # # # # JJqMMMM Jrctfd}||ddt|zS)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. c|r_t|dkr |dzdSt|}td|DzdSt zdS)Nrrc34K|]}t|VdSr)r:rtts rrzDmatchPreviousLiteral..copyTokenToRepeater..*s(77272;;777777r)rrrGr+r2)rrrtflatreps rcopyTokenToRepeaterz1matchPreviousLiteral..copyTokenToRepeater#s{  1vv{{qt !,,s77777777777 577NNNNrTrz(prev) )r4rrmr)rrrs @rrvrvse ))C      +4@@@KK E$KK'((( Jrct|}|zfd}||ddt |zS)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. ct|fd}|ddS)Ncxt|}|krtddddS)Nrr)rrGrE)rrr theseTokens matchTokenss rmustMatchTheseTokenszLmatchPreviousExpr..copyTokenToRepeater..mustMatchTheseTokensEs="188::..Kk))$RB///*)rTrz)rrGr)rrrrrrs @rrz.matchPreviousExpr..copyTokenToRepeaterCsTqxxzz**  0 0 0 0 0 /tDDDDDrTrzr)r4rrrmr)re2rrs @rruru1s ))C BBJCEEEEE +4@@@KK E$KK'((( JrcdD] }||t|z}!|dd}|dd}t|S)Nz\^-[]r rsr'r*)r_bslashr)rrs rrrNs[ && IIa1 % % $A $A 88Orc t|trtjdd|rd}d}|rtnt nd}d}|rt nt g}t|tr|}nAt|trt|}ntjdtd|stS|sd }|t|d z kr||}t||d zd D]I\} } || |r ||| zd z=n3||| r!||| zd z=||| nJ|d z }|t|d z k|s |s |r t|td |krUt#d d d|Dzd|St#dd|Dd|S#t&$rtjdtdYnwxYwt) fd|Dd|S)aHelper 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 stringrrcV||kSr)rrbs rrzoneOf..{s QWWYY 6rct||Sr)rrrs rrzoneOf..|s$aggii2217799==rc||kSrrrs rrzoneOf..s Qrc,||Srrrs rrzoneOf..sall1oorz6Invalid argument to oneOf, expected string or iterablerrNrrc34K|]}t|VdSr)rrsyms rrzoneOf..s+-]-]c.DS.I.I-]-]-]-]-]-]rr|c3>K|]}tj|VdSr)rrrs rrzoneOf..s*%H%Hbinn%H%H%H%H%H%Hrz7Exception creating Regex for oneOf, building MatchFirstc3.K|]}|VdSrr)rrparseElementClasss rrzoneOf..s/@@'',,@@@@@@r)rrUrrr,r-r7r:rr rPrr=rrrrrMrmr r<) strsruseRegexrisequalmaskssymbolsrcurrlrrs @rrzrzVsA@(J''S DPQ S S S S>66==/8MOOo&&--'0=GGgG$ ##3**,, D( # #3t** N# 3 3 3 3 yy  #g,,"""!*C%ga!effo66  575#&&A *EU3&&A *NN1e,,,E Q#g,,"""  1 1x 1 17||s2777#3#34444Vbgg-]-]U\-]-]-]&]&]]^^ffglgqgqrygzgz{{{SXX%H%H%H%H%HHHIIQQRWR\R\]dReRefff 1 1 1 MS!a 1 1 1 1 1 1 1 @@@@@@@ @ @ H HT[I\I\ ] ]]sBI AI&JJcZttt||zS)aHelper 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'} )r0r?r6)rrms rrhrhs'J  %e ,,-- . ..rctd}|}d|_|d|z|dz}|rd}nd}|||j|_|S)aHelper 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'] c|Srr)rrrs rrz!originalTextFor..srF_original_start _original_endc*||j|jSr)rrrs rrz!originalTextFor..sa(91?(J&Krcr||d|dg|dd<dS)Nrr)rrs r extractTextz$originalTextFor..extractTexts9aee-..quu_/E/EEFGAaaaDDDr)r2rrrdr])rasString locMarker endlocMarker matchExprrs rrrs:&&'<'<==I>>##L %L +,,t3ll?6S6SSIHKK  H H H [))) ,I rcHt|dS)zkHelper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty. c|dSr<rrs rrzungroup..s 1r)rSr)rs rrrs" $   . .~~ > >>rctd}t|d|dz|dzS)aHelper 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]] c|Srrrs rrzlocatedExpr..sQr locn_startrmlocn_end)r2rr6rrC)rlocators rrrsi2gg$$%6%677G &&g69Y9W9W9Y9YZd9e9ee f ffrrjrprorrz\[]-*.$+^?()~ rc|ddSrdrrs rrr(sXYZ[X\]^X_rz\\0?[xX][0-9a-fA-F]+cntt|dddS)Nrz\0xr)unichrrrxrs rrr)s1PVWZ[\]^[_[f[fgm[n[nprWsWsPtPtrz \\0[0-7]+cXtt|ddddS)Nrr)rrrs rrr*s,VCPQRSPTUVUWUWPXZ[L\L\E]E]rz\]r}rrnegatebodyrcd dfdt|jDS#t$rYdSwxYw)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.) c t|ts|nUddtt |dt |ddzDS)Nrc34K|]}t|VdSrrrs rrz+srange....Is*KKZ[FSTIIKKKKKKrrr)rrHrreord)ps rrzsrange..Ise:a#>#>!!BGGKK_dehijklimenenpstuvwtxpypy|}p}_~_~KKKDDrrc3.K|]}|VdSrr)rpart _expandeds rrzsrange..Ks+VV4yyVVVVVVr)r_reBracketExprrrr )rrs @rrr/sm4@IwwVVVV>3M3Ma3P3P3UVVVVVV rrs=A AAcfd}|S)zoHelper method for defining parse actions that require matching at a specific column in the input text. cXt||krt||dzdS)Nzmatched token not at column %drJ)rlocnr!r#s r verifyColz!matchOnlyAtCol..verifyColSs7 tT??a   t-MPQ-QRR R rr)r#rs` rrtrtOs)SSSSS rcfdS)aHelper 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] c gSrr)rrrreplStrs rrzreplaceWith..es G9rr)rs`rrrXs % $ $ $$rc"|dddS)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"] rrrrrs rrrgs Q4":rcfd} tdtdj}n#t$rt}YnwxYw||_|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'] c"fd|DS)Nc"g|] }|gR Srr)rtoknrr(s rrz(tokenMap..pa..s+000dT!D!!!000rr)rrrrr(s rrztokenMap..pas 00000a0000rrr>)r@rr r)r(rrrCs`` rrrvsH111111D*#D+66?AA II BK Is$/A  A cDt|Srrrrs rrrs%((.."2"2rcDt|Srrlowerrs rrrsE!HHNN$4$4rrrc t|tr|t|| }n|jt t t dz}|rt t}||dzttt|tdz|zztddgd d z|z}nt  tt t"d z}||dzttt| t$ttd|zzztddgd d z|z}t't)d |zd zd}|dz|fd|ddddzdz}|_|_t9||_||fS)zRInternal helper to construct opening and closing tag expressions, given a tag namerz_-:tag=/Frrjc|ddkSNrrrrs rrz_makeTags..\]^_\`dg\grrrc|ddkSrrrs rrz_makeTags..rrr)rOz<%s>c |ddddz|S)Nrr:r)rbrrtitlerr)rresnames rrz_makeTags..s[Q]]7RWWW__UXZ]E^E^EdEdEfEfElElEnEn=o=o3oqrqwqwqyqy%z%zrrrrrz)rrUr7rFrUr[rZrerrrr0rXr6rQrArr}rir/_LrmrrrrrrrNtag_body) tagStrxml suppress_LT suppress_GT tagAttrName tagAttrValueopenTagcloseTagrs @r _makeTagsrs&*%%c'222+vy5011K "&++--<<\JJ VE]]#*U;#+F+U%V%VWWXXY4XcE7333G<<KKLgLghhi! ! $((**99,GG$zhkJlJlJll VE]]#*U;+E+En+U+U-5hsmml6R-S-S,T&U&UVVWWW4XcE7333G<<KKLgLghh i ! ! r$xx&(3.???H OOFW$%%% zzzz{{{xS(A(A(G(G(I(I(O(O(Q(Q R RRSS[[\cfm\mnnHGKHLhhjj))G H rc"t|dS)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 Frrs rrrrrs, VU # ##rc"t|dS)zHelper 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` Trrs rrsrss VT " ""rcl|r |ddn|dDfd}|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 Ncg|] \}}||f Srrrs rrz!withAttribute../s & & &1aV & & &rc D]Z\}}||vrt||d|z|tjkr-|||kr!t||d|d||d|d[dS)Nzno matching attribute z attribute 'z ' has value 'z ', must be '')rEr ANY_VALUE)rrrattrName attrValueattrss rrzwithAttribute..pa0s#( U U Hiv%%$Q+Ch+NOOOM333x8HI8U8U$Q-5XXvh7G7G7G,TUUU  U Ur)rh)rattrDictrrs @rrrsdp !QQQ   & & & & &EUUUUU Irc0|rd|znd}tdi||iS)aSimplified 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:classclassr)r) classname namespace classattrs rrr:s2F+4@ Y&&I  2 2Iy1 2 22rrrc Gddt}t}|||z|zz}t|D]\}}|dzdd\} } } } | dkrd| znd| z} | dkr)| t| d krt d | \}}t| }| t jkr| d kr0||| zt|t| zz}n| d krh| 6||| z|zt|t| |zzz}n|||zt|t|zz}n}| dkrB|||z|z|z|zt|t||z|z|zzz}n5t d | t j kr| d krKt| tst| } || j |zt| |zz}n| d krf| 5||| z|zt|t| |zzz}n|||zt|t|zz}nX| dkr4|||z|z|z|zt||z|z|z|zz}nt d t d | r._FBTc@|j|||gfSr)rrrs rr z$infixNotation.._FB.parseImpls# I  x - - -7NrNrrrrr_FBrs(      rr rNrrz%s termz %s%s termrz@if numterms=3, opExpr must be a tuple or list of two expressionsrz6operator must be unary (1), binary (2), or ternary (3)z2operator must indicate right or left associativity)r3r4rrr&rmr{LEFTr6r?RIGHTrrArr%rPr)baseExpropListlparrparr rlastExprroperDefopExprarityrightLeftAssocrtermNameopExpr1opExpr2thisExprrs rrrdsPj ))C4#:,-H''.. 7-4x-?!,D)~r).9v%% f8L A::~V!1!1 VXXX% GW99$$X.. W\ ) )zzC6 122U8iPVFWFW;W5X5XX !% #Hv$5$@ A AE(U^_ehp_pUqUqJqDrDr rII #Hx$7 8 85IV^L_L_A_;`;` `II! SG!3h!>!H8!STT$X 'H:Lw:VYa:a0b0b%bccd !!YZZZ w} , ,zz!&(33.%f--FC h 677%@Q:R:RR !% #Hv$5$@ A AE(U^_ehp_pUqUqJqDrDr rII #Hx$7 8 85IV^L_L_A_;`;` `II! SG!3h!>!H8!STT$X%7(%BW%Lx%WXXY !!YZZZQRR R  -"udm,, -( ("---((,,,i''11H<=HC Jrz4"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*"z string enclosed in double quotesz4'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*rz string enclosed in single quotesz*quotedString using single or double quotesuzunicode string literalc d||krtd|t|trt|trt|dkrt|dkr|Ut t |t ||ztjzdz d}n;t t ||ztjz dz}n|pt t |t|zt|zt tjdz d}n{t t t|t|zt tjdz d}ntd t}|F|tt|t!||z|zzt|zz}nB|tt|t!||zzt|zz}|d ||d |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 sameNrrc6|dSr<rrs rrznestedExpr..;!A$**,,rc6|dSr<rrs rrznestedExpr..@sTUVWTXT^T^T`T`rc6|dSr<rrs rrznestedExpr..Grrc6|dSr<rrs rrznestedExpr..LrrzOopening and closing arguments must be strings if no content expression is givenznested z expression)r&rrUrr/r?r.rJrFrrjrr:r4r6rQrXrm)openerclosercontentr2rs rrwrwsBIJJJ fj ) ) pj.L.L p6{{aCKK1$4$4)&y*3=f@F?G@M@a?bij4l4l4l2l(3(3 ) ) *88N8N)O)O G %zz||j;A:B;H;\:]/;/;J`J`;a;a bGG )&y*4;FOO3C2D4;FOO3C2D4>m>_gh3i3i3i2j(k(k ) )*88N8N)O)O G 'y'&//1A4;FOO3C2D3=m>_gh3i3i3i2j(k(k ) )*88N8N)O)OG noo o ))C hv&&J4Dw4N)O)OORZ[aRbRbbccc hv&&C'M)B)BBhvFVFVVWWWKKKFFFFF;<<< Jrc d dd fd fd}fd}fd}ttdt }t t |zd}t |d }t |d } |ratt||zt|t|zt|zt z| z} n]tt|t|t|zt|zt z| z} | fd | ttz| d S) aHelper 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']]]]]]] Ncdd<dSrr) backup_stack indentStacksr reset_stackz"indentedBlock..reset_stacks% AAArc|t|krdSt||}|dkr.|dkrt||dt||ddS)Nrzillegal nestingznot a peer entry)rr`rErrrcurColr(s rcheckPeerIndentz&indentedBlock..checkPeerIndentso A;;Q [_ $ $ B''$Q+<=== A'9:: : % $rct||}|dkr|dSt||d)Nrznot a subentry)r`rrEr+s rcheckSubIndentz%indentedBlock..checkSubIndentsLQ KO # #   v & & & & & A'788 8rc|t|krdSt||}r|vst||d|dkrdSdS)Nznot an unindentr)rr`rErr+s r checkUnindentz$indentedBlock..checkUnindentsu A;;Q :v44 A'899 9 KO # # OO      $ #rz r#INDENTrUNINDENTcSrr)rrrr r)s rrzindentedBlock..s KKMMrzindented block) r?r8rEr@rOr2rrmr6rArrIr) blockStatementExprr(rr-r/r1rr2PEERUNDENTsmExprr'r)s ` @@rrrWs<bqqq>L&&&&&&;;;;;99999 799//66??AA)++ V V VBgg..~>>> G G Q QF WW # #O 4 4 < >* + ++rz#[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]z[\0xa1-\0xbf\0xd7\0xf7]z_:zany tagzgt lt amp nbsp quot aposz><& "'z &(?Prz);zcommon HTML entityc@t|jS)zRHelper parser action to replace common HTML entities with their special characters)_htmlEntityMaprentityrs rrrs   ah ' ''rz/\*(?:[^*]|\*(?!/))*z*/zC style commentzz HTML commentz.*z rest of linez//(?:\\\n|[^\n])*z // commentzC++ style commentz#.*zPython style commentr commaItemrrac eZdZdZeeZ eeZ e e  d eZ e e d eedZ ed d eZ e edze ez dZ ed eeeed ezzz d Z eeed  d  eZ ed d eZ eezezZ ed d eZ e edzedz dZ ed dZ ed dZ!e!de!zdzz dZ"ee!de!zdzzdzee!de!zdzzz dZ#e#$dde z d Z%e&e"e%ze#z d! d!Z' ed" d#Z( e)d9d%Z*e)d:d'Z+ed( d)Z, ed* d+Z- ed, d-Z. e/e0zZ1e)d.Z2e&e3e4d/e5ze e6d/0zee7d1z d2Z8e9ee:;e8zd34 d5Z< e)ed6Z= e)ed7Z>d8S);ra 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 integerrz[+-]?\d+zsigned integerrfractionc$|d|dz S)Nrrrrs rrzpyparsing_common.sad1R5jrr}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_integerrzfull IPv6 address)rr7z::zshort IPv6 addressc<td|DdkS)Nc3XK|]%}tj|!dV&dSr)r _ipv6_partrrs rrz,pyparsing_common...s:2l2lDTD_DgDghjDkDk2l12l2l2l2l2l2lrr)rrs rrzpyparsing_common.s#s2l2lq2l2l2l/l/lop/prz::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-%dcfd}|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)] c tj|dS#t$r#}t ||t |d}~wwxYwr<)rstrptimedater&rErrrrvefmts rcvt_fnz.pyparsing_common.convertToDate..cvt_fnsb 4(1s3388::: 4 4 4$Q3r77333 4s,0 AAArrPrQs` r convertToDatezpyparsing_common.convertToDate#$ 4 4 4 4 4  r%Y-%m-%dT%H:%M:%S.%fcfd}|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)] c tj|dS#t$r#}t||t |d}~wwxYwr<)rrLr&rErrNs rrQz2pyparsing_common.convertToDatetime..cvt_fnsV 4(1s333 4 4 4$Q3r77333 4s A AA rrRs` rconvertToDatetimez"pyparsing_common.convertToDatetimerTrz7(?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}UUIDcLtj|dS)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)rrrs r stripHTMLTagszpyparsing_common.stripHTMLTagss  .>>vayIIIrrorr<r=rrzcomma separated listcDt|Srrrs rrzpyparsing_common.#s588>>3C3CrcDt|Srrrs rrzpyparsing_common.&sU1XX^^5E5ErN)rI)rU)?rrrrrrconvertToIntegerfloatconvertToFloatrUryrmrr?rkrDrMsigned_integerr@rrAr@ mixed_integerrrealsci_realrnumberrBr[rZrC ipv4_addressrH_full_ipv6_address_short_ipv6_addressr_mixed_ipv6_addressr/ ipv6_address mac_addressr&rSrX iso8601_dateiso8601_datetimeuuidr^r]r[r\r?r:r8r}rT _commasepitemrgrrcomma_separated_listrrirrrrrs9NN` x}}Xe__Nd4jj  ++::;KLLGD$w--'' 66EEhhsTVFWFWXXKFU;''//0@AAPPQabbNV  //??#EHXHXHgHghvHwHwwAABLMMHT 00111((3--:P:P:R:RU]:]1^1^ ^^ggiMNNMf  %%% 5+ , , 4 4] C C R RSa b bDLuXYYaacIJJYYZhiiH/o. : : < (>'?@@AABLggVaNbNb)=,2C2C2E2E4A3BKM*O*O*O+++273I+J+Je<)C)C D DEEL7!\((+E+E"F"FGGN77rrceZdZdZdZdS)_lazyclasspropertycD||_|j|_|j|_dSr)rrrrs rrz_lazyclassproperty.__init__+sz   rc"t|tdr(tfdjddDri_|jj}|jvr|j|<j|S)N_internc3HK|]}jt|dguVdS)rvN)rvr@)r superclassrs rrz-_lazyclassproperty.__get__..3sT.Q.Q2</2kWZQZ\^=_=_._.Q.Q.Q.Q.Q.Qrr)rrr__mro__rvrr)rrrattrnames ` r__get__z_lazyclassproperty.__get__0s ;s))CsI&& #.Q.Q.Q.Q@C ABB.Q.Q.Q+Q+Q CK7# 3; & &$(GGCLLCK !{8$$rN)rrrrr{rrrrsrs*s2$$$ % % % % %rrsceZdZdZgZedZedZedZ edZ edZ dS)ra 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 c g}|jD]I}|turn=|jD]4}|t |d|ddz5Jdt t |DS)Nrrrc,g|]}t|Srrrs rrz5unicode_set._get_chars_for_ranges..Ts444aq 444r)ryr_rangesrrerr)rrccrrs r_get_chars_for_rangesz!unicode_set._get_chars_for_rangesLs+ 5 5B[  j 5 5 5A2 334444 5446#c((#3#34444rcdttj|S)z+all non-whitespace characters in this ranger)rrrrHrrLs rr}zunicode_set.printablesVs.xx GOS5N5N5P5PQQRRRrcdttj|S)z'all alphabetic characters in this ranger)rfilterrisalpharrLs rr[zunicode_set.alphas[.xxw0I0I0K0KLLMMMrcdttj|S)z*all numeric digit characters in this ranger)rrrisdigitrrLs rryzunicode_set.nums`rrc |j|jzS)z)all alphanumeric characters in this range)r[ryrLs rrZzunicode_set.alphanumseszCH$$rN) rrrrrrrrsr}r[ryrZrrrrr<s  G55[5SSSNNNNNN%%%%%rrceZdZdZdejfgZGddeZGddeZ GddeZ Gd d eZ Gd d eZ Gd deZ GddeZGddeZGdde eeZGddeZGddeZGddeZGddeZdS)rzF A namespace class for defining common language unicode_sets. ceZdZdZddgZdS)pyparsing_unicode.Latin1z/Unicode set for Latin-1 Unicode Character Range)r~)NrrrrrrrrLatin1rq99#%57rrceZdZdZdgZdS)pyparsing_unicode.LatinAz/Unicode set for Latin-A Unicode Character Range)iNrrrrLatinAru99#%rrceZdZdZdgZdS)pyparsing_unicode.LatinBz/Unicode set for Latin-B Unicode Character Range)iiONrrrrLatinBryrrrceZdZdZgdZdS)pyparsing_unicode.Greekz.Unicode set for Greek Unicode Character Ranges))ipi)ii)ii)i iE)iHiM)iPiW)iY)i[)i])i_i})ii)ii)ii)ii)ii)ii)iiNrrrrGreekr}s%88   rrceZdZdZdgZdS)pyparsing_unicode.Cyrillicz0Unicode set for Cyrillic Unicode Character Range)iiNrrrrCyrillicrs::#$rrceZdZdZddgZdS)pyparsing_unicode.Chinesez/Unicode set for Chinese Unicode Character Range)Nii0i?0NrrrrChineserrrrcjeZdZdZgZGddeZGddeZGddeZdS) pyparsing_unicode.Japanesez`Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana rangesceZdZdZddgZdS) pyparsing_unicode.Japanese.Kanjiz-Unicode set for Kanji Unicode Character Range)rirNrrrrKanjirs ; ;')9;GGGrrceZdZdZdgZdS)#pyparsing_unicode.Japanese.Hiraganaz0Unicode set for Hiragana Unicode Character Range)i@0i0NrrrrHiraganars > >')GGGrrceZdZdZdgZdS)#pyparsing_unicode.Japanese.Katakanaz1Unicode set for Katakana Unicode Character Range)i0i0NrrrrKatakanars ? ?')GGGrrN) rrrrrrrrrrrrJapanesersjj < < < < z?pyparsing_test.reset_pyparsing_context.save..s1...26gh--...rr!rr*) rJrFrr7rrKrrr! _all_namesr*rrs rsavez+pyparsing_test.reset_pyparsing_context.saves7D7XD 3 4:A:WD 6 71  & 5B4QD 0 12?2FD  /..:B:M...D z *)**K0D | ,Krctj|jdkr%t|jd|jdt_t|jd|jdD]\}}tt|||jdt_ |jdt_ |jdt_ dS)Nrrrr!rrr*)rJrFrrIr7rrMrhsetattrr!rrr*r)rrFrms rrestorez.pyparsing_test.reset_pyparsing_context.restores1%&:;<<77&';<-1,>?V,WG )  - -"#9:    $1*=CCEE / / e$....,0,>?P,QM )#'#5o#FM 040B<0PJ - - -rc*|Sr)rrs r __enter__z0pyparsing_test.reset_pyparsing_context.__enter__ s99;; rc*|Sr)rrs r__exit__z/pyparsing_test.reset_pyparsing_context.__exit__s<<>> !rN) rrrrrrrrrrrrreset_pyparsing_contextrsl  , $ $ $     Q Q Q&    " " " " "rrcVeZdZdZ d dZ d dZ d dZ d dZee dfdZ dS) &pyparsing_test.TestParseResultsAssertszk A mixin class to add parse results assertion methods to normal unittest.TestCase classes. Nc|*|||||,||||dSdS)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. Nr) assertEqualrGr)rr expected_list expected_dictrs rassertParseResultsEqualsz?pyparsing_test.TestParseResultsAsserts.assertParseResultsEqualssd(   S III(   S IIIII)(rTc||d}|r!t|||||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. Tro)rrNrrrr)rr test_stringrrverbosers rassertParseAndCheckListz>pyparsing_test.TestParseResultsAsserts.assertParseAndCheckList!\%%kD%AAF %fkkmm$$$  ) )& SV ) W W W W Wrc||d}|r!t|||||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. Tro)rrNr)rrrrrrrs rassertParseAndCheckDictz>pyparsing_test.TestParseResultsAsserts.assertParseAndCheckDict-rrc|\}}|dt||D}|D]\}}} td| Dd} td| Dd} | J|| | p|5t|tr| dddn #1swxYwYtd| Dd} td| Dd} | | fdkr||| | | p| t d |||||nd 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)] Nc6g|]\}}|d|d|fSrr)rrptexpecteds rrzOpyparsing_test.TestParseResultsAsserts.assertRunTestResults..Hs;%XVSVX.rc3DK|]}t|t|VdSr)rrrexps rrzNpyparsing_test.TestParseResultsAsserts.assertRunTestResults..Qs1IIJsC4H4HIIIIIIIrc3nK|]0}t|tt|t,|V1dSr)rrrr rs rrzNpyparsing_test.TestParseResultsAsserts.assertRunTestResults..Ts[ #)#t44:DC9S9Sr)expected_exceptionrc3DK|]}t|t|VdSr)rrPrs rrzNpyparsing_test.TestParseResultsAsserts.assertRunTestResults..c1NNS 38M8MNSNNNNNNrc3DK|]}t|t|VdSr)rrSrs rrzNpyparsing_test.TestParseResultsAsserts.assertRunTestResults..frrr!)rrrzno validation for {!r}zfailed runTestsr) rr assertRaisesrr rrr assertTrue)rrun_tests_reportexpected_parse_resultsrrun_test_successrun_test_resultsmergedrrrfail_msgrrrs rassertRunTestResultsz;pyparsing_test.TestParseResultsAsserts.assertRunTestResults9s82B . .%1),-=?U)V)V6<%P%P1K $IIIII4  H*.'/  **&*5!../AxSV/-- *&)<<-&, ---------------- )-NNHNNNPT)) )-NNHNNNPT)) *=9\II 99 &.;.;$,O :"":"A"A+"N"NOOOO OO S_ccBS      s;B  B$ 'B$ c#rK|||5dVddddS#1swxYwYdS)Nr)r)rrrs rassertRaisesParseExceptionzApyparsing_test.TestParseResultsAsserts.assertRaisesParseExceptionxs""8"55                    s ,00rRr r!) rrrrrrrrrrErrrrTestParseResultsAssertsrs  GK J J J JGK X X X XGK X X X XFJ= = = = ~ 6D$       rrN)rrrrrrrrrrrsA"A"A"A"A"A"A"A"Fjjjjjjjjjjrr__main__selectfromrrj)rrcolumnsrstablescommandaK # '*' 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 r)r)roFr)FTFrr(rr'r(r)rweakrefrr_rrrrrrrr0rroperatorr itertools functoolsr contextlibrr ImportErrorr _threadr threadingcollections.abcr r r rr ordereddictrr*rr!r"r#r$r%rkrbrr&enable_all_warnings__all__r% version_infor/rmaxsizerrrUchrrrrrrrreversedrPrrrrrr?maxintxrangere __builtin__rfnamerr@rrrRrascii_uppercaseascii_lowercaser[ryrkrZrr printabler}rr rCrErGrIrLrBr2rHregisterr`rqrnrr"r$rxrrJrrRr2r=r:rrrKr7r-r,rrUrrYrMrKr.rTrAr5r9r8rPrOrWrVrFr+rBr<r1rDr3r;r>rr?rXr(rArNr4rSr/r6r0rQr@rrgrcrrvrurrzrhrrrrmrjrprorrr _escapedPunc_escapedHexChar_escapedOctChar _singleChar _charRangerqrrrtrrrrrirrrrsrrrr{r r rr|rerrrrwrr\r~r^r]rSrr:rrbrr_rlrCrrfrdrmrrrprarrsrrrrrrrrrrrrrrrrrr selectToken fromTokenident columnNamecolumnNameList columnSpec tableName tableNameList simpleSQLrrfrBrDrorYrrrr3sQ6EP ) 9    %%%%%%6%%%%%%%666555555556     4((((((777777777444$$$$$$33333333334 7777777;;;;;;;    %%%%%%%    _     %) ! ?  6;25:2*/'16.-2*iiDDNNiii::: 4   ,s'((!,aA,{HJ FG Ec68T5#sCQTVYZzH E333.IOOQQ   $ $WW[%%@%@ A A A A    H ++%%((+++,,  &"8 8   TM #b'' WWOO 0OOO O O     =;=;=;=;=;=;=;=;~ZZZZZ'ZZZz     ,        .   *HHHHH HHH$$$$$f$$$A A A A A 6A A A F %%% W W W ( ( (!!!xxxBBB,,,   4DAAAAH]#]#]#]#]#F]#]#]#@-^^^^^=^^^B44444M444#####E### ? ? ? ? ?e ? ? ?%?%?%?%?%?e%?%?%?N????????  $+ !L.L.L.L.L.eL.L.L.\?????g???. V V V V Vg V V VB?B?B?B?B?B?B?B?J]]]]]5]]]~######## & & & & &: & & &J'J'J'J'J'EJ'J'J'XTTTTT5TTTnIIIIIIIIVC(C(C(C(C(EC(C(C(L#####U###4????????>CCCCCnCCC(     .   CCCCCCCC"*n.vRvRvRvRvRmvRvRvRrjjjjj/jjjZxExExExExExExExEvSMSMSMSMSMSMSMSMlB.B.B.B.B.?B.B.B.JLLLLL-LLL^     $   FHHHHH$HHHV***** ***X7Q7Q7Q7Q7Q(7Q7Q7Qt!!!!!!!!F>BBBBB"BBBHttttt tttlhJhJhJhJhJ!hJhJhJT     (   +++++n+++ZN,AAAAA>AAAH~:     v   + + + `KKKK*"I"I"I"IH<:U^U^U^U^n%/%/%/N((((T??? ggg<eggoog&&ikk!!+.. gii **kmm##M22 ikk!!+.. tG.a888GGH_H_`` %/00??@t@tuu% %%445]5]^^_,>EYZA[A[A[[ U;#.< = =  < >?WXX #t @Q@Q@S@SffffP|,|,|,|,|V: ; ; 6, - -&,ttFI4D'E'E'M'Mi'X'XYY Kcc4::<3F3F3H3H*I*II4OPPXXYmnn((( 566=>>FFGXYY #e&''//?? & U5\\ ) ) + + 3 3N C C %,--55lCC1'%% 7884?/QRRZZ[nooK""U6]]**+ABB0 $$z"D"D"D$,HTT%[[07 }.=@G z.J%K%K#KLLMMMWZ\\ZaZabmZnZn#]88L,=,=,?,?-,OY[#\#\#\]]eefz{{i8i8i8i8i8i8i8i8X %%%%%%%%$,%,%,%,%,%&,%,%,%^H7H7H7H7H7 H7H7H7T'8&@&F&N(9(B(K(S'T(9(B(K(S'T"  Z G 02C2JKKK G y*;*CDDD G 46G6PQQQ G 24E4KLLL G 02C2JKKK G |->-GHHH G  & 3D3M3STTT G  &9J9S9\]]] G  &9J9S9\]]] G |->-EFFF G |->-CDDD G :=G>