o 7]h= @sUddlZddlmZmZmZmZmZm Z m Z m Z m Z m Z mZmZmZddlmZmZddlmZddlZddlZddlZddlZddlZddlZddlmZddlZddlZddl m!Z!ddl"m#Z#ddl$m%Z%dd l&m'Z'd d l(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z1m2Z3d d l4Td d l5Td d l6m7Z7m8Z8d dl9m:Z:ej;ZfZ?e e@dfeAd<Gddde+ZBGddde+ZCGdddeZDdeDddfddZEdeDddfddZFdddZG[+dee=d ee=deHfd!d"ZIeIejJejKLd#reGeMeNeOePeQeReSeTeUeVeWh ZXejYZZeege fee7ge fee[e7ge fee=e[e7ge ffZ\eegeHfee7geHfee[e7geHfee=e[e7geHffZ]ee=e[d$e^gdfZ_ee=e[d$eHgdfZ`ee=e[e[d$e7eHgdfZaee=e[d$e^eHgdfZbejcejdZee:jfjgZge:jfjhZhd%Zieid&ZjeeeiZkd'ld(d)ejmDZndaodd+d,Zp -dd.e]d/e=d0eHde\fd1d2Zq -dd3e=d4e[d5d$d6eHfd7d8Zr -dd3e=d9e[d:e[d5d$d;e7d6eHf de^d6eHf d?d@ZtdAdBZuGdCd$d$eZvGdDdEdEevZwGdFdGdGevZxGdHdIdIexZyGdJdKdKexZzGdLdMdMexZ{GdNdOdOe{Z|e{ev_}GdPdQdQexZ~GdRdSdSe{ZGdTdUdUe~ZGdVdWdWexZGdXdYdYexZGdZd[d[eZGd\d]d]eZGd^d_d_exZGd`dadaexZGdbdcdcexZGdddedeexZGdfdgdgexZGdhdidieZGdjdkdkeZGdldmdmeZGdndodoeZGdpdqdqeZGdrdsdseZGdtdudueZGdvdwdwevZGdxdydyeZGdzd{d{eZGd|d}d}eZGd~ddeZGdddevZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddZGdddeZeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZde\de\fddZeydZedZedZedZedZee.dd*dddZedddZedddZeeBeBedd dBZeeedeZe{deddeeeeBddZde=de=fddZde\fddÄZdddńZeedƃddȡZeedɃddˡZeedƃdedɃdBd̡ZededΡZedσZedЃZdd)e¡DZeZeqZeuZeZeZeZeZeZeZeZeZeZdS)N) OptionalIterable NamedTupleUnionCallableAny GeneratorTupleListTextIOSetDictSequence)ABCabstractmethod)Enum)r) itemgetter)wraps)RLock)Path) _FifoCache_UnboundedCache__config_flags_collapse_string_to_ranges_escape_regex_range_chars_bslash_flattenLRUMemo UnboundedMemo)*) ParseResults_ParseResultsWithOffset)pyparsing_unicode.str_typec@s0eZdZdZdZdZddeDZdZ dS) __compat__aJ 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 :class:`And` expression is nested within an :class:`Or` or :class:`MatchFirst`; maintained for compatibility, but setting to ``False`` no longer restores pre-2.3.1 behavior compatibilityTcCg|] }|ds|qS_ startswith.0__r/`z__compat__.z( collect_all_And_tokens N) __name__ __module__ __qualname____doc__ _type_desccollect_all_And_tokenslocals _all_namessplit _fixed_namesr/r/r/r0r%Os r%c@sjeZdZdZdZdZdZdZdZdZ dZ dZ dde DZ dde DZdde DZed d d ZdS) __diag__ diagnosticFcCr'r(r*r,r/r/r0r1rr2z__diag__.cCg|] }|dr|qS)warnr*r-namer/r/r0r1sr2cCr?) enable_debugr*rAr/r/r0r1tr2returnNcCs|jD]}||qdSN)_warning_namesenable)clsrBr/r/r0enable_all_warningsvs  z__diag__.enable_all_warningsrDN)r3r4r5r7)warn_multiple_tokens_in_named_alternation)warn_ungrouped_named_tokens_in_collectionwarn_name_set_on_empty_Forward!warn_on_parse_using_empty_Forwardwarn_on_assignment_to_Forward%warn_on_multiple_string_args_to_oneof(warn_on_match_first_with_lshift_operator!enable_debug_on_named_expressionsr9r:rF _debug_names classmethodrIr/r/r/r0r=fsr=c@s0eZdZdZdZdZdZdZdZdZ dZ d Z d S) Diagnosticsa Diagnostic configuration (all default to disabled) - ``warn_multiple_tokens_in_named_alternation`` - flag to enable warnings when a results name is defined on a :class:`MatchFirst` or :class:`Or` expression with one or more :class:`And` subexpressions - ``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 when a :class:`Forward` is defined with a results name, but has no contents defined - ``warn_on_parse_using_empty_Forward`` - flag to enable warnings when a :class:`Forward` is defined in a grammar but has never had an expression attached to it - ``warn_on_assignment_to_Forward`` - flag to enable warnings when a :class:`Forward` is defined but is overwritten by assigning using ``'='`` instead of ``'<<='`` or ``'<<'`` - ``warn_on_multiple_string_args_to_oneof`` - flag to enable warnings when :class:`one_of` is incorrectly called with multiple str arguments - ``enable_debug_on_named_expressions`` - flag to auto-enable debug on all subsequent calls to :class:`ParserElement.set_name` Diagnostics are enabled/disabled by calling :class:`enable_diag` and :class:`disable_diag`. All warnings can be enabled by calling :class:`enable_all_warnings`. rrN) r3r4r5r6rKrLrMrNrOrPrQrRr/r/r/r0rU|srU diag_enumrDcCt|jdS)zO Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`). N)r=rGrBr\r/r/r0 enable_diagr_cCr])zP Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`). N)r=disablerBr^r/r/r0 disable_diagr`rbcCs tdS)zU Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`). N)r=rIr/r/r/r0rIs rIcmd_line_warn_options warn_env_varc Csxt|}|D]3}|dddd\}}}}}|ds,|s%|s%|r)|dkr,d}q|dr9|dvr9d}q|S) Nz:::::rYi pyparsingT)rgF)boolr;lowerr+) rcrdrGwarn_optw_action w_message w_categoryw_modulew_liner/r/r0_should_enable_warningss(rqPYPARSINGENABLEALLWARNINGS ParserElement 0123456789 ABCDEFabcdefrhcCsg|] }|tjvr|qSr/)string whitespacer-cr/r/r0r1r2r1rVcstvr fddSdddddd}tptjdd d atdtd |ffd d }tdtdj}||_|S)zAdecorator to trim function calls to match the arity of the targetcs|SrEr/slt)funcr/r0z_trim_arity..rFcSs$tj||d}|d}|ddgS)NlimitrV) traceback extract_tb)tbrframes frame_summaryr/r/r0rsz_trim_arity..extract_tb rVrrrc s z |d}d|WSty@}z&r|j}|dddddk}~|r;kr;d7WYd}~qd}~ww)NrTrVrr) TypeError __traceback__)argsrettertrim_arity_type_errorr found_arityr~rmaxargspa_call_line_synthr/r0wrappers& z_trim_arity..wrapperr3 __class__Nr)_single_arg_builtins_trim_arity_call_liner extract_stackgetattrr3)r~r LINE_DIFFr func_namer/rr0 _trim_aritys   rFfnmessagefatalcs@|dur|nd|r tntttfdd}|S)aC Function to convert a simple predicate function that returns ``True`` or ``False`` into a parse action. Can be used in places when a parse action is required and :class:`ParserElement.add_condition` cannot be used (such as when adding a condition to an operator level in :class:`infix_notation`). Optional keyword arguments: - ``message`` - define a custom message to be used in the raised exception - ``fatal`` - if True, will raise :class:`ParseFatalException` to stop parsing immediately; otherwise will raise :class:`ParseException` Nzfailed user-defined conditioncs t|||s||dSrE)rirzexc_typermsgr/r0paNs z%condition_as_parse_action..pa)ParseFatalExceptionParseExceptionrr)rrrrr/rr0condition_as_parse_action:s  rinstringlocexpr cache_hitc CsJ|rdnd}td|||t||t||t||dt||ddS)Nr rhz&{}Match {} at loc {}({},{}) {} {}^ r)printformatlinenocolline)rrrr cache_hit_strr/r/r0_default_start_debug_actionVs rstartlocendloctokscCs&|rdnd}td|||dS)Nr rhz{}Matched {} -> {})rras_list)rrrrrrrr/r/r0_default_success_debug_actionis rexccCs*|rdnd}td||t|j|dS)Nr rhz {}Match {} failed, {} raised: {})rrtyper3)rrrrrrr/r/r0_default_exception_debug_actionus rcGdS)zG'Do-nothing' debug action, to suppress debugging output during parsing.Nr/)rr/r/r0null_debug_actionrc'@seZdZUdZdZeed<dZeed<dZ e e ed<e ded dfd d Z e d e d dfd dZGdddeZddefddZded dfddZdddZ ddddededed dfddZddd Zdd"ed dfd#d$Zd%ed dfd&d'Zd%ed dfd(d)Zd%ed dfd*d+Zd,ed dfd-d.Zd/d0Zd1d2Z dd3d4Z!d5d6Z" !dd e#e$e%ffd7d8Z&dd9ed:e$d;ed e$fdd?Z(e)Z*iZ+e,e#e$d@efe#e$e-e%e.fffedA<iZ/e)Z0dBdBgZ1 !dd e#e$e%ffdCdDZ2e&Z3e ddEdFZ4dZ5dZ6e ddGdHZ7e dddIdJe e$d dfdKdLZ8e dddIdJe$dNed dfdOdPZ9 dddQd9edRedSed e%fdTdUZ:e;dfde;dVd9edWe$dXedYedZe$d ee;fde;dVd9edWe$dYedZe$d e%f d`daZ?e;dfddbd9edce$dded eZeUZeVZe[Ze\Ze^ZeaZelZerZeRZeSZdS)rsz)Abstract base level parser element class.z DEFAULT_WHITE_CHARSFverbose_stacktraceN_literalStringClasscharsrDcCs$|t_tD] }|jrt||_qdS)a Overrides the default whitespace chars Example:: # default whitespace chars are space, and newline OneOrMore(Word(alphas)).parse_string("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] # change to just treat newline as significant ParserElement.set_default_whitespace_chars(" \t") OneOrMore(Word(alphas)).parse_string("abc def\nghi jkl") # -> ['abc', 'def'] N)rsr_builtin_exprscopyDefaultWhiteCharsset whiteChars)rrr/r/r0set_default_whitespace_charss  z*ParserElement.set_default_whitespace_charsrHcC |t_dS)al 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.parse_string("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # change to Suppress ParserElement.inline_literals_using(Suppress) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parse_string("1999/12/31") # -> ['1999', '12', '31'] N)rsr)rHr/r/r0inline_literals_usings z#ParserElement.inline_literals_usingc@s2eZdZUeeed<eeed<eeed<dS)zParserElement.DebugActions debug_try debug_match debug_failN)r3r4r5 OptionalTypeDebugStartAction__annotations__DebugSuccessActionDebugExceptionActionr/r/r/r0 DebugActionss  rsavelistcCst|_d|_d|_d|_d|_||_d|_tt j |_ d|_ d|_ d|_t|_d|_d|_d|_d|_d|_|ddd|_d|_d|_d|_g|_dS)NTFrh)list parseAction failAction customName _defaultName resultsName saveAsListskipWhitespacerrsrrrmayReturnEmptykeepTabs ignoreExprsdebug streamlined mayIndexErrorerrmsg modalResultsr debugActionsre callPreparse callDuringTrysuppress_warnings_)selfrr/r/r0__init__s,  zParserElement.__init__ warning_typecCs|j||S)aY Suppress warnings emitted for a particular diagnostic on this expression. Example:: base = pp.Forward() base.suppress_warning(Diagnostics.warn_on_parse_using_empty_Forward) # statement would normally raise a warning, but is now suppressed print(base.parseString("x")) )rappend)rrr/r/r0suppress_warnings zParserElement.suppress_warningcCs@t|}|jdd|_|jdd|_|jrttj|_|S)a8 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).set_parse_action(lambda toks: int(toks[0])) integerK = integer.copy().add_parse_action(lambda toks: toks[0] * 1024) + Suppress("K") integerM = integer.copy().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress("M") print(OneOrMore(integerK | integerM | integer).parse_string("5K 100 640K 256M")) prints:: [5120, 100, 655360, 268435456] Equivalent form of ``expr.copy()`` is just ``expr()``:: integerM = integer().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress("M") N)copyrrrrrsrr)rcpyr/r/r0rs  zParserElement.copy)listAllMatchesrBlist_all_matchesrcCs|p|}|||S)a Define name for referencing matching tokens as a nested attribute of the returned parse results. Normally, results names are assigned as you would assign keys in a dict: any existing value is overwritten by later values. If it is necessary to keep all values captured for a particular results name, call ``set_results_name`` with ``list_all_matches`` = True. NOTE: ``set_results_name`` 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.set_results_name("name")`` - see :class:`__call__`. If ``list_all_matches`` is required, use ``expr("name*")``. Example:: date_str = (integer.set_results_name("year") + '/' + integer.set_results_name("month") + '/' + integer.set_results_name("day")) # equivalent form: date_str = integer("year") + '/' + integer("month") + '/' + integer("day") )_setResultsName)rrBrrr/r/r0set_results_name s zParserElement.set_results_namecCs@|dur|S|}|dr|dd}d}||_| |_|S)Nr rT)rendswithrr)rrBrnewselfr/r/r0r*s  zParserElement._setResultsNameT break_flagcsB|r|jdfdd }|_||_|St|jdr|jj|_|S)z Method to invoke the Python pdb debugger when this element is about to be parsed. Set ``break_flag`` to ``True`` to enable, ``False`` to disable. Tcsddl}|||||SNr)pdb set_trace)rr doActions callPreParser _parseMethodr/r0breaker>sz(ParserElement.set_break..breaker_originalParseMethodNTT)_parserhasattr)rrrr/rr0 set_break5s zParserElement.set_breakfnscOs\t|dgkr g|_|Stdd|Dstddd|D|_|d|dd |_|S) ao Define one or more actions to perform when successfully matching parse element definition. Parse actions can be called to perform data conversions, do extra validation, update external data structures, or enhance or replace the parsed tokens. Each 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 The parsed tokens are passed to the parse action as ParseResults. They can be modified in place using list-style append, extend, and pop operations to update the parsed list elements; and with dictionary-style item set and del operations to add, update, or remove any named results. If the tokens are modified in place, it is not necessary to return them with a return statement. Parse actions can also completely replace the given tokens, with another ``ParseResults`` object, or with some entirely different object (common for parse actions that perform data conversions). A convenient way to build a new parse result is to define the values using a dict, and then create the return value using :class:`ParseResults.from_dict`. If None is passed as the ``fn`` parse action, all previously added parse actions for this expression are cleared. Optional keyword arguments: - call_during_try = (default= ``False``) indicate if parse action should be run during lookaheads and alternate testing. For parse actions that have side effects, it is important to only call the parse action once it is determined that it is being called as part of a successful parse. For parse actions that perform additional validation, then call_during_try should be passed as True, so that the validation code is included in the preliminary "try" parses. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See :class:`parse_string` 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:: # parse dates in the form YYYY/MM/DD # use parse action to convert toks from str to int at parse time def convert_to_int(toks): return int(toks[0]) # use a parse action to verify that the date is a valid date def is_valid_date(instring, loc, toks): from datetime import date year, month, day = toks[::2] try: date(year, month, day) except ValueError: raise ParseException(instring, loc, "invalid date given") integer = Word(nums) date_str = integer + '/' + integer + '/' + integer # add parse actions integer.set_parse_action(convert_to_int) date_str.set_parse_action(is_valid_date) # note that integer fields are now ints, not strings date_str.run_tests(''' # successful parse - note that integer fields were converted to ints 1999/12/31 # fail - invalid date 1999/13/31 ''') Ncs|]}t|VqdSrE)callabler-rr/r/r0 z1ParserElement.set_parse_action..zparse actions must be callablecSg|]}t|qSr/rrr/r/r0r1z2ParserElement.set_parse_action..call_during_tryrF)rrallrgetrrrkwargsr/r/r0set_parse_actionLsK zParserElement.set_parse_actioncOs8|jdd|D7_|jp|d|dd|_|S)z Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`. See examples in :class:`copy`. cSr r/r rr/r/r0r1r z2ParserElement.add_parse_action..r rF)rrrrr/r/r0add_parse_actions   zParserElement.add_parse_actionc OsN|D]}|jt||d|dddq|jp#|d|dd|_|S)aAdd a boolean predicate function to expression's list of parse actions. See :class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``, functions passed to ``add_condition`` need to return boolean success/fail of the condition. Optional keyword arguments: - message = define a custom message to be used in the raised exception - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException - call_during_try = boolean to indicate if this method should be called during internal tryParse calls, default=False Example:: integer = Word(nums).set_parse_action(lambda toks: int(toks[0])) year_int = integer.copy() year_int.add_condition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") date_str = year_int + '/' + integer + '/' + integer result = date_str.parse_string("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1) rrF)rrr r)rrrrr)rrrrr/r/r0 add_conditions  zParserElement.add_conditionrcCs ||_|S)a Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments ``fn(s, loc, expr, err)`` where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The function returns no value. It may throw :class:`ParseFatalException` if it is desired to stop parsing immediately.)r)rrr/r/r0set_fail_actions zParserElement.set_fail_actionc CsJd}|r#d}|jD]}z |||\}}d}q ty Yq w|s|SNTF)rrr)rrr exprsFoundedummyr/r/r0_skipIgnorabless   zParserElement._skipIgnorablescCsZ|jr |||}|jr+t|}|j}||kr+|||vr+|d7}||kr+|||vs|SNr)rrrlenr)rrrinstrlen white_charsr/r/r0preParses zParserElement.preParsecCs|gfSrEr/rrrrr/r/r0 parseImplzParserElement.parseImplcCs|SrEr/rrr tokenlistr/r/r0 postParsezParserElement.postParsec Cs&d\}}}|j}t|} |s|jrzJ|r|jr|||} n|} | } |jjr/|j|| |d|js6| | krQz ||| |\}} Wnt yPt || |j |w||| |\}} Wnat y} z|jj rq|j || || d|jr|||| || d} ~ ww|r|jr|||} n|} | } |js| | krz ||| |\}} Wnt yt || |j |w||| |\}} |||| } t| |j|j|jd}|jr||s|jr||r;zA|jD];}z||| |} Wnt y}zt d}||d}~ww| dur| |urt| |j|jot| ttf|jd}qWn^t y:} z|jj r5|j || || dd} ~ ww|jD]=}z||| |} Wnt y\}zt d}||d}~ww| durz| |urzt| |j|jout| ttf|jd}q>|r|jjr|j|| |||d||fS)NrrrVF)asListmodalz exception raised in parse action)rrrrrrrrr! IndexErrorrr Exceptionrr%r!rrrrr isinstancerr)rrrrrTRYMATCHFAIL debugging len_instringpre_loc tokens_starttokenserr ret_tokensrparse_action_excrr/r/r0 _parseNoCaches               zParserElement._parseNoCacherr raise_fatalcCs<z |j||dddWSty|rt|||j|w)NFrr)rrrr)rrrr9r/r/r0 try_parsegs zParserElement.try_parsec Cs,z |||WdSttfyYdSw)NFT)r;rr*)rrrr/r/r0can_parse_nextos zParserElement.can_parse_nextForwardrecursion_memosrc Csd\}}d\}}} |||||f} tjtj} | | } | | jurdtj|d7<z |||||} WntyK} z | | | j | j d} ~ ww| | | d| d |f| WdStj|d7<|j r|j jrz |j j|||ddWn tyYnwt| tr|j r|j jrz|j j|||| ddW| tyY| w| | d| d | d}}}|j r|j jrz|j j|||||ddWn tyYnw||fWdS1swYdS)N)rrr'rrT)rrV)rspackrat_cache_lock packrat_cacher not_in_cachepackrat_cache_statsr8ParseBaseExceptionrrrrrrrrr,r+rr)rrrrrHITMISSr-r.r/lookupcachevaluepeloc_resultrr/r/r0 _parseCaches`          $zParserElement._parseCachecCs2tjdgttjtjdd<tjdSr)rsr@clearrrBr>r/r/r/r0 reset_caches zParserElement.reset_cachecCs tdt_dt_tjt_dS)a$ Disables active Packrat or Left Recursion parsing and their memoization This method also works if neither Packrat nor Left Recursion are enabled. This makes it safe to call before activating Packrat nor Left Recursion to clear any previous settings. FN)rsrN_left_recursion_enabled_packratEnabledr8rr/r/r/r0disable_memoizations  z!ParserElement.disable_memoization)forcecache_size_limitcCsZ|rtntjrtd|durtt_n|dkr"t|dt_ntd|dt_dS)a4 Enables "bounded recursion" parsing, which allows for both direct and indirect left-recursion. During parsing, left-recursive :class:`Forward` elements are repeatedly matched with a fixed recursion depth that is gradually increased until finding the longest match. Example:: from pip._vendor import pyparsing as pp pp.ParserElement.enable_left_recursion() E = pp.Forward("E") num = pp.Word(pp.nums) # match `num`, or `num '+' num`, or `num '+' num '+' num`, ... E <<= E + '+' - num | num print(E.parse_string("1+2+3")) Recursion search naturally memoizes matches of ``Forward`` elements and may thus skip reevaluation of parse actions during backtracking. This may break programs with parse actions which rely on strict ordering of side-effects. Parameters: - cache_size_limit - (default=``None``) - memoize at most this many ``Forward`` elements during matching; if ``None`` (the default), memoize all ``Forward`` elements. Bounded Recursion parsing works similar but not identical to Packrat parsing, thus the two cannot be used together. Use ``force=True`` to disable any previous, conflicting settings. 0Packrat and Bounded Recursion are not compatibleNr)capacityzMemo size of %sT) rsrQrP RuntimeError_UnboundedMemor>_LRUMemoNotImplementedErrorrOrSrRr/r/r0enable_left_recursions$    z#ParserElement.enable_left_recursionrRcCsT|rtntjrtdtjs(dt_|durtt_nt|t_tjt_ dSdS)aw Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions. Parameters: - cache_size_limit - (default= ``128``) - if an integer value is provided will limit the size of the packrat cache; if None is passed, then the cache size will be unbounded; if 0 is passed, the cache will be effectively disabled. This speedup may break existing programs that use parse actions that have side-effects. For this reason, packrat parsing is disabled when you first import pyparsing. To activate the packrat feature, your program must call the class method :class:`ParserElement.enable_packrat`. For best results, call ``enable_packrat()`` immediately after importing pyparsing. Example:: from pip._vendor import pyparsing pyparsing.ParserElement.enable_packrat() Packrat parsing works similar but not identical to Bounded Recursion parsing, thus the two cannot be used together. Use ``force=True`` to disable any previous, conflicting settings. rTTN) rsrQrOrVrPrr@rrLrrZr/r/r0enable_packrats    zParserElement.enable_packrat)parseAll parse_allr^c Cs|p|}t|js||jD]}|q|js |}z"||d\}}|r@|||}t t }|||W|SW|St yW}z tj rN| dd}~ww)a6 Parse a string with respect to the parser definition. This function is intended as the primary interface to the client code. :param instring: The input string to be parsed. :param parse_all: If set, the entire input string must match the grammar. :param parseAll: retained for pre-PEP8 compatibility, will be removed in a future release. :raises ParseException: Raised if ``parse_all`` is set and the input string does not match the whole grammar. :returns: the parsed data as a :class:`ParseResults` object, which may be accessed as a `list`, a `dict`, or an object with attributes if the given parser includes results names. If the input string is required to match the entire grammar, ``parse_all`` flag must be set to ``True``. This is also equivalent to ending the grammar with :class:`StringEnd`(). To report proper column numbers, ``parse_string`` operates on a copy of the input string where all tabs are converted to spaces (8 spaces per tab, as per the default in ``string.expandtabs``). If the input string contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string being parsed, one can ensure a consistent view of the input string by doing one of the following: - calling ``parse_with_tabs`` on your grammar before calling ``parse_string`` (see :class:`parse_with_tabs`), - define your parse action using the full ``(s,loc,toks)`` signature, and reference the input string using the parse action's ``s`` argument, or - explicitly expand the tabs in your input string before calling ``parse_string``. Examples: By default, partial matches are OK. >>> res = Word('a').parse_string('aaaaabaaa') >>> print(res) ['aaaaa'] The parsing behavior varies by the inheriting class of this abstract class. Please refer to the children directly to see more examples. It raises an exception if parse_all flag is set and instring does not match the whole grammar. >>> res = Word('a').parse_string('aaaaabaaa', parse_all=True) Traceback (most recent call last): ... pyparsing.ParseException: Expected end of text, found 'b' (at char 5), (line:1, col:6) rN)rsrNr streamlinerr expandtabsrrEmpty StringEndrCrwith_traceback) rrr_r^rrr4serr/r/r0 parse_string-s.-      zParserElement.parse_string)r maxMatches max_matchesoverlaprrgc cslt||}|js ||jD]}|q|js t|}t|}d}|j} |j } t d} zn||kr| |krz| ||} | || dd\} }Wn t yX| d}Yn5w| |kr| d7} |rmt || | d|| | fV|r| ||}||kr| }n |d7}n| }n| d}||kr| |ks;WdSWdSWdSWdSty}z t jr|dd}~ww)at Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional ``max_matches`` argument, to clip scanning after 'n' matches are found. If ``overlap`` is specified, then overlapping matches will be reported. Note that the start and end locations are reported relative to the string being parsed. See :class:`parse_string` for more information on parsing strings with embedded tabs. Example:: source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" print(source) for tokens, start, end in Word(alphas).scan_string(source): print(' '*start + '^'*(end-start)) print(' '*start + tokens[0]) prints:: sldjf123lsdjjkf345sldkjf879lkjsfd987 ^^^^^ sldjf ^^^^^^^ lsdjjkf ^^^^^^ sldkjf ^^^^^^ lkjsfd rFrr)r4startendN)minrr`rrstrrarrrrs resetCacherrr(rCrrd)rrrhrirrgrrr preparseFnparseFnmatchesprelocnextLocr4nextlocrr/r/r0 scan_stringrs\ '         ( zParserElement.scan_stringrc Csg}d}d|_zX|j||dD]3\}}}|||||r@t|tr+||7}nt|tr;t|ts;||n|||}q|||ddd|D}d ddt |DWSt yt}z t j rk|dd}~ww) ab Extension to :class:`scan_string`, to modify matching text with modified tokens that may be returned from a parse action. To use ``transform_string``, define a grammar and attach a parse action to it that modifies the returned token list. Invoking ``transform_string()`` on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. ``transform_string()`` returns the resulting transformed string. Example:: wd = Word(alphas) wd.set_parse_action(lambda toks: toks[0].title()) print(wd.transform_string("now is the winter of our discontent made glorious summer by this sun of york.")) prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. rTrwNcSsg|]}|r|qSr/r/r-or/r/r0r1r z2ParserElement.transform_string..rhcSr r/rn)r-r{r/r/r0r1r )rrvrr,r!rrr$extendjoinrrCrsrrd) rrroutlastEr}r{rrr/r/r0transform_strings,    zParserElement.transform_stringc CsVt||}ztdd|j|||dDWSty*}z tjr!|dd}~ww)a Another extension to :class:`scan_string`, simplifying the access to the tokens found to match the given parse expression. May be called with optional ``max_matches`` argument, to clip searching after 'n' matches are found. Example:: # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters cap_word = Word(alphas.upper(), alphas.lower()) print(cap_word.search_string("More than Iron, more than Lead, more than Gold I need Electricity")) # the sum() builtin can be used to merge results into a single ParseResults object print(sum(cap_word.search_string("More than Iron, more than Lead, more than Gold I need Electricity"))) prints:: [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']] ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity'] cSsg|]\}}}|qSr/r/)r-r}r{rr/r/r0r1sz/ParserElement.search_string..rwN)rmr!rvrCrsrrd)rrrhrrgrr/r/r0 search_strings  zParserElement.search_string)includeSeparatorsmaxsplitinclude_separatorsc csZ|p|}d}|j||dD]\}}}|||V|r!|dV|}q||dVdS)aT Generator method to split a string using the given expression as a separator. May be called with optional ``maxsplit`` argument, to limit the number of splits; and the optional ``include_separators`` argument (default= ``False``), if the separating matching text should be included in the split results. Example:: punc = one_of(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] r)rhN)rv) rrrrrlastr}r{rr/r/r0r;!s zParserElement.splitcCsN|turt|St|tr||}t|ts!tdt|j t ||gS)ah Implementation of ``+`` operator - returns :class:`And`. Adding strings to a :class:`ParserElement` converts them to :class:`Literal`s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print(hello, "->", greet.parse_string(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 {} with ParserElement) Ellipsis _PendingSkipr,r$rrsrrrr3Androtherr/r/r0__add__As    zParserElement.__add__cCsR|tur t|d|St|tr||}t|ts%tdt|j ||S)zd Implementation of ``+`` operator when left operand is not a :class:`ParserElement` _skipped*r) rSkipTor,r$rrsrrrr3rr/r/r0__radd__is   zParserElement.__radd__cCsBt|tr ||}t|tstdt|j|t |S)zX Implementation of ``-`` operator, returns :class:`And` with error stop r) r,r$rrsrrrr3r _ErrorStoprr/r/r0__sub__zs   zParserElement.__sub__cCs:t|tr ||}t|tstdt|j||S)zd Implementation of ``-`` operator when left operand is not a :class:`ParserElement` rr,r$rrsrrrr3rr/r/r0__rsub__   zParserElement.__rsub__cs|turd}nt|tr#|ddtfkr#d|ddddd}t|tr.|d}}n}t|trtdd |D}|d dd}|ddurPd|df}t|dtr{|ddur{|ddkrgtS|ddkrqtS|dtSt|dtrt|dtr|\}}||8}ntd d d d |Dtdt |j |dkrt d|dkrt d||krdkrt gS|rfdd|r|dkr|}|St g||}|S|}|S|dkr}|St g|}|S)a Implementation of ``*`` operator, allows use of ``expr * 3`` in place of ``expr + expr + expr``. Expressions may also be 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`` )rNNrrrErVrcss |] }|tur |ndVqdSrE)rrxr/r/r0rsz(ParserElement.__mul__..)NNz.cannot multiply ParserElement and ({}) objects,css|]}t|jVqdSrErr3)r-itemr/r/r0rz,cannot multiply ParserElement and {} objectsz/cannot multiply ParserElement by negative valuez@second tuple value must be greater or equal to first tuple valuecs$|dkrt|dStSr)Opt)nmakeOptionalListrr/r0rsz/ParserElement.__mul__..makeOptionalList) rr,tupleint ZeroOrMore OneOrMorerrr|rr3 ValueErrorr)rr minElements optElementsrr/rr0__mul__sl          zParserElement.__mul__cCs ||SrE)rrr/r/r0__rmul__ zParserElement.__rmul__cCsR|tur t|ddSt|tr||}t|ts#tdt|j t ||gS)zP Implementation of ``|`` operator - returns :class:`MatchFirst` T) must_skipr) rrr,r$rrsrrrr3 MatchFirstrr/r/r0__or__s     zParserElement.__or__cCs:t|tr ||}t|tstdt|j||BS)zd Implementation of ``|`` operator when left operand is not a :class:`ParserElement` rrrr/r/r0__ror__rzParserElement.__ror__cC>t|tr ||}t|tstdt|jt||gS)zH Implementation of ``^`` operator - returns :class:`Or` r) r,r$rrsrrrr3Orrr/r/r0__xor__    zParserElement.__xor__cCs:t|tr ||}t|tstdt|j||AS)zd Implementation of ``^`` operator when left operand is not a :class:`ParserElement` rrrr/r/r0__rxor__rzParserElement.__rxor__cCr)zJ Implementation of ``&`` operator - returns :class:`Each` r) r,r$rrsrrrr3Eachrr/r/r0__and__*rzParserElement.__and__cCs:t|tr ||}t|tstdt|j||@S)zd Implementation of ``&`` operator when left operand is not a :class:`ParserElement` rrrr/r/r0__rand__8rzParserElement.__rand__cCt|S)zL Implementation of ``~`` operator - returns :class:`NotAny` )NotAnyrr/r/r0 __invert__FszParserElement.__invert__cCszt|tr |f}t|Wn ty||f}Ynwt|dkr=td|ddt|dkr9dt|d|t|dd}|S)a{ use ``[]`` indexing notation as a short form for expression repetition: - ``expr[n]`` is equivalent to ``expr*n`` - ``expr[m, n]`` is equivalent to ``expr*(m, n)`` - ``expr[n, ...]`` or ``expr[n,]`` is equivalent to ``expr*n + ZeroOrMore(expr)`` (read as "at least n instances of ``expr``") - ``expr[..., n]`` is equivalent to ``expr*(0, n)`` (read as "0 to n instances of ``expr``") - ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)`` - ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)`` ``None`` may be used in place of ``...``. Note that ``expr[..., n]`` and ``expr[m, n]``do not raise an exception if more than ``n`` ``expr``s exist in the input stream. If this behavior is desired, then write ``expr[..., n] + ~expr``. rVz,only 1 or 2 index arguments supported ({}{})NrYz... [{}]rh)r,r$iterrrrr)rkeyrr/r/r0 __getitem__Ps$     "zParserElement.__getitem__cCs|dur ||S|S)a Shortcut for :class:`set_results_name`, with ``list_all_matches=False``. If ``name`` is given with a trailing ``'*'`` character, then ``list_all_matches`` will be passed as ``True``. If ``name` is omitted, same as calling :class:`copy`. Example:: # these are equivalent userdata = Word(alphas).set_results_name("name") + Word(nums + "-").set_results_name("socsecno") userdata = Word(alphas)("name") + Word(nums + "-")("socsecno") N)rrrrBr/r/r0__call__xs zParserElement.__call__cCr)z Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from cluttering up returned output. )Suppressrr/r/r0suppressszParserElement.suppress recursivecC d|_|S)z Enables the skipping of whitespace before matching the characters in the :class:`ParserElement`'s defined pattern. :param recursive: If ``True`` (the default), also enable whitespace skipping in child elements (if any) Trrrr/r/r0ignore_whitespaceszParserElement.ignore_whitespacecCr)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. :param recursive: If true (the default), also disable whitespace skipping in child elements (if any) Frrr/r/r0leave_whitespaceszParserElement.leave_whitespace copy_defaultscCsd|_t||_||_|S)z8 Overrides the default whitespace chars T)rrrr)rrrr/r/r0set_whitespace_charss z"ParserElement.set_whitespace_charscCr)z Overrides default behavior to expand ```` s to spaces before parsing the input string. Must be called before ``parse_string`` when the input grammar contains elements that match ```` characters. T)rrr/r/r0parse_with_tabsszParserElement.parse_with_tabsrcCsVddl}t|tr t|}t|tr||jvr|j||S|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.parse_string('ablaj /* comment */ lskjd') # -> ['ablaj'] patt.ignore(c_style_comment) patt.parse_string('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd'] rN)typingr,r$rrrr)rrrr/r/r0ignores    zParserElement.ignore start_actionsuccess_actionexception_actioncCs&||pt|pt|p t|_d|_|S)a  Customize display of debugging messages while doing pattern matching: - ``start_action`` - method to be called when an expression is about to be parsed; should have the signature ``fn(input_string: str, location: int, expression: ParserElement, cache_hit: bool)`` - ``success_action`` - method to be called when an expression has successfully parsed; should have the signature ``fn(input_string: str, start_location: int, end_location: int, expression: ParserELement, parsed_tokens: ParseResults, cache_hit: bool)`` - ``exception_action`` - method to be called when expression fails to parse; should have the signature ``fn(input_string: str, location: int, expression: ParserElement, exception: Exception, cache_hit: bool)`` T)rrrrrr)rrrrr/r/r0set_debug_actionsszParserElement.set_debug_actionsflagcCs |r |ttt|Sd|_|S)a Enable display of debugging messages while doing pattern matching. Set ``flag`` to ``True`` to enable, ``False`` to disable. Example:: wd = Word(alphas).set_name("alphaword") integer = Word(nums).set_name("numword") term = wd | integer # turn on debugging for wd wd.set_debug() OneOrMore(term).parse_string("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:`set_debug_actions`. 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:`set_name` 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 ``set_name`` is ``"W:(A-Za-z)"``. F)rrrrr)rrr/r/r0 set_debugs%zParserElement.set_debugcCs|jdur ||_|jSrE)r_generateDefaultNamerr/r/r0 default_name!s  zParserElement.default_namecCr)zg Child classes must define this method, which defines how the ``default_name`` is set. Nr/rr/r/r0r'rz"ParserElement._generateDefaultNamecCs$||_d|j|_tjr||S)a\ Define name for this expression, makes debugging and exception messages clearer. Example:: Word(nums).parse_string("ABC") # -> Exception: Expected W:(0-9) (at char 0), (line:1, col:1) Word(nums).set_name("integer").parse_string("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1) Expected )rrBrr=rRrrr/r/r0set_name-s  zParserElement.set_namecCs|jdur|jS|jSrE)rrrr/r/r0rB:szParserElement.namecC|jSrErBrr/r/r0__str__?zParserElement.__str__cCrrErzrr/r/r0__repr__Br"zParserElement.__repr__cCsd|_d|_|SNT)rrrr/r/r0r`EszParserElement.streamlinecCgSrEr/rr/r/r0recurseJr&zParserElement.recursecCs.|dd|g}|D]}||q dSrE)r_checkRecursionrparseElementListsubRecCheckListrr/r/r0rMs  zParserElement._checkRecursioncCs|gdS)zj Check defined expressions for valid structure, check for infinite recursive definitions. N)r)r validateTracer/r/r0validateRszParserElement.validateutf-8file_or_filenameencodingc Cs|p|}z|}Wn$ty.t|d|d }|}Wdn1s'wYYnwz|||WStyK}z tjrB|dd}~ww)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. rrN)readAttributeErroropenrfrCrsrrd)rrrr_r^ file_contentsfrr/r/r0 parse_fileXs"     zParserElement.parse_filecCsB||urdSt|tr|j|ddSt|trt|t|kSdS)NTr_F)r,r$rrrsvarsrr/r/r0__eq__ts  zParserElement.__eq__cCrrE)idrr/r/r0__hash__}r"zParserElement.__hash__ test_stringcCs6|o|}z |jt||dWdStyYdSw)a Method for quick testing of a parser against a test string. Good for simple inline microtests of sub expressions while building up larger parser. Parameters: - ``test_string`` - to test against this expression for a match - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests Example:: expr = Word(nums) assert expr.matches("100") rTF)rfrnrC)rrr_r^r/r/r0rrs zParserElement.matches#)r^fullDump printResults failureTestsr%testscomment full_dump print_results failure_tests post_parsefilewith_line_numbersrrrr%c  s(ddlm}| o |} | o |} | o|} | p|} |p|}t|tr1t|jfdd|D}t|tr:t|}|durAt j }|j }g}g}d}td t dt}d }|D]4}|durg||d sk|rx|sx|| rt||n|qZ|s{qZ|rdd|nd | r||n|g}g}z|||}|j|| d }Wnnty}z1t|trd nd }|||dt|tjr|t|j |o| }|}WYd}~nd}~wt!y}z%|d"t|j#|tjr|t|j |o| }|}WYd}~nmd}~ww|o| }|durpz)|||}|dur=t|t$r5||%n|t|n||%Wn3t!yo}z||j%| d|d"|j#t|j#|WYd}~nd}~ww||j%| d|d | r|d||||fqZ||fS)a Execute the parse expression on a series of test strings, showing each test, the parsed results or where the parse failed. Quick and easy way to run a parse expression against a list of sample strings. Parameters: - ``tests`` - a list of separate test strings, or a multiline string of test strings - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests - ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test string; pass None to disable comment filtering - ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline; if False, only dump nested list - ``print_results`` - (default= ``True``) prints test output to stdout - ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing - ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as `fn(test_string, parse_results)` and returns a string to be added to the test output - ``file`` - (default= ``None``) optional file-like object to which test output will be written; if None, will default to ``sys.stdout`` - ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers Returns: a (success, results) tuple, where success indicates that all tests succeeded (or failed if ``failure_tests`` is True), and the results contain a list of lines of each test's output Example:: number_expr = pyparsing_common.number.copy() result = number_expr.run_tests(''' # unsigned integer 100 # negative integer -100 # float with scientific notation 6.02e23 # integer with scientific notation 1e-12 ''') print("Success" if result[0] else "Failed!") result = number_expr.run_tests(''' # stray character 100Z # missing leading digit before '.' -.100 # too many '.' 3.14.159 ''', failure_tests=True) print("Success" if result[0] else "Failed!") prints:: # unsigned integer 100 [100] # negative integer -100 [-100] # float with scientific notation 6.02e23 [6.02e+23] # integer with scientific notation 1e-12 [1e-12] Success # stray character 100Z ^ FAIL: Expected end of text (at char 3), (line:1, col:4) # missing leading digit before '.' -.100 ^ FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) # too many '.' 3.14.159 ^ FAIL: Expected end of text (at char 4), (line:1, col:5) Success Each test string must be on a single line. If you want to test a string that spans multiple lines, create a test like this:: expr.run_tests(r"this is a test\n of strings that spans \n 3 lines") (Note that this is a raw string literal, you must include the leading ``'r'``.) r)pyparsing_testcsg|]}|qSr/r/)r- test_line line_stripr/r0r1r z+ParserElement.run_tests..NT\n uFrhrz(FATAL)zFAIL: zFAIL-EXCEPTION: {}: {})fullz{} failed: {}: {})&testingrr,r$rstriprstrip splitlinesLiteralsysstdoutwriter replace_withr quoted_stringrrrrr|rlstriprfrCrexplainrnrsrr{r format_tbrr+rr3r!dump)rrr_rrrrrrrr^rrrr%rprint_ allResultscommentssuccessNLBOMr}r}rKrIrrpp_valuerr/rr0 run_testss p           zParserElement.run_testsrW output_htmlverticalshow_results_namesc Ksz ddlm}m}Wnty}ztd|d}~ww||||||d}t|ttfrPt |ddd} | ||WddS1sIwYdS| ||dS) a  Create a railroad diagram for the parser. Parameters: - output_html (str or file-like object) - output target for generated diagram HTML - vertical (int) - threshold for formatting multiple alternatives vertically instead of horizontally (default=3) - show_results_names - bool flag whether diagram should show annotations for defined results names Additional diagram-formatting keyword arguments can also be included; see railroad.Diagram class. r) to_railroadrailroad_to_htmlzMmust ``pip install pyparsing[diagrams]`` to generate parser railroad diagramsN)rrdiagram_kwargswrr) diagramrr ImportErrorr+r`r,rnrrr ) rrrrrrrierailroad diag_filer/r/r0create_diagramZs,"zParserElement.create_diagramF)rDrsTrrJrE)r\)rrsrDrs)rF)TrTTFNNF)rWF)r3r4r5r6rrnrrrirrr staticmethodrrrrrrUrrrrr ParseActionrrParseConditionrParseFailActionrrrr!r%r rr!r8r;r<rrecursion_lockr>DictTyperr+r@r?rBrLrrNrPrOrQr[r]rf_MAX_INTrrvrrr;rrrrrrrrrrrrr__iter__rrrrrr rrrrrrrrpropertyrrrrrBrrr`rrrrrr rrrrrr rrr&setDefaultWhitespaceCharsinlineLiteralsUsingsetResultsNamesetBreaksetParseActionaddParseAction addCondition setFailActiontryParse canParseNextroenableLeftRecursion enablePackrat parseString scanString searchStringtransformStringsetWhitespaceChars parseWithTabssetDebugActionssetDebug defaultNamesetName parseFilerunTestsignoreWhitespaceleaveWhitespacer/r/r/r0rssP     ! V #   f    0    / , H Y1 +   (V(     /               G  ,csHeZdZddedeffdd ZddZdd Zd d Zd d Z Z S)rFrrcst||_||_dSrE)superranchorr)rrrrr/r0r  z_PendingSkip.__init__cCst|jtddS)Nrb...)rnrMrbreplacerr/r/r0rz!_PendingSkip._generateDefaultNamecs\t|dd}jr'dd}fdd}j||||B|Sj||S)NrPrcSs0|jr |jdgkr|d=|dddSdS)Nrhr_skipped)rSrpopr}r/r/r0rsz'_PendingSkip.__add__..must_skipcs@|jdddgkr|ddtjd|d<dSdS)NrrhrSz missing <>)rSrrTreprrMrUrr/r0 show_skips z'_PendingSkip.__add__..show_skip)rrrrMr)rrskipperrrXr/rr0rs  z_PendingSkip.__add__cCrrE)rFrr/r/r0rrz_PendingSkip.__repr__cGstd)NzBuse of `...` expression without following SkipTo target expression)r+)rrr/r/r0r!sz_PendingSkip.parseImplr') r3r4r5rsrirrrrr! __classcell__r/r/rNr0rs rcs(eZdZdZfddZddZZS)TokenzYAbstract :class:`ParserElement` subclass, for defining atomic matching patterns. cstjdddS)NFrrLrrrNr/r0rzToken.__init__cCs t|jSrErrr/r/r0rrzToken._generateDefaultName)r3r4r5r6rrrZr/r/rNr0r[s r[cs eZdZdZfddZZS)rbz, An empty token, will always match. ctd|_d|_dSrrLrrrrrNr/r0rrOzEmpty.__init__)r3r4r5r6rrZr/r/rNr0rbsrbc*eZdZdZfddZdddZZS)NoMatchz( A token that will never match. cs td|_d|_d|_dS)NTFzUnmatchable token)rLrrrrrrNr/r0rs  zNoMatch.__init__TcCst|||j|rE)rrr r/r/r0r!szNoMatch.parseImplr(r3r4r5r6rr!rZr/r/rNr0rb rbcsDeZdZdZd dddedeffddZdd Zdd d ZZS)ra Token to exactly match a specified string. Example:: Literal('blah').parse_string('blah') # -> ['blah'] Literal('blah').parse_string('blahfooblah') # -> ['blah'] Literal('blah').parse_string('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`. rh matchString match_stringrfcst|p|}||_t||_z|d|_Wn ty#tdwd|j|_ d|_ d|_ |jdkr@t |t urBt|_dSdSdS)Nrz2null string passed to Literal; use Empty() insteadrFr)rLrmatchrmatchLenfirstMatchCharr*rrBrrrrr_SingleCharLiteralrrrgrfrNr/r0r s     zLiteral.__init__cC t|jSrErWrhrr/r/r0r rzLiteral._generateDefaultNameTcCs<|||jkr||j|r||j|jfSt|||j|rE)rjr+rhrirrr r/r/r0r! s zLiteral.parseImplrhr() r3r4r5r6rnrrr!rZr/r/rNr0rs rc@eZdZdddZdS)rkTcCs,|||jkr|d|jfSt|||j|r)rjrhrrr r/r/r0r! sz_SingleCharLiteral.parseImplNr(r3r4r5r!r/r/r/r0rk rkc szeZdZdZedZ   dddddedeed ed ed eef fd d Z ddZ dddZ e dddZ e ZZS)Keyworda Token to exactly match a specified string as a keyword, that is, it must be immediately followed by a non-keyword character. Compare with :class:`Literal`: - ``Literal("if")`` will match the leading ``'if'`` in ``'ifAndOnlyIf'``. - ``Keyword("if")`` will not; it will only match the leading ``'if'`` in ``'if x=1'``, or ``'if(y==2)'`` Accepts two optional constructor arguments in addition to the keyword string: - ``identChars`` is a string of characters that would be valid identifier characters, defaulting to all alphanumerics + "_" and "$" - ``caseless`` allows case-insensitive matching, default is ``False``. Example:: Keyword("start").parse_string("start") # -> ['start'] Keyword("start").parse_string("starting") # -> Exception For case-insensitive matching, use :class:`CaselessKeyword`. z_$rhNFrf identCharsrg ident_charscaselessrfrucst|p|}|durtj}|p|}||_t||_z|d|_Wn ty.t dwd t |j |j |_d|_d|_||_|rN||_|}t||_dS)Nrz2null string passed to Keyword; use Empty() insteadzExpected {} {}F)rLrrsDEFAULT_KEYWORD_CHARSrhrrirjr*rrrr3rBrrrrwupper caselessmatchrru)rrgrvrwrfrurNr/r0rF s(    zKeyword.__init__cCrmrErnrr/r/r0rc rzKeyword._generateDefaultNameTcCsR|j}|}|jrU||||j|jkrT|dks%||d|jvrL|t||jks:|||j|jvrB||j|jfS|d7}||j}nV|d7}|d}nM|||jkra|jdksh| |j|r|dksu||d|jvr|t||jks|||j|jvr||j|jfS|d7}||j}n|d7}|d}t ||||)Nrrz/, was immediately followed by keyword characterz7, keyword was immediately preceded by keyword characterz7, keyword was immediately followed by keyword character) rrwriryrzrurrhrjr+r)rrrrrerrlocr/r/r0r!f s8    zKeyword.parseImplrDcCr)zX Overrides the default characters used by :class:`Keyword` expressions. N)rsrx)rr/r/r0set_default_keyword_chars s z!Keyword.set_default_keyword_chars)rhNFr(rJ)r3r4r5r6 alphanumsrxrnrrirrr!r)r|setDefaultKeywordCharsrZr/r/rNr0rs) s2 /  rscs<eZdZdZd dddedeffddZd d d ZZS) CaselessLiteralat Token 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")).parse_string("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD'] (Contrast with example for :class:`CaselessKeyword`.) rhrergrfcs.|p|}t|||_d|j|_dS)Nr)rLrry returnStringrBrrlrNr/r0r szCaselessLiteral.__init__TcCs<||||j|jkr||j|jfSt|||j|rE)riryrhrrrr r/r/r0r! szCaselessLiteral.parseImplror()r3r4r5r6rnrr!rZr/r/rNr0r s rc sHeZdZdZ  d ddddedeededeeffd d ZZS) CaselessKeywordz Caseless version of :class:`Keyword`. Example:: OneOrMore(CaselessKeyword("CMD")).parse_string("cmd CMD Cmd10") # -> ['CMD', 'CMD'] (Contrast with example for :class:`CaselessLiteral`.) rhNrtrgrvrfrucs&|p|}|p|}tj||dddS)NT)rwr])rrgrvrfrurNr/r0r szCaselessKeyword.__init__)rhN)r3r4r5r6rnrrrZr/r/rNr0r s  rcsLeZdZdZ dddddededeffd d Zd d ZdddZZ S) CloseMatchaA 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 - ``caseless`` - a boolean indicating whether to ignore casing when comparing characters - ``max_mismatches`` - (``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.parse_string("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']}) patt.parse_string("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1) # exact match patt.parse_string("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']}) # close match allowing up to 2 mismatches patt = CloseMatch("ATCATCGAATGGA", max_mismatches=2) patt.parse_string("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']}) NrF) maxMismatchesrwrgmax_mismatchesrcsN|dur|n|}t||_||_d|j|j|_||_d|_d|_dS)Nz(Expected {!r} (with up to {} mismatches)F) rLrrgrrrrwrr)rrgrrrwrNr/r0r s  zCloseMatch.__init__cCsdt|j|jS)Nz{}:{!r})rrr3rgrr/r/r0r zCloseMatch._generateDefaultNameTcCs|}t|}|t|j}||krg|j}d}g} |j} tt||||D]%\}} | \} } |jr:| | } } | | krK| |t| | krKnq&||d}t|||g}||d<| |d<||fSt |||j |)Nrroriginal mismatches) rrgr enumerateziprwrjrr!rr)rrrrrkrmaxlocrgmatch_stringlocrrs_msrcmatresultsr/r/r0r! s2    zCloseMatch.parseImplrEr( r3r4r5r6rnrrrr!rZr/r/rNr0r s%rcseZdZdZ       ddddddded eed ed ed ed edeedeedeededeeffddZddZ dddZ Z S)Worda8 Token for matching words composed of allowed character sets. Parameters: - ``init_chars`` - string of all characters that should be used to match as a word; "ABC" will match "AAA", "ABAB", "CBAC", etc.; if ``body_chars`` is also specified, then this is the string of initial characters - ``body_chars`` - string of characters that can be used for matching after a matched initial character as given in ``init_chars``; if omitted, same as the initial characters (default=``None``) - ``min`` - minimum number of characters to match (default=1) - ``max`` - maximum number of characters to match (default=0) - ``exact`` - exact number of characters to match (default=0) - ``as_keyword`` - match as a keyword (default=``False``) - ``exclude_chars`` - characters that might be found in the input ``body_chars`` string but which should not be accepted for matching ;useful to define a word of all printables except for one or two characters, for instance (default=``None``) :class:`srange` is useful for defining custom character set strings for defining :class:`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) ``alphas``, ``nums``, and ``printables`` are also defined in several Unicode sets - see :class:`pyparsing_unicode``. 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, exclude_chars=",") rhNrrF) initChars bodyChars asKeyword excludeChars init_chars body_charsrmmaxexact as_keyword exclude_charsrrrrc s|p|}| p|} | p |} | p|} t|s!tdt|jt|}||_| r:t| } || 8}| r:t| | } dt ||_ | rRdt | |_ t| |_ n dt ||_ t||_ |dk|_ |dkrltd||_|dkrw||_nt|_|dkr||_||_d|j|_d|_| |_d|j|j BvrI|dkrK|dkrM|j |jkr|dkrd } n|dkrd} nd |j|jtkrdn|j} d t|j| |_nIt|jdkr|dkrd } nd |d} dt|j t|j | |_n$|dkrd } n|dkrd} nd |d} dt|jt|j | |_|jr&d|jd|_z t|j|_Wntjy>d|_YdSw|jj|_t|_ dSdSdSdS)Nz,invalid {}, initChars cannot be empty stringrhrrzUcannot specify a minimum length < 1; use Opt(Word()) if zero-length word is permittedrFr+ {{{},{}}}z[{}]{}r z{{0,{}}}z{}[{}]{}rVz [{}][{}]{}z\b)!rLrrrrr3rrr|sorted initCharsOrig bodyCharsOrigr maxSpecifiedminLenmaxLenr/rBrrrrreStringrrescapecompile sre_constantserrorrhre_match _WordRegexr) rrrrmrrrrrrrrrepeatrNr/r0rm s      &       z Word.__init__cCsdd}|j|jkrd||j||j}nd||j}|jdks)|jtkrY|j|jkrB|jdkr:|ddS|d|jS|jtkrO|d|jS|d |j|jS|S) NcSs4d}t|dd}t||kr|d|ddS|S)NF) re_escaperWrP)rr)r{ max_repr_lenr/r/r0 charsAsStr s   z-Word._generateDefaultName..charsAsStrz W:({}, {})zW:({})rrVz{{{}}}z {{{},...}}r)rrrrrr/)rrbaser/r/r0r s     zWord._generateDefaultNameTc Cs|||jvrt|||j||}|d7}t|}|j}||j}t||}||kr>|||vr>|d7}||kr>|||vs0d}|||jkrJd}n+|jrZ||krZ|||vrZd}n|j ru|dkri||d|vss||kru|||vrud}|rt|||j|||||fS)NrFTr) rrrrrrrmrrr) rrrrrkr bodycharsrthrowExceptionr/r/r0r! s2   zWord.parseImpl)rhNrrrFNr() r3r4r5r6rnrrrirrr!rZr/r/rNr0r, sNB     qrc@rp)rTcCs4|||}|st|||j||}||fSrE)rrrrlgroup)rrrrrKr/r/r0r! s  z_WordRegex.parseImplNr(rqr/r/r/r0r rrrc sLeZdZdZ  d ddddededeeded eef fd d ZZS) CharzA short-cut class for defining :class:`Word` ``(characters, exact=1)``, when defining a match of any single character in a string of characters. FN)rrcharsetrrrrcsd|p|}|p|}tj|d||ddt|j|_|r$d|j|_t|j|_|jj|_ dS)Nr)rrrz[{}]z\b{}\b) rLrrrrrrrrhr)rrrrrrrNr/r0r, s z Char.__init__)FN) r3r4r5r6rnrirrrZr/r/rNr0r& s$rcseZdZdZ   dddddedeejefde de d e d e f fd d Z d dZ dddZ dddZ dddZdedefddZZS)RegexaToken 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 :class:`ParseResults`. If instead of the Python stdlib ``re`` module you wish to use a different RE module (such as the ``regex`` module), you can do so by building your ``Regex`` object with a compiled RE that was compiled using ``regex``. Example:: realnum = Regex(r"[+-]?\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})") # named fields in a regex will be returned as named results date = Regex(r'(?P\d{4})-(?P\d\d?)-(?P\d\d?)') # the Regex class will accept re's compiled using the regex module import regex parser = pp.Regex(regex.compile(r'[0-9]')) rF) asGroupListasMatchpatternflags as_group_listas_matchrrcst|p|}|p |}t|tr=|std||_||_zt|j|j|_|j|_ Wn+t j y<td |wt |drUt |drU||_|j|_|_ ||_ntd|jj|_d|j|_d|_|dd 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() insteadz&invalid pattern ({!r}) passed to RegexrrhzCRegex may only be constructed with a string or a compiled RE objectrFrhN)rLrr,r$rrrrrrrrrrrrhrrBrrrrrparseImplAsGroupListr!parseImplAsMatch)rrrrrrrrNr/r0rZ sD      zRegex.__init__cCsdt|jddS)NzRe:({})z\\\)rrWrrQrr/r/r0r rRzRegex._generateDefaultNameTc Csb|||}|st|||j||}t|}|}|r-|D]\}}|||<q$||fSrE)rrrrlr!r groupdictitems) rrrrrKrdkvr/r/r0r! s   zRegex.parseImplcCs8|||}|st|||j||}|}||fSrE)rrrrlgroupsrrrrrKrr/r/r0r s zRegex.parseImplAsGroupListcCs4|||}|st|||j||}|}||fSrE)rrrrlrr/r/r0r s zRegex.parseImplAsMatchreplrDcsPjrtdjrtrtdjrfdd}nfdd}|S)a Return :class:`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.transform_string("h1:main title:")) # prints "

main title

" z-cannot use sub() with Regex(asGroupList=True)z9cannot use sub() with a callable with Regex(asMatch=True)cs|dSr)expandr4)rr/r0r zRegex.sub..pacsj|dSr)rsubrrrr/r0r r^)rrrrr)rrrr/rr0r s  z Regex.sub)rFFr()r3r4r5r6rrr RegexFlagrrirrr!rrrnrsrrZr/r/rNr0rA s4 8   rcseZdZdZdZ       ddddddddded eed eed ed ed eedededeedeededeedeffddZddZ dddZ Z S) QuotedStringa Token for matching strings that are delimited by quoting characters. Defined with the following parameters: - ``quote_char`` - string of one or more characters defining the quote delimiting string - ``esc_char`` - character to re_escape quotes, typically backslash (default= ``None``) - ``esc_quote`` - special quote sequence to re_escape an embedded quote string (such as SQL's ``""`` to re_escape an embedded ``"``) (default= ``None``) - ``multiline`` - boolean indicating whether quotes can span multiple lines (default= ``False``) - ``unquote_results`` - boolean indicating whether the matched text should be unquoted (default= ``True``) - ``end_quote_char`` - string of one or more characters defining the end of the quote delimited string (default= ``None`` => same as quote_char) - ``convert_whitespace_escapes`` - convert escaped whitespace (``'\t'``, ``'\n'``, etc.) to actual whitespace (default= ``True``) Example:: qs = QuotedString('"') print(qs.search_string('lsjdf "This is the quote" sldjf')) complex_qs = QuotedString('{{', end_quote_char='}}') print(complex_qs.search_string('lsjdf {{This is the "quote"}} sldjf')) sql_qs = QuotedString('"', esc_quote='""') print(sql_qs.search_string('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']] ))z\t )rr)z\f )z\r rhNFT) quoteCharescCharescQuoteunquoteResults endQuoteCharconvertWhitespaceEscapes quote_charesc_char esc_quote multilineunquote_resultsend_quote_charconvert_whitespace_escapesrrrrrrc sVt| p|} | p |} | o|} | p|} | o|} |p|}|}|s'td| dur.|} n | } | s8td|_t|_|d_| _t| _ | _ | _ | _ | _ d}d}| rl|d|t| 7}d}| r|d|t| 7}d}tj d_tjd kr|d |dfd d ttjd dd Dd7}d}|rtjtjB_|d|tjd| durt| nd7}nd_|d|tjd| durt| nd7}dtjd|dtjg_ztjj_j_jj_Wntjytdjwdj_ d_!d_"dS)Nz%quote_char cannot be the empty stringz'endQuoteChar cannot be the empty stringrrhz{}(?:{})|z {}(?:{}.)z(.)rz{}(?:c 3s<|]}dtjd|tj|dVqdS)z (?:{}(?!{}))N)rrrr)r-rfrr/r0r; s z(QuotedString.__init__..r)z {}(?:[^{}{}])z{}(?:[^{}\n\r{}])z(?:z)*z$invalid pattern {!r} passed to RegexrFT)#rLrrrrr quoteCharLenfirstQuoteCharrendQuoteCharLenrrrrrrrescCharReplacePatternr|range MULTILINEDOTALLrrrrrrhrrrrBrrr)rrrrrrrrrrrrrrsep inner_patternrNrr0r s             zQuotedString.__init__cCs4|j|jkrt|jtrd|jSd|j|jS)Nzstring enclosed in {!r}z.quoted string, starting with {} ending with {})rrr,r$rrr/r/r0rl s  z!QuotedString._generateDefaultNamecCs|||jkr |||pd}|st|||j||}|}|jr]||j|j }t |t r]d|vrG|j rG|j D] \}}| ||}q<|jrRt|jd|}|jr]| |j|j}||fS)Nrz\g<1>)rrrrrlrrrrr,r$rws_maprQrrrrrr)rrrrrKrwslitwscharr/r/r0r!t s(  zQuotedString.parseImpl)rhNNFTNTr() r3r4r5r6rrnrrirrr!rZr/r/rNr0r s\&     qrc sXeZdZdZ    ddddededed ed ef fd d Zd dZdddZZ S) CharsNotInaToken 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(delimited_list(csv_value).parse_string("dkls,lsdkjf,s12 34,@!#,213")) prints:: ['dkls', 'lsdkjf', 's12 34', '@!#', '213'] rhrr)notChars not_charsrmrrrcstd|_|p ||_t|j|_|dkrtd||_|dkr&||_nt |_|dkr3||_||_d|j |_ |jdk|_ d|_ dS)NFrzacannot specify a minimum length < 1; use Opt(CharsNotIn()) if zero-length char group is permittedrr)rLrrrr notCharsSetrrrr/rBrrr)rrrmrrrrNr/r0r s$      zCharsNotIn.__init__cCs6t|j}t|dkrd|jddSd|jS)Nrz !W:({}...) z!W:({}))rrrr)r not_chars_strr/r/r0r s   zCharsNotIn._generateDefaultNameTcCs|j}|||vrt|||j||}|d7}t||jt|}||kr9|||vr9|d7}||kr9|||vs+|||jkrHt|||j|||||fSr)rrrrmrrr)rrrrnotcharsrkmaxlenr/r/r0r! s zCharsNotIn.parseImpl)rhrrrr(rr/r/rNr0r s*#rc seZdZdZidddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*Zd9d.ed/ed0ed1effd2d3 Zd4d5Zd:d7d8Z Z S);WhiteaSpecial 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. rzrzrzrzrz zu zu᠎zu z u z u z u z u zu zu zu zu zz z zzzz)u u u​u u u  rrwsrmrrcs~t|_jdfddjDddd_dj_|_ |dkr.|_ nt _ |dkr=|_ |_ dSdS)Nrhc3s|] }|jvr|VqdSrE) matchWhiterxrr/r0r sz!White.__init__..Trrr) rLrrrr| whiteStrsrrBrrrr/)rrrmrrrNrr0r s   zWhite.__init__cCsddd|jDS)Nrhcss|]}tj|VqdSrE)rrrxr/r/r0r! rz-White._generateDefaultName..)r|rrr/r/r0r zWhite._generateDefaultNameTcCs|||jvrt|||j||}|d7}||j}t|t|}||kr;|||jvr;|d7}||kr;|||jvs,|||jkrJt|||j|||||fSr)rrrrrmrr)rrrrrkrr/r/r0r!# s zWhite.parseImpl)rrrrr() r3r4r5r6rrnrrrr!rZr/r/rNr0r s^       rcseZdZfddZZS) PositionTokencr_rr`rrNr/r0r4 rOzPositionToken.__init__)r3r4r5rrZr/r/rNr0r3 srcs8eZdZdZdeffdd ZddZd dd ZZS) GoToColumnzaToken to advance to a specific column of input text; useful for tabular report scraping. colnocst||_dSrE)rLrr)rrrNr/r0r?   zGoToColumn.__init__cCs~t|||jkr=t|}|jr|||}||kr=||r=t|||jkr=|d7}||kr=||r=t|||jks'|Sr)rrrrisspace)rrrrr/r/r0rC s   zGoToColumn.preParseTcCsDt||}||jkrt||d|||j|}|||}||fS)NzText not in expected column)rr)rrrrthiscolnewlocrr/r/r0r!P s   zGoToColumn.parseImplr() r3r4r5r6rrrr!rZr/r/rNr0r: s  rcs2eZdZdZfddZddZd ddZZS) LineStartaMatches 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).search_string(test): print(t) prints:: ['AAA', ' this line'] ['AAA', ' and this line'] csFt|t|jB|_|jdt|j|_ d|_ dS)NrzExpected start of line) rLrrrrorig_whiteCharsdiscardrbrrYrrrNr/r0rp s   zLineStart.__init__cCsb|dkr|S|j||}d|jvr/|||ddkr/|j||d}|||ddks|S)Nrrr)rYrr)rrrrr/r/r0rx s zLineStart.preParseTcCs&t||dkr |gfSt|||j|r)rrrr r/r/r0r! szLineStart.parseImplr()r3r4r5r6rrr!rZr/r/rNr0rY s   rcra)LineEndzTMatches if current position is at the end of a line within the parse string cs0t|jd|j|jddd|_dS)NrFrzExpected end of line)rLrrrrrrrNr/r0r s   zLineEnd.__init__TcCs\|t|kr||dkr|ddfSt|||j||t|kr&|dgfSt|||j|)Nrrrrrr r/r/r0r! s     zLineEnd.parseImplr(rcr/r/rNr0r rdrcra) StringStartzLMatches if current position is at the beginning of the parse string ctd|_dS)NzExpected start of textrLrrrrNr/r0r rzStringStart.__init__TcCs0|dkr|||dkrt|||j||gfSr)rrrr r/r/r0r! szStringStart.parseImplr(rcr/r/rNr0r   r cra)rczG Matches if current position is at the end of the parse string cr )NzExpected end of textr rrNr/r0r rzStringEnd.__init__TcCsX|t|krt|||j||t|kr|dgfS|t|kr$|gfSt|||j|rrr r/r/r0r! s    zStringEnd.parseImplr(rcr/r/rNr0rc r rcc>eZdZdZefeddedeffddZd dd ZZS) WordStartaMatches if the current position is at the beginning of a :class:`Word`, and is not preceded by any character in a given set of ``word_chars`` (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.  wordChars word_charsrcs.|tkr|n|}tt||_d|_dS)NzNot at the start of a word) printablesrLrrrrrrrrNr/r0r s   zWordStart.__init__TcCs@|dkr||d|jvs|||jvrt|||j||gfSNrr)rrrr r/r/r0r! s zWordStart.parseImplr( r3r4r5r6rrnrr!rZr/r/rNr0r s rcr ) WordEndaiMatches if the current position is at the end of a :class:`Word`, and is not followed by any character in a given set of ``word_chars`` (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. rrrcs4|tkr|n|}tt||_d|_d|_dS)NFzNot at the end of a word)rrLrrrrrrrNr/r0r s    zWordEnd.__init__TcCsPt|}|dkr$||kr$|||jvs||d|jvr$t|||j||gfSr)rrrr)rrrrrr/r/r0r! s zWordEnd.parseImplr(rr/r/rNr0r s rcseZdZdZddeedeffdd Zdeefdd Z defd d Z d d edeffdd Z d d edeffdd Z deffdd Z ddZdeffdd Zd!d"ddZdeffdd Zdfdd Ze Ze ZZS)#ParseExpressionz]Abstract subclass of ParserElement, for combining and post-processing parsed tokens. Fexprsrcst|t|trt|}t|tr|g_n@t|tr(|g_n6t|t rIt|}t dd|DrCfdd|D}t|_nzt|_Wn t y]|g_Ynwd_ dS)Ncss|]}t|tVqdSrE)r,r$)r-rr/r/r0r rz+ParseExpression.__init__..c3s(|]}t|tr|n|VqdSrE)r,r$rr-rrr/r0r s  F) rLrr,_generatorTyperr$rrrsranyrrrrrrNrr0r s*           zParseExpression.__init__rDcCs|jddSrE)rrr/r/r0rrzParseExpression.recursecCs|j|d|_|SrE)rrrrr/r/r0rs zParseExpression.appendTrc<t||rdd|jD|_|jD]}||q|S)z Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on all contained expressions. cSg|]}|qSr/rrr/r/r0r1(r z4ParseExpression.leave_whitespace..)rLrrrrrrNr/r0r s   z ParseExpression.leave_whitespacecr)z Extends ``ignore_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on all contained expressions. cSrr/rrr/r/r0r14r z5ParseExpression.ignore_whitespace..)rLrrr rNr/r0r-s   z!ParseExpression.ignore_whitespacecslt|tr ||jvrt||jD] }||jdq|St||jD] }||jdq)|SNr)r,rrrLrr)rrrrNr/r0r9     zParseExpression.ignorecCd|jjt|jSNz{}:({}))rrr3rnrrr/r/r0rErz$ParseExpression._generateDefaultNamecs&|jr|St|jD]}|q t|jdkr|jd}t||jrR|jsR|jdurR|j sR|jdd|jdg|_d|_ |j |j O_ |j |j O_ |jd}t||jr|js|jdur|j s|jdd|jdd|_d|_ |j |j O_ |j |j O_ dt ||_|S)NrVrrrr)rrLr`rrr,rrrrrrrrnr)rrrrNr/r0r`Hs@         zParseExpression.streamlineNcCsB|dur|ngdd|g}|jD]}||q|gdSrE)rrr)rrtmprr/r/r0rqs  zParseExpression.validatecs t}dd|jD|_|S)NcSrr/rrr/r/r0r1yr z(ParseExpression.copy..)rLrrrrrNr/r0rws zParseExpression.copycsjtjr.tj|jvr.|jD]!}t|tr-|jr-tj|jvr-tj d d|t |j |jddq t ||SNzY{}: setting results name {!r} on {} expression collides with {!r} on contained expressionrLrW stacklevel)r=rLrUrrr,rsrwarningsr@rrr3rLrrrBrrrNr/r0r|s2  zParseExpression._setResultsNamer'r(rErJ)r3r4r5r6 IterableTypersrirrrrrrrrr`rrrrJrKrZr/r/rNr0r s    ) rcsteZdZdZGdddeZddeedeffdd Z d effd d Z dd d Z ddZ ddZ ddZZS)ra 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") cs$eZdZfddZddZZS)zAnd._ErrorStopcstj|i||dSrE)rLrr)rrrrNr/r0rs zAnd._ErrorStop.__init__cCr)N-r/rr/r/r0rr&z#And._ErrorStop._generateDefaultName)r3r4r5rrrZr/r/rNr0rs rT exprs_argrcs t|}|rFt|vrFg}t|D]/\}}|tur:|t|dkr6t||djd}|t|dqtd||q||dd<t |||jr~t dd|jD|_ t |jdtsz|j|jdj|jdjd|jdj|_nd |_nd |_ d |_dS) Nrrrz0cannot construct And with sequence ending in ...cs|]}|jVqdSrErrr/r/r0rzAnd.__init__..rrFT)rrrrrbrrrr+rLrrrr,rrrrrr)rr.rrr%rfr skipto_argrNr/r0rs2      z And.__init__rDcsH|jrStdd|jddDrSt|jddD]/\}}|dur#qt|trI|jrIt|jdtrI|jd|j|d|jd<d|j|d<qdd|jD|_tt|j|jddD]3\}}t }|rt ||vrsn#| t |t|t r| |fddn |}tt|d}|slqctd d|jD|_|S) Ncss0|]}t|to|jot|jdtVqdSrN)r,rrrrr/r/r0rs  z!And.streamline..rrcSsg|]}|dur|qSrEr/rr/r/r0r1z"And.streamline..cSst|dt||S)N parent_anchor)setattrr)r{r|r}cur_r/r/r0rsz And.streamline..csr/rEr0rr/r/r0rr1)rrrr,rrrLr`rrradd IndentedBlockrrnextrrr)rrfrprevcurseensubsrNr/r0r`sF      zAnd.streamlinec Cs|jdj|||dd\}}d}|jddD]X}t|tjur#d}q|r\z ||||\}}Wn4ty8tyK}zd|_t|d}~wt y[t|t ||j |w||||\}}|sk| ro||7}q||fS)NrFrjrT) rrrrrParseSyntaxExceptionrCr_from_exceptionr*rrhaskeys) rrrr resultlist errorStopr exprtokensrIr/r/r0r!s6      z And.parseImplcCt|tr ||}||SrEr,r$rrrr/r/r0__iadd__   z And.__iadd__cCs8|dd|g}|jD] }|||jsdSq dSrE)rrrrr/r/r0r!s  zAnd._checkRecursioncCszddd|jD}t|dkr7|ddt|ddkr7|dd}t|dkr7|ddt|ddksd|d S) NrcsrrErzrr/r/r0r)r z+And._generateDefaultName..rr{}r{})r|rrrinnerr/r/r0r(s & & zAnd._generateDefaultNamer()r3r4r5r6rbrr,rsrirr`r!rGrrrZr/r/rNr0rs +rcjeZdZdZddeedeffdd Zdeffdd Zdd d Z d dZ ddZ dfdd Z Z S)raRequires 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.search_string("123 3.1416 789")) prints:: [['123'], ['3.1416'], ['789']] FrrcNt|||jr"tdd|jD|_tdd|jD|_dSd|_dS)Ncsr/rEr0rr/r/r0rEr1zOr.__init__..csr/rErrr/r/r0rFr1TrLrrrrrrrrNr/r0rB  z Or.__init__rDcs`t|jr+tdd|jD|_tdd|jD|_tdd|jD|_|Sd|_|S)Ncsr/rEr0rr/r/r0rMr1z Or.streamline..csr/rErrr/r/r0rNr1cs"|] }|jo t|t VqdSrErr,rrr/r/r0rO F)rLr`rrrrrrrrNr/r0r`Js  z Or.streamlineTc Csxd}d}g}g}tdd|jDr|||}|jD]q}z |j||dd} Wn]tyH} zd| _|| _|| d}d}WYd} ~ qd} ~ wtyh} z|s^d| _| j |kr^| }| j }WYd} ~ qd} ~ wt yt ||krt|t ||j |}t |}Yqw|| |fq|r|j tddd|s|dd} | |||Sd } |D]M\}}|| dkr| Sz ||||\} }Wnty} zd| _| j |kr| }| j }WYd} ~ qd} ~ ww| |kr| |fS| | dkr| |f} q| d kr| S|r*t |dkr$|j d d d |dj |dj kr$|j d d d |d}||dur5|j |_|t||d|)Nrcsr/rE)rrr/r/r0r[r1zOr.parseImpl..Tr9r)rreverserr3cS|j SrErrr/r/r0rrzOr.parseImpl..rcS|j tt|j fSrErrrn parserElementrZr/r/r0rr4 no defined alternatives to match)rrrr;rrr^rrrr*rrsortrrr)rrrr maxExcLoc maxExceptionrrfatalsrloc2pfer5 best_exprlongestloc1expr1r max_fatalr/r/r0r!Vs             z Or.parseImplcCrErErFrr/r/r0__ixor__rHz Or.__ixor__cCdddd|jDdS)NrJz ^ csrrErzrr/r/r0rr z*Or._generateDefaultName..rKr|rrr/r/r0rzOr._generateDefaultNamecRtjr"tj|jvr"tdd|jDr"tjdd|t |j ddt ||S)Ncs&|]}t|totj|jvVqdSrEr,rrUrKrrr/r/r0r  z%Or._setResultsName..{}: setting results name {!r} on {} expression will return a list of all parsed tokens in an And alternative, in prior versions only the first token was returned; enclose contained argument in GrouprKrWr( r=rKrUrrrr*r@rrr3rLrrrBrrNr/r0r$ zOr._setResultsNamer'r()r3r4r5r6r,rsrirr`r!rkrrrZr/r/rNr0r0s RrcrN)raRequires that at least one :class:`ParseExpression` is found. If more than one expression matches, 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.search_string("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']] # put more selective expression first number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums) print(number.search_string("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']] FrrcrO)Ncsr/rEr0rr/r/r0rr1z&MatchFirst.__init__..csr/rErrr/r/r0rr1TrPrrNr/r0rrQzMatchFirst.__init__rDcsp|jr|St|jr0tdd|jD|_tdd|jD|_tdd|jD|_|Sd|_d|_|S)Ncsr/rErRrr/r/r0rr1z(MatchFirst.streamline..csr/rEr0rr/r/r0rr1csrSrErTrr/r/r0rrUFT) rrLr`rrrrrrrrNr/r0r`s  zMatchFirst.streamlineTc Csd}d}|jD]V}z ||||WSty&}zd|_||_d}~wtyA}z|j|kr7|}|j}WYd}~qd}~wty]t||kr[t|t||j |}t|}Yqw|durh|j |_ |t||d|)Nrr_) rrrrr^rrr*rrr) rrrrrarbrrer5r/r/r0r!sB     zMatchFirst.parseImplcCrErErFrr/r/r0__ior__rHzMatchFirst.__ior__cCrl)NrJz | csrrErzrr/r/r0rr z2MatchFirst._generateDefaultName..rKrmrr/r/r0rrnzMatchFirst._generateDefaultNamecro)NcsrprErqrr/r/r0r%rrz-MatchFirst._setResultsName..rsrKrWr(rtrurNr/r0rrvzMatchFirst._setResultsNamer'r()r3r4r5r6r,rsrirr`r!rwrrrZr/r/rNr0rs "rcsTeZdZdZddeedeffdd Zdeffdd Zdd d Z d d Z Z S)ralRequires 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 = one_of("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN") shape_type = one_of("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 & Opt(color_attr) & Opt(size_attr) shape_spec.run_tests(''' 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 TrrcsHt|||jrtdd|jD|_nd|_d|_d|_d|_dS)Ncsr/rEr0rr/r/r0rwr1z Each.__init__..T)rLrrrrrinitExprGroupsrrrNr/r0rts z Each.__init__rDcs4t|jrtdd|jD|_|Sd|_|S)Ncsr/rEr0rr/r/r0rr1z"Each.streamline..T)rLr`rrrrrNr/r0r`~s zEach.streamlinec s|jrItdd|jD|_dd|jD}dd|jD}|||_dd|jD|_dd|jD|_dd|jD|_|j|j7_d |_|}|jdd}|jdd|jdd}g} d } g} g} | r||} | | | D][}z |j ||d d }Wn/t y}zd|_ ||_ | || |WYd}~qzd}~wty| |Yqzw| |jt||||vr||qz|vrՈ|qzt| t| krd } | sj| r t| d kr| jd dd| dj| d jkr| jddd| d}||r#ddd|D}t||d|| fdd|jD7} tg}| D]}||||\}}||7}q5||fS)Ncss(|]}t|trt|j|fVqdSrE)r,rrrrr/r/r0rs    z!Each.parseImpl..cSsg|] }t|tr|jqSr/r,rrrr/r/r0r1z"Each.parseImpl..cSs&g|]}|jrt|tttfs|qSr/)rr,rrrrr/r/r0r1scS(g|]}t|tr|jj|jddqST)r)r,_MultipleMatchrrrrr/r/r0r1 cSr{r|)r,rrrrrr/r/r0r1r~cSs g|] }t|tttfs|qSr/)r,rrrrr/r/r0r1s FTrVrcSrXrErYrZr/r/r0rrz Each.parseImpl..r[rcSr\rEr]rZr/r/r0rr4z, cSr r/rzrr/r/r0r1r z*Missing one or more required elements ({})cs$g|]}t|tr|jvr|qSr/ryrtmpOptr/r0r1s$)rxdictropt1map optionalsmultioptionals multirequiredrequiredrMr;rrr^rrrrremoverr`rr|rr!r)rrrropt1opt2tmpLoctmpReqdmultis matchOrder keepMatchingfailedrctmpExprsrrerjmissing total_resultsrr/rr0r!s        zEach.parseImplcCrl)NrJz & csrrErzrr/r/r0rr z,Each._generateDefaultName..rKrmrr/r/r0rrnzEach._generateDefaultNamer() r3r4r5r6r,rsrirr`r!rrZr/r/rNr0r:s 9 WrcseZdZdZddeeefdeffdd Zde efdd Z dd d Z dd edeffdd Z dd edeffdd Z deffdd Zdeffdd ZddZdd ddZddZe Ze ZZS)!ParseElementEnhancezfAbstract subclass of :class:`ParserElement`, for combining and post-processing parsed tokens. Frrcst|t|tr+t|jtr||}ntt||jr$t|}n|t|}||_ |durX|j |_ |j |_ |j |j |jd|j|_|j|_|j|_|j|jdSdS)Nr)rLrr,r$ issubclassrr[rrrrrrrrrrrrr{rrrrNr/r0rs&     zParseElementEnhance.__init__rDcCs|jdur |jgSgSrErrr/r/r0rrzParseElementEnhance.recurseTcCs,|jdur|jj|||ddSt||d|)NFrjzNo expression defined)rrrr r/r/r0r!s zParseElementEnhance.parseImplrc6t||r|j|_|jdur|j||SrE)rLrrrrrNr/r0r    z$ParseElementEnhance.leave_whitespacecrrE)rLrrrrrNr/r0r rz%ParseElementEnhance.ignore_whitespacecslt|tr ||jvrt||jdur|j|jd|St||jdur4|j|jd|Sr!)r,rrrLrrrrNr/r0rr"zParseElementEnhance.ignorecs"t|jdur|j|SrE)rLr`rrrNr/r0r`"s   zParseElementEnhance.streamlinecCsF||vr t||g|dd|g}|jdur!|j|dSdSrE)RecursiveGrammarExceptionrr)rrrr/r/r0r(s  z#ParseElementEnhance._checkRecursionNcCsB|durg}|dd|g}|jdur|j||gdSrErrrrrr%r/r/r0r/s   zParseElementEnhance.validatecCr#r$)rrr3rnrrr/r/r0r7rz(ParseElementEnhance._generateDefaultNamer'r(rErJ)r3r4r5r6rrsrnrirrrr!rrrr`rrrrJrKrZr/r/rNr0rs       rcs`eZdZdZGdddeZGdddeZdddd ed ed effd d Z dddZ Z S)r9z Expression to match one or more expressions at a given indentation level. Useful for parsing text where structure is implied by indentation (like Python source code). c"eZdZdeffdd ZZS)zIndentedBlock._Indentref_colc,td|_|fdddS)Nzexpected indent at column {}cst||kSrErrzrr/r0rHz0IndentedBlock._Indent.__init__..rLrrrrrrrNrr0rE  zIndentedBlock._Indent.__init__r3r4r5rrrZr/r/rNr0_IndentDrcr)zIndentedBlock._IndentGreaterrcr)Nz)expected indent at column greater than {}cst||kSrErrzrr/r0rNrz7IndentedBlock._IndentGreater.__init__..rrrNrr0rKrz%IndentedBlock._IndentGreater.__init__rr/r/rNr0_IndentGreaterJrrFTrgroupedrrrcs&tj|dd||_||_d|_dS)NTr\r)rLr _recursive_groupedr5)rrrrrNr/r0rPs zIndentedBlock.__init__c Cst||}|j|||t||}||}t||j}|jrD||}t|j|j|j d} | |j || _ |t || 7}|dtt|ddd|t|} ||j tB} |j rlt} ndd} | | t| |||S)Nrzinner @cS|SrEr/rr/r/r0rxrz)IndentedBlock.parseImpl..)rbrrr;rrrrr9rrrr5rrhexrryrrcGrouprr!) rrrr anchor_loc indent_colpeer_detect_expr inner_expr sub_indent nested_blockblocktrailing_undentrr/r/r0r!Zs,     *zIndentedBlock.parseImplr() r3r4r5r6rbrrrsrirr!rZr/r/rNr0r9>s r9c<eZdZdZdeeefffdd Zdfdd ZZ S) AtStringStartzMatches if expression matches at the beginning of the parse string:: AtStringStart(Word(nums)).parse_string("123") # prints ["123"] AtStringStart(Word(nums)).parse_string(" 123") # raises ParseException rct|d|_dSNFrLrrrrrNr/r0r  zAtStringStart.__init__Tcs$|dkr t||dt|||S)Nrznot found at string start)rrLr!r rNr/r0r!s zAtStringStart.parseImplr( r3r4r5r6rrsrnrr!rZr/r/rNr0r~s rcr) AtLineStartaMatches if an expression matches 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 (AtLineStart('AAA') + restOfLine).search_string(test): print(t) prints:: ['AAA', ' this line'] ['AAA', ' and this line'] rcrrrrrNr/r0rrzAtLineStart.__init__Tcs*t||dkr t||dt|||S)Nrznot found at line start)rrrLr!r rNr/r0r!s zAtLineStart.parseImplr(rr/r/rNr0rsrcs8eZdZdZdeeefffdd ZdddZZ S) FollowedByafLookahead 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, stop_on=label).set_parse_action(' '.join)) OneOrMore(attr_expr).parse_string("shape: SQUARE color: BLACK posn: upper left").pprint() prints:: [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']] rcrrrLrrrrNr/r0rrzFollowedBy.__init__TcCs(|jj|||d\}}|dd=||fS)Nr:)rr)rrrrr)rr/r/r0r!s zFollowedBy.parseImplr(rr/r/rNr0rsrcsDeZdZdZ d deeefdeeffdd Z d d d Z Z S) PrecededByaLookbehind 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, :class:`Literal`, :class:`Keyword`, or a :class:`Word` or :class:`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 Nrretreatcst|||_d|_d|_d|_t|tr#t |}d|_n+t|t t fr1|j }d|_nt|t tfrD|jtkrD|j}d|_n t|trNd}d|_||_dt||_d|_|jdddS)NTFrznot preceded by cSs|tddSrE) __delitem__slicerzr/r/r0r sz%PrecededBy.__init__..)rLrrrrrrr,r$rrrsrirrrr/rrrnrrrr)rrrrNr/r0rs*   zPrecededBy.__init__rTc Cs|jr!||jkrt|||j||j}|j||\}}||fS|jt}|td||j|}t|||j} tdt ||jddD])} z||t || \}}Wnt yk} z| } WYd} ~ qGd} ~ ww||fS| r) rrrrrrrcrrrmrrC) rrrrrkr)r test_exprinstring_slice last_exproffsetpber/r/r0r!s*     zPrecededBy.parseImplrE)rT) r3r4r5r6rrsrnrrrr!rZr/r/rNr0rs rc@seZdZdZdddZdS)Locateda Decorates 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.parse_with_tabs` Example:: wd = Word(alphas) for match in Located(wd).search_string("ljsdf123lksdjjf123lkkjj1222"): print(match) prints:: [0, ['ljsdf'], 5] [8, ['lksdjjf'], 15] [18, ['lkkjj'], 23] TcCsZ|}|jj|||dd\}}t|||g}||d<||d<||d<|jr)||gfS||fS)NFrj locn_startrHlocn_end)rrr!r)rrrrrkr4r6r/r/r0r!Es zLocated.parseImplNr()r3r4r5r6r!r/r/r/r0r)srcs@eZdZdZdeeefffdd Zd ddZdd Z Z S) ra Lookahead to disallow matching with the given parse expression. ``NotAny`` does *not* advance the parsing position within the input string, it only verifies that the specified parse expression does *not* match at the current position. Also, ``NotAny`` does *not* skip over leading whitespace. ``NotAny`` always returns a null token list. May be constructed using the ``'~'`` operator. Example:: AND, OR, NOT = map(CaselessKeyword, "AND OR NOT".split()) # take care not to mistake keywords for identifiers ident = ~(AND | OR | NOT) + Word(alphas) boolean_term = Opt(NOT) + ident # very crude boolean expression - to support parenthesis groups and # operation hierarchy, use infix_notation boolean_expr = boolean_term + ZeroOrMore((AND | OR) + boolean_term) # integers that are followed by "." are actually floats integer = Word(nums) + ~Char(".") rcs,t|d|_d|_dt|j|_dS)NFTzFound unwanted token, )rLrrrrnrrrrNr/r0rls zNotAny.__init__TcCs&|j||rt|||j||gfSrE)rr<rrr r/r/r0r!uszNotAny.parseImplcCdt|jdS)Nz~{rKrnrrr/r/r0rzr^zNotAny._generateDefaultNamer() r3r4r5r6rrsrnrr!rrZr/r/rNr0rSs  rc sreZdZ ddddedeeeefdeeeefffddZdefd d Zdd d Z dfdd Z Z S)r}NstopOnrstop_onrcs@t||p |}d|_|}t|tr||}||dSr)rLrrr,r$rr)rrrrenderrNr/r0rs   z_MultipleMatch.__init__rDcCs2t|tr ||}|dur||_|Sd|_|SrE)r,r$r not_ender)rrr/r/r0rs  z_MultipleMatch.stopOnTc Cs|jj}|j}|jdu}|r|jj}|r|||||||\}}z*|j } |r/|||| r7|||} n|} ||| |\}} | sG| rK|| 7}q(ttfyYY||fSwrE) rrrrr:rrArr*) rrrrself_expr_parseself_skip_ignorables check_ender try_not_enderr4hasIgnoreExprsrs tmptokensr/r/r0r!s0       z_MultipleMatch.parseImplFcsvtjr4tj|jvr4|jg|jD]!}t|tr3|jr3tj|jvr3t j d d|t |j |jddqt||Sr')r=rLrUrrrr,rsrr*r@rrr3rLrr+rNr/r0rs2 z_MultipleMatch._setResultsNamerEr(r') r3r4r5rsrrrnrrr!rrZr/r/rNr0r}~s r}c@seZdZdZddZdS)rau Repetition of one or more of the given expression. Parameters: - expr - expression that must match one or more times - stop_on - (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).set_parse_action(' '.join)) text = "shape: SQUARE posn: upper left color: BLACK" OneOrMore(attr_expr).parse_string(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']] # use stop_on attribute for OneOrMore to avoid reading label string as part of the data attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)) OneOrMore(attr_expr).parse_string(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] # could also be written as (attr_expr * (1,)).parse_string(text).pprint() cCr)NrJz}...rrr/r/r0rr^zOneOrMore._generateDefaultNameN)r3r4r5r6rr/r/r/r0rs rc sfeZdZdZ ddddedeeeefdeeeefffddZdfd d Z d d Z Z S)rao Optional repetition of zero or more of the given expression. Parameters: - ``expr`` - expression that must match zero or more times - ``stop_on`` - expression for a terminating sentinel (only required if the sentinel would ordinarily match the repetition expression) - (default= ``None``) Example: similar to :class:`OneOrMore` Nrrrrcstj||p|dd|_dS)NrTr)rrrrrNr/r0rs zZeroOrMore.__init__Tc s<z t|||WSttfy|tg|jdfYSw)Nr)rLr!rr*r!rr rNr/r0r!s zZeroOrMore.parseImplcCr)N[z]...rrr/r/r0rr^zZeroOrMore._generateDefaultNamerEr() r3r4r5r6rsrrrnrr!rrZr/r/rNr0rs rc@seZdZddZddZdS) _NullTokencCrrr/rr/r/r0__bool__ r&z_NullToken.__bool__cCr)Nrhr/rr/r/r0rr&z_NullToken.__str__N)r3r4r5rrr/r/r/r0r s rcsNeZdZdZeZefdeeefde ffdd Z d ddZ d d Z Z S) raN Optional 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) + Opt('-' + Word(nums, exact=4))) zip.run_tests(''' # 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) rdefaultcs*tj|dd|jj|_||_d|_dS)NFr\T)rLrrr defaultValuer)rrrrNr/r0r=s  z Opt.__init__Tc Cs|j}z|j|||dd\}}W||fSttfyG|j}||jur6|jr2t|g}|||j<n|g}ng}Y||fSY||fSY||fSw)NFrj)rrrr*r_Opt__optionalNotMatchedrr!)rrrr self_exprr4 default_valuer/r/r0r!Es$    z Opt.parseImplcCsnt|j}t|dkr1|ddt|ddkr1|dd}t|dkr1|ddt|ddksd|dS)NrrrIrr])rnrrrLr/r/r0rUs & & zOpt._generateDefaultNamer()r3r4r5r6rrrrsrnrrr!rrZr/r/rNr0rs&  rcsjeZdZdZ   ddddeeefdededeeeefd eeeff fd d Z dd dZ Z S)ra 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`` - if ``True``, the target expression is also parsed (the skipped text and target expression are returned as a 2-element list) (default= ``False``). - ``ignore`` - (default= ``None``) used to define grammars (typically quoted strings and comments) that might contain false matches to the target expression - ``fail_on`` - (default= ``None``) define expressions that are not allowed to be included in the skipped test; if found before the target expression is found, the :class:`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=quoted_string) string_data.set_parse_action(token_map(str.strip)) ticket_expr = (integer("issue_num") + SEP + string_data("sev") + SEP + string_data("desc") + SEP + integer("days_open")) for tkt in ticket_expr.search_string(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 FN)failOnrincluderfail_onrcsdt||p |}||_d|_d|_||_d|_t|tr%| ||_ n||_ dt |j |_ dS)NTFzNo match found for )rLr ignoreExprrr includeMatchrr,r$rrrnrr)rrrrrrrNr/r0rs  zSkipTo.__init__Tc Cs|}t|}|jj}|jdur|jjnd}|jdur|jjnd}|} | |krf|dur0||| r0n>|durG z||| } Wn tyEYnwq5z ||| dddWntt fy`| d7} Ynwn | |ks&t|||j || }|||} t | } |j r||||dd\}} | | 7} || fS)NrF)rrrj) rrrrr;rr:rCrr*rr!r) rrrrrrrself_failOn_canParseNextself_ignoreExpr_tryParsetmplocskiptext skipresultrr/r/r0r!sF    zSkipTo.parseImpl)FNNr() r3r4r5r6rrsrnrirrr!rZr/r/rNr0r`s&?  rcseZdZdZd"deeeefffdd ZddZ dd Z fd d Z d d Z d#fdd Z d#dedefddZd#dedefddZdefddZd"d$ddZddZdeffdd Zd%fd d! ZeZeZZS)&r=aw 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:: fwd_expr << a | b | c will actually be evaluated as:: (fwd_expr << 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``:: fwd_expr << (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``. Nrcs,tjddd|_tj|ddd|_dS)NrVrrFr\)rr caller_framerLr lshift_linerrNr/r0rs zForward.__init__cCst|dr|`t|tr||}||_|jj|_|jj|_|j|jj |jj d|jj |_ |jj |_ |j |jj tjddd|_|S)NrrrVr)rrr,r$rrrrrrrrrrr{rrrrr/r/r0 __lshift__s        zForward.__lshift__cCs||>SrEr/rr/r/r0 __ilshift__r"zForward.__ilshift__csJtjddd}tjr||jkrtj|jvrtjdddt |}|S)NrVrrzr,r+rKeyErrorr)rrrr parse_fnsrrffrmr)memoprev_loc prev_resultact_keypeek_key prev_peeknew_locnew_peekrrNr/r0r!9s           %)zForward.parseImplrrDcCrrrrr/r/r0rzForward.leave_whitespacecCrrrrr/r/r0rrzForward.ignore_whitespacecCs$|jsd|_|jdur|j|Sr)rrr`rr/r/r0r`s   zForward.streamlinecCsJ|durg}||vr|dd|g}|jdur|j||gdSrErrr/r/r0rs  zForward.validatecCsnd|_d}z#|jdurt|jdd}n d}W|jjd|SW|jjd|S|jjd|YS)Nz: ...rPiNonez: )rrrnrr3)r retStringr/r/r0rs ,zForward._generateDefaultNamecs&|jdur tSt}||K}|SrE)rrLrr=r&rNr/r0rs  z Forward.copyFcsHtjrtj|jvr|jdurtjdd|t|j ddt ||S)NzO{}: setting results name {!r} on {} expression that has no contained expressionrMrWr() r=rMrUrrr*r@rrr3rLr)rrBrrNr/r0rs  zForward._setResultsNamerEr(rJr')r3r4r5r6rrrsrnrrrrrr!rirrr`rrrrrJrKrZr/r/rNr0r=s"  _   r=cs0eZdZdZddeeefffdd ZZS)TokenConverterzW Abstract subclass of :class:`ParseExpression`, for converting parsed results. Frcrr)rLrrrrNr/r0rrzTokenConverter.__init__r') r3r4r5r6rrsrnrrZr/r/rNr0r s$r c s\eZdZdZ  ddddededed eeffd d Zd effd d Z ddZ Z S)CombineaConverter 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.parse_string('3.1416')) # -> ['3', '.', '1416'] # will also erroneously match the following print(real.parse_string('3. 1416')) # -> ['3', '.', '1416'] real = Combine(Word(nums) + '.' + Word(nums)) print(real.parse_string('3.1416')) # -> ['3.1416'] # no match when there are internal spaces print(real.parse_string('3. 1416')) # -> Exception: Expected W:(0123...) rhTN) joinStringr join_stringadjacentr csDt||dur |n|}|r|||_d|_||_d|_dSr)rLrrrrr r)rrrrr rNr/r0rs  zCombine.__init__rDcs&|jr t|||St||SrE)rrsrrLrrNr/r0r s   zCombine.ignorecCsL|}|dd=|td||jg|jd7}|jr$|r$|gS|S)Nrh)r))rr!r| _asStringListr rrrA)rrrr$retToksr/r/r0r%s zCombine.postParse)rhT) r3r4r5r6rsrnrirrrr%rZr/r/rNr0r s"r c4eZdZdZd dedeffdd ZddZZS) raConverter to return the matched tokens as a list - useful for returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions. The optional ``aslist`` argument when set to True will return the parsed tokens as a Python list instead of a pyparsing ParseResults. Example:: ident = Word(alphas) num = Word(nums) term = ident | num func = ident + Opt(delimited_list(term)) print(func.parse_string("fn a, b, 100")) # -> ['fn', 'a', 'b', '100'] func = ident + Group(Opt(delimited_list(term))) print(func.parse_string("fn a, b, 100")) # -> ['fn', ['a', 'b', '100']] Fraslistct|d|_||_dSr)rLrr _asPythonList)rrrrNr/r0r4  zGroup.__init__cCs.|jrtt|tr|St|S|gSrE)rr!r r,r(rr#r/r/r0r%9szGroup.postParser' r3r4r5r6rsrirr%rZr/r/rNr0rsrcr) r asConverter 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. The optional ``asdict`` argument when set to True will return the parsed tokens as a Python dict instead of a pyparsing ParseResults. Example:: data_word = Word(alphas) label = data_word + FollowedBy(':') text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)) # print attributes as plain groups print(OneOrMore(attr_expr).parse_string(text).dump()) # instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names result = Dict(OneOrMore(Group(attr_expr))).parse_string(text) print(result.dump()) # access named fields as dict entries, or output as dict print(result['shape']) print(result.as_dict()) 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. Frasdictcrr)rLrr _asPythonDict)rrrrNr/r0rnrz Dict.__init__c Cs&t|D]w\}}t|dkrq|d}t|trt|}t|dkr,td|||<qt|dkrCt|dtsCt|d|||<qz|}Wnt yWt d}|dw|d=t|dksjt|trr| rrt||||<qt|d|||<q|j r|j r|gS|S|j r|gS|S)NrrrhrVzdcould not extract dict values from parsed results - Dict expression must contain Grouped expressions)rrr,rrnrr"r!rr+rrArras_dict) rrrr$rftokikey dictvaluerr/r/r0r%ss:       zDict.postParser'rr/r/rNr0r Ds)r csbeZdZdZddeeefdeffdd ZfddZ fd d Z d d Z d efddZ Z S)raConverter 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.parse_string(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.parse_string(source)) # Skipped text (using '...') can be suppressed as well source = "lead in START relevant text END trailing text" start_marker = Keyword("START") end_marker = Keyword("END") find_body = Suppress(...) + start_marker + ... + end_marker print(find_body.parse_string(source) prints:: ['a', ',', 'b', ',', 'c', ',', 'd'] ['a', 'b', 'c', 'd'] ['START', 'relevant text ', 'END'] (See also :class:`delimited_list`.) Frrcs"|dur tt}t|dS)N.)rrbrLrrrNr/r0rs zSuppress.__init__cs(t|jtrtt||St|SrE)r,rrrrrLrrrNr/r0r  zSuppress.__add__cs(t|jtrtt||St|SrE)r,rrrrrLrrrNr/r0rrzSuppress.__sub__cCrrEr/r#r/r/r0r%r&zSuppress.postParserDcCrrEr/rr/r/r0rr&zSuppress.suppressr')r3r4r5r6rrsrnrirrrr%rrZr/r/rNr0rs   rrcs tfdd}j|_|S)avDecorator 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) @trace_parse_action def remove_duplicate_chars(tokens): return ''.join(sorted(set(''.join(tokens)))) wds = OneOrMore(wd).set_parse_action(remove_duplicate_chars) print(wds.parse_string("slkdjs sld sldd sdlf sdljf")) prints:: >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {})) <>entering {}(line: {!r}, {}, {!r}) z<.z)rr3)rr%r/r$r0trace_parse_actions r&empty line_startline_end string_start string_endz\[]-*.$+^?()~ )rcCs |ddSrr/rzr/r/r0r s rz\\0?[xX][0-9a-fA-F]+cCstt|dddS)Nrz\0xr)chrrrrzr/r/r0r r4z \\0[0-7]+cCstt|ddddS)Nrr)r,rrzr/r/r0rr2z\]r-r^negatebodyrr{cs@ddzdfddt|jDWStyYdSw)a Helper to easily define string ranges for use in :class:`Word` construction. Borrows syntax from regexp ``'[]'`` string range definitions:: srange("[0-9]") -> "0123456789" srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" The input string must be enclosed in []'s, and the returned string is the expanded character set joined into a single string. The values enclosed in the []'s may be: - a single character - an escaped character with a leading backslash (such as ``\-`` or ``\]``) - an escaped hex character with a leading ``'\x'`` (``\x21``, which is a ``'!'`` character) (``\0x##`` is also supported for backwards compatibility) - an escaped octal character with a leading ``'\0'`` (``\041``, which is a ``'!'`` character) - a range of any of the above, separated by a dash (``'a-z'``, etc.) - any combination of the above (``'aeiouy'``, ``'a-zA-Z0-9_$'``, etc.) cSs<t|ts|Sdddtt|dt|ddDS)NrhcsrrE)r,rxr/r/r0r:r z+srange....rr)r,r!r|rord)pr/r/r0r8s.zsrange..rhc3s|]}|VqdSrEr/)r-part _expandedr/r0r=r zsrange..)r|_reBracketExprrfr0r+)r{r/r4r0sranges" r7cs,fdd}tdtdj}||_|S)agHelper to define a parse action by mapping a function to all elements of a :class:`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).set_parse_action(token_map(int, 16))``, which will convert the parsed data to an integer using base 16. Example (compare the last to example in :class:`ParserElement.transform_string`:: hex_ints = OneOrMore(Word(hexnums)).set_parse_action(token_map(int, 16)) hex_ints.run_tests(''' 00 11 22 aa FF 0a 0d 1a ''') upperword = Word(alphas).set_parse_action(token_map(str.upper)) OneOrMore(upperword).run_tests(''' my kingdom for a horse ''') wd = Word(alphas).set_parse_action(token_map(str.title)) OneOrMore(wd).set_parse_action(' '.join).run_tests(''' 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'] csfdd|DS)Ncsg|] }|gRqSr/r/)r-toknrr~r/r0r1hrzz)token_map..pa..r/rzr9r/r0rgrztoken_map..par3r)rr3)r~rrrr/r9r0 token_mapBs%r:cCs8tjjD]\}}t|tr|js||qdS)zy Utility to simplify mass-naming of parser elements, for generating railroad diagram with named subdiagrams. N) r  _getframef_backf_localsrr,rsrr)rBvarr/r/r0autoname_elementsps  r?z4"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*"z string enclosed in double quotesz4'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*'z string enclosed in single quotesz*quotedString using single or double quotesuzunicode string literalz#[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]z[\0xa1-\0xbf\0xd7\0xf7]cCsg|] }t|tr|qSr/)r,rs)r-rr/r/r0r1r2rJ)rVrr')osrrrrr,rrrrrr r r r r r.rabcrrenumrrvrr*rrr collections.abcrtypesoperatorr functoolsr threadingrpathlibrutilrrrrrrrrrXrrW exceptionsactionsrr!r"unicoder#maxsizer/rnbytesr$rrr%r=rUr_rbrIrirq warnoptionsenvironrsumrrrrrrrrrmrr GeneratorTyperrr*r+r+r,rrrascii_uppercaseascii_lowercasealphasLatin1 identcharsidentbodycharsnumshexnumsr}r| printablerrrrrrrrrsrr[rbrbrrkrrsrrrrrrrrrrrrrrr rcrrrrrrrrr9rrrrrrr}rrrrrr=r r rrr&rr'r(r)r*r+r _escapedPunc_escapedHexChar_escapedOctChar _singleChar _charRangerr6r7r:r?dbl_quoted_stringsgl_quoted_stringr unicode_string alphas8bitpunc8bitrvaluesrtokenMapconditionAsParseActionnullDebugActionsglQuotedStringdblQuotedString quotedString unicodeString lineStartlineEnd stringStart stringEndtraceParseActionr/r/r/r0s <      ,  !        ?    ))  -vYq EPM/"o(]@!$Q*+N!Iw 9%W7 0     % .