U ʗRe٘ @sUddlZddlZddlZddlmZddlTddlmZm Z m Z dVdde e e fe e e feejeejeee d d d ZdWdd e eje eje e d ddZe e dddZe e dddZdXddde eje e feeeeee dddZe e e dddZdYdde eee ddd Ze e dd!d"Ze e dd#d$Zd%d&defed'e e e fe e e feje e e e d(d)d*Zed+ed,fd-d.Ze e e fee e fd/d0d1Z e e e fee e fd/d2d3Z!e e"d4<e e"d5<e e#e$e%d6&d7\Z'Z(d8d9ej)j*+DZ,e-d:d;.e,d<&d=Z/d>d?Z0Gd@dAdAe1Z2e e e ee e e fe e e fffZ3e ee3ee2eje4fee3ee2ffZ5ed%ed&fe e6e5e e e fe e e fe dBdCdDZ7dgfdEdFZ8e9e-dGdH&dIZ:e-dJ&dKZ;e-dL<&dMZ=e-dN&dOZ>e9e-dGdHe>B&dPZ?e?Z@e-dQ&dRZAdSdTeBCDZDe6e e"dU<eZEeZFeZGeZHeZIeZJeZKeZLe ZMe!ZNe'e(ZOZPe/ZQe0ZRe2ZSe7ZTe:ZUe;ZVe=ZWe>ZXe?ZYe@ZZeAZ[dS)ZN)__diag__)*)_bslash_flatten_escape_regex_range_chars,F)allow_trailing_delim)exprdelimcombineminmaxr returncCst|trt|}djt|t||r>dt|ndd}|sRt|}|dk rr|dkrjt d|d8}|dk r|dk r||krt d|d8}|||||f}|r|t |7}|rt | |S| |SdS) a/Helper to define a delimited list of expressions - the delimiter defaults to ','. By default, the list elements and delimiters can have intervening whitespace, and comments, but this can be overridden by passing ``combine=True`` in the constructor. If ``combine`` is set to ``True``, the matching tokens are returned as a single token string, with the delimiters included; otherwise, the matching tokens are returned as a list of tokens, with the delimiters suppressed. If ``allow_trailing_delim`` is set to True, then the list may end with a delimiter. Example:: delimited_list(Word(alphas)).parse_string("aa,bb,cc") # -> ['aa', 'bb', 'cc'] delimited_list(Word(hexnums), delim=':', combine=True).parse_string("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE'] z{expr} [{delim} {expr}]...{end}z [{}])r r endNrzmin must be greater than 0z)max must be greater than, or equal to min) isinstancestr_type ParserElement_literalStringClassformatstrcopy streamlineSuppress ValueErrorOptCombineset_name)r r r r rr dlNamedelimited_list_exprr!/builddir/build/BUILDROOT/alt-python38-pip-22.2.1-2.el8.x86_64/opt/alt/python38/lib/python3.8/site-packages/pip/_vendor/pyparsing/helpers.pydelimited_lists.   r#)intExpr)r int_exprr$rcsr|p|}tfdd}|dkr8ttdd}n|}|d|j|dd|d td S) a~Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. If ``int_expr`` is specified, it should be a pyparsing expression that produces an integer value. Example:: counted_array(Word(alphas)).parse_string('2 ab cd ef') # -> ['ab', 'cd'] # in this parser, the leading integer value is given in binary, # '10' indicating that 2 values are in the array binary_constant = Word('01').set_parse_action(lambda t: int(t[0], 2)) counted_array(Word(alphas), int_expr=binary_constant).parse_string('10 ab cd ef') # -> ['ab', 'cd'] # if other fields must be parsed after the count but before the # list items, give the fields results names and they will # be preserved in the returned ParseResults: count_with_metadata = integer + Word(alphas)("type") typed_array = counted_array(Word(alphanums), int_expr=count_with_metadata)("items") result = typed_array.parse_string("3 bool True True False") print(result.dump()) # prints # ['True', 'True', 'False'] # - items: ['True', 'True', 'False'] # - type: 'bool' cs,|d}|r|ntK|dd=dSNr)Empty)sltn array_exprr r!r"count_field_parse_actionssz/counted_array..count_field_parse_actionNcSs t|dSr&)intr*r!r!r"{zcounted_array..arrayLenT)call_during_tryz(len) z...)ForwardWordnumsset_parse_actionrradd_parse_actionr)r r%r$r.r!r,r" counted_arrayGs) r:)r rcs6tfdd}|j|dddt|S)a9Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = match_previous_literal(first) match_expr = first + ":" + second will match ``"1:1"``, but not ``"1:2"``. Because this matches a previous literal, will also match the leading ``"1:1"`` in ``"1:10"``. If this is not desired, use :class:`match_previous_expr`. Do *not* use with packrat parsing enabled. csP|rBt|dkr|d>qLt|}tdd|D>n t>dS)Nrrcss|]}t|VqdSN)Literal).0ttr!r!r" szImatch_previous_literal..copy_token_to_repeater..)lenras_listAndr')r(r)r*tflatrepr!r"copy_token_to_repeaters   z6match_previous_literal..copy_token_to_repeaterT callDuringTry(prev) )r5r9rr)r rFr!rDr"match_previous_literals  rJcsFt|}|Kfdd}|j|dddt|S)aWHelper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = match_previous_expr(first) match_expr = first + ":" + second will match ``"1:1"``, but not ``"1:2"``. Because this matches by expressions, will *not* match the leading ``"1:1"`` in ``"1:10"``; the expressions are evaluated first, and then compared, so ``"1"`` is compared with ``"10"``. Do *not* use with packrat parsing enabled. cs*t|fdd}j|dddS)Ncs,t|}|kr(t||d|dS)NzExpected {}, found{})rrAParseExceptionr)r(r)r* theseTokens matchTokensr!r"must_match_these_tokenss  zTmatch_previous_expr..copy_token_to_repeater..must_match_these_tokensTrG)rrAr8)r(r)r*rOrDrMr"rFs  z3match_previous_expr..copy_token_to_repeaterTrGrI)r5rr9rr)r e2rFr!rDr"match_previous_exprs rQT)useRegex asKeyword)strscaseless use_regex as_keywordrRrSrcsD|p|}|o|}t|tr.tjr.tjddd|rPdd}dd}|rJtntndd}dd}|rhtnt g}t|tr| }nt|t rt |}nt d |stStd d |DrLd } | t|d krL|| } t|| d dD]P\} } || | r|| | d =qq|| | r|| | d =|| | qq| d 7} q|r"|r^tjnd } ztdd |Drdddd |D}nddd |D}|rd|}t|| dd|}|rdd|D|fdd|WStjk r tjdddYnXtfdd |Dd|S)a Helper to quickly define a set of alternative :class:`Literal` s, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a :class:`MatchFirst` for best performance. Parameters: - ``strs`` - a string of space-delimited literals, or a collection of string literals - ``caseless`` - treat all literals as caseless - (default= ``False``) - ``use_regex`` - as an optimization, will generate a :class:`Regex` object; otherwise, will generate a :class:`MatchFirst` object (if ``caseless=True`` or ``asKeyword=True``, or if creating a :class:`Regex` raises an exception) - (default= ``True``) - ``as_keyword`` - enforce :class:`Keyword`-style matching on the generated expressions - (default= ``False``) - ``asKeyword`` and ``useRegex`` are retained for pre-PEP8 compatibility, but will be removed in a future release Example:: comp_oper = one_of("< = > <= >= !=") var = Word(alphas) number = Word(nums) term = var | number comparison_expr = term + comp_oper + term print(comparison_expr.search_string("B = 12 AA=23 B<=AA AA>12")) prints:: [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']] z`More than one string argument passed to one_of, pass choices as a list or space-delimited string) stacklevelcSs||kSr;)upperabr!r!r"r1r2zone_of..cSs||Sr;)rZ startswithr[r!r!r"r1r2cSs||kSr;r!r[r!r!r"r1r2cSs ||Sr;)r^r[r!r!r"r1r2z7Invalid argument to one_of, expected string or iterablecss|]}t|dkVqdSrNr@r=symr!r!r"r?szone_of..rrNcss|]}t|dkVqdSr_r`rar!r!r"r?&sz[{}]rcss|]}t|VqdSr;)rrar!r!r"r?)s|css|]}t|VqdSr;)reescaperar!r!r"r?,sz \b(?:{})\b)flagsz | cSsi|]}||qSr!lowerrar!r!r" 7szone_of..cs|dSr&rgr(r)r*) symbol_mapr!r"r18r2z8Exception creating Regex for one_of, building MatchFirstc3s|]}|VqdSr;r!ra)parseElementClassr!r"r?Bs)rrr%warn_on_multiple_string_args_to_oneofwarningswarnCaselessKeywordCaselessLiteralKeywordr<splitIterablelist TypeErrorNoMatchanyr@ enumerateinsertrd IGNORECASEallrjoinRegexrr9error MatchFirst)rTrUrVrWrRrSisequalmaskssymbolsicurjotherre_flagspattretr!)rlrkr"one_ofsz)           r)keyvaluercCsttt||S)aHelper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the :class:`Dict`, :class:`ZeroOrMore`, and :class:`Group` tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the :class:`Dict` results can include named token fields. Example:: text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)) print(attr_expr[1, ...].parse_string(text).dump()) attr_label = label attr_value = Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join) # similar to Dict, but simpler call format result = dict_of(attr_label, attr_value).parse_string(text) print(result.dump()) print(result['shape']) print(result.shape) # object attribute access works too print(result.as_dict()) prints:: [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: 'light blue' - posn: 'upper left' - shape: 'SQUARE' - texture: 'burlap' SQUARE SQUARE {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} )Dict OneOrMoreGroup)rrr!r!r"dict_ofGs%r)asString)r as_stringrrcCsr|o|}tdd}|}d|_|d||d}|rHdd}ndd}|||j|_|tj|S) aHelper to return the original, untokenized text for a given expression. Useful to restore the parsed fields of an HTML start tag into the raw tag text itself, or to revert separate tokens with intervening whitespace back to the original matching input text. By default, returns astring containing the original parsed text. If the optional ``as_string`` argument is passed as ``False``, then the return value is a :class:`ParseResults` containing any results names that were originally matched, and a single token containing the original matched text from the input string. So if the expression passed to :class:`original_text_for` contains expressions with defined results names, you must set ``as_string`` to ``False`` if you want to preserve those results name values. The ``asString`` pre-PEP8 argument is retained for compatibility, but will be removed in a future release. Example:: src = "this is test bold text normal text " for tag in ("b", "i"): opener, closer = make_html_tags(tag) patt = original_text_for(opener + SkipTo(closer) + closer) print(patt.search_string(src)[0]) prints:: [' bold text '] ['text'] cSs|Sr;r!)r(locr*r!r!r"r1r2z#original_text_for..F_original_start _original_endcSs||j|jSr;)rrrjr!r!r"r1r2cSs&||d|dg|dd<dS)Nrrpoprjr!r!r" extractTextsz&original_text_for..extractText)r'r8r callPreparse ignoreExprssuppress_warning Diagnostics)warn_ungrouped_named_tokens_in_collection)r rr locMarker endlocMarker matchExprrr!r!r"original_text_foros"   rcCst|ddS)zkHelper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty. cSs|dSr&r!r0r!r!r"r1r2zungroup..)TokenConverterr9)r r!r!r"ungroupsrcCs4tdd}t|d|d|dS)a (DEPRECATED - future code should use the Located class) Helper to decorate a returned token with its starting and ending locations in the input string. This helper adds the following results names: - ``locn_start`` - location where matched expression begins - ``locn_end`` - location where matched expression ends - ``value`` - the actual parsed results Be careful if the input text contains ```` characters, you may want to call :class:`ParserElement.parseWithTabs` Example:: wd = Word(alphas) for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"): print(match) prints:: [[0, 'ljsdf', 5]] [[8, 'lksdjjf', 15]] [[18, 'lkkjj', 23]] cSs|Sr;r!)ssllr>r!r!r"r1r2zlocatedExpr.. locn_startrlocn_end)r'r8rrleaveWhitespace)r locatorr!r!r" locatedExprsr()) ignoreExpr)openerclosercontent ignore_exprrrcCs||kr|tkr|n|}||kr*td|dkrFt|tr>t|tr>t|dkrt|dkr|dk rtt|t||tj dd dd}n$t t||tj  dd}nz|dk rtt|t |t |ttj dd dd}n4ttt |t |ttj dd d d}ntd t}|dk r|tt|t||B|Bt|K}n$|tt|t||Bt|K}|d ||f|S) a& Helper method for defining nested lists enclosed in opening and closing delimiters (``"("`` and ``")"`` are the default). Parameters: - ``opener`` - opening character for a nested list (default= ``"("``); can also be a pyparsing expression - ``closer`` - closing character for a nested list (default= ``")"``); can also be a pyparsing expression - ``content`` - expression for items within the nested lists (default= ``None``) - ``ignore_expr`` - expression for ignoring opening and closing delimiters (default= :class:`quoted_string`) - ``ignoreExpr`` - this pre-PEP8 argument is retained for compatibility but will be removed in a future release If an expression is not provided for the content argument, the nested expression will capture all whitespace-delimited content between delimiters as a list of separate values. Use the ``ignore_expr`` argument to define expressions that may contain opening or closing characters that should not be treated as opening or closing characters for nesting, such as quoted_string or a comment expression. Specify multiple expressions using an :class:`Or` or :class:`MatchFirst`. The default is :class:`quoted_string`, but if no expressions are to be ignored, then pass ``None`` for this argument. Example:: data_type = one_of("void int short long char float double") decl_data_type = Combine(data_type + Opt(Word('*'))) ident = Word(alphas+'_', alphanums+'_') number = pyparsing_common.number arg = Group(decl_data_type + ident) LPAR, RPAR = map(Suppress, "()") code_body = nested_expr('{', '}', ignore_expr=(quoted_string | c_style_comment)) c_function = (decl_data_type("type") + ident("name") + LPAR + Opt(delimited_list(arg), [])("args") + RPAR + code_body("body")) c_function.ignore(c_style_comment) source_code = ''' int is_odd(int x) { return (x%2); } int dec_to_hex(char hchar) { if (hchar >= '0' && hchar <= '9') { return (ord(hchar)-ord('0')); } else { return (10+ord(hchar)-ord('A')); } } ''' for func in c_function.search_string(source_code): print("%(name)s (%(type)s) args: %(args)s" % func) prints:: is_odd (int) args: [['int', 'x']] dec_to_hex (int) args: [['char', 'hchar']] z.opening and closing strings cannot be the sameNr)exactcSs |dSr&stripr0r!r!r"r1(r2znested_expr..cSs |dSr&rr0r!r!r"r1,r2cSs |dSr&rr0r!r!r"r16r2cSs |dSr&rr0r!r!r"r1>r2zOopening and closing arguments must be strings if no content expression is givenznested %s%s expression) quoted_stringrrrr@rr CharsNotInrDEFAULT_WHITE_CHARSr8emptyrr<r5rr ZeroOrMorer)rrrrrrr!r!r" nested_exprszJ         $r<>cst|tr|t|| d}n|jtttd}|rt t }||dt t t |td|tddgdd d d |}npt t ttd d B}||dt t t | d d ttd|tddgdd dd |}ttd|d dd}|d|fdd |ddddd}|_|_t||_||fS)zRInternal helper to construct opening and closing tag expressions, given a tag name)rUz_-:tag=/F)defaultrcSs |ddkSNrrr!rjr!r!r"r1^r2z_makeTags..r) exclude_charscSs |dSr&rgr0r!r!r"r1lr2cSs |ddkSrr!rjr!r!r"r1rr2zc s*|dddd|S)Nstartr: ) __setitem__r}replacetitlersrr0resnamer!r"r1{srrrrz)rrrrnamer6alphas alphanumsdbl_quoted_stringrr8 remove_quotesrrrrrr printablesrr<rr9r}rrrsrSkipTotag_body)tagStrxml suppress_LT suppress_GT tagAttrName tagAttrValueopenTagcloseTagr!rr" _makeTagsNsr       r)tag_strrcCs t|dS)aPHelper to construct opening and closing tag expressions for HTML, given a tag name. Matches tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values. Example:: text = 'More info at the pyparsing wiki page' # make_html_tags returns pyparsing expressions for the opening and # closing tags as a 2-tuple a, a_end = make_html_tags("A") link_expr = a + SkipTo(a_end)("link_text") + a_end for link in link_expr.search_string(text): # attributes in the tag (like "href" shown here) are # also accessible as named results print(link.link_text, '->', link.href) prints:: pyparsing -> https://github.com/pyparsing/pyparsing/wiki Frrr!r!r"make_html_tagssrcCs t|dS)zHelper to construct opening and closing tag expressions for XML, given a tag name. Matches tags only in the given upper/lower case. Example: similar to :class:`make_html_tags` Trrr!r!r" make_xml_tagssr any_open_tag any_close_tagz_:zany tagcCsi|]\}}|d|qS);)rstrip)r=kvr!r!r"risriz &(?Prcz);zcommon HTML entitycCs t|jS)zRHelper parser action to replace common HTML entities with their special characters)_htmlEntityMapgetentityr0r!r!r"replace_html_entitysrc@seZdZdZdZdS)OpAssocrrXN)__name__ __module__ __qualname__LEFTRIGHTr!r!r!r"rsr) base_exprop_listlparrparrcCs:Gdddt}d|_t}t|tr.t|}t|tr@t|}t|trTt|tsj|t|||B}n||||B}t|D]\}}|ddd\} } } } t| trt | } | dkrt| t t frt | dkrtd | \} }d | |}n d | }d | krdks$ntd | tjtjfkr>tdt|}| tjkr| d kr~||| t|| d}n| dkr| dk r||| |t|| |d}n|||t|d}n>| dkr||| |||t|t| |||}n| tjkr| d krXt| ts._FBTcSs|j|||gfSr;)r try_parse)selfinstringr doActionsr!r!r" parseImpl(sz%infix_notation.._FB.parseImplN)T)rrrrr!r!r!r"_FB'srz FollowedBy>r;NrXz@if numterms=3, opExpr must be a tuple or list of two expressionsz {}{} termz{} termrz6operator must be unary (1), binary (2), or ternary (3)z2operator must indicate right or left associativity)r.)rX.) FollowedByrr5rrrrryrrrtuplerur@rrrrrrrrr r8setName)rrrrrrlastExprroperDefopExprarityrightLeftAssocpaopExpr1opExpr2 term_namethisExprrr!r!r"infix_notationsQ                     r c s0ddfddfdd}fdd}fdd }ttd }tt|d }t|d } t|d } |rtt ||t| t|t || } n,tt |t| t|t |t | } | fdd| fdd| t t| dS)a (DEPRECATED - use IndentedBlock class instead) Helper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code. Parameters: - ``blockStatementExpr`` - expression defining syntax of statement that is repeated within the indented block - ``indentStack`` - list created by caller to manage indentation stack (multiple ``statementWithIndentedBlock`` expressions within a single grammar should share a common ``indentStack``) - ``indent`` - boolean indicating whether block must be indented beyond the current level; set to ``False`` for block of left-most statements (default= ``True``) A valid block must contain at least one ``blockStatement``. (Note that indentedBlock uses internal parse actions which make it incompatible with packrat parsing.) Example:: data = ''' def A(z): A1 B = 100 G = A2 A2 A3 B def BB(a,b,c): BB1 def BBA(): bba1 bba2 bba3 C D def spam(x,y): def eggs(z): pass ''' indentStack = [1] stmt = Forward() identifier = Word(alphas, alphanums) funcDecl = ("def" + identifier + Group("(" + Opt(delimitedList(identifier)) + ")") + ":") func_body = indentedBlock(stmt, indentStack) funcDef = Group(funcDecl + func_body) rvalue = Forward() funcCall = Group(identifier + "(" + Opt(delimitedList(rvalue)) + ")") rvalue << (funcCall | identifier | Word(nums)) assignment = Group(identifier + "=" + rvalue) stmt << (funcDef | assignment | identifier) module_body = stmt[1, ...] parseTree = module_body.parseString(data) parseTree.pprint() prints:: [['def', 'A', ['(', 'z', ')'], ':', [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], 'B', ['def', 'BB', ['(', 'a', 'b', 'c', ')'], ':', [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], 'C', 'D', ['def', 'spam', ['(', 'x', 'y', ')'], ':', [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] Ncsddd<dSNr!r!) backup_stacks indentStackr!r" reset_stacksz"indentedBlock..reset_stackcsN|t|krdSt||}|dkrJ|dkr>t||dt||ddS)Nrzillegal nestingznot a peer entry)r@colrKr(r)r*curColrr!r"checkPeerIndents     z&indentedBlock..checkPeerIndentcs2t||}|dkr"|n t||ddS)Nrznot a subentry)rappendrKrrr!r"checkSubIndents   z%indentedBlock..checkSubIndentcsJ|t|krdSt||}r&|ks2t||d|dkrFdS)Nznot an unindentr)r@rrKrrrr!r" checkUnindents     z$indentedBlock..checkUnindentz INDENTrUNINDENTcsrdodSdSr rr!)rr!r"r1r2zindentedBlock..csSr;r!)r\r]cd)rr!r"r1r2zindented block)rrLineEndset_whitespace_charssuppressr'r8rrrr9set_fail_actionignorer) blockStatementExprrindentrrrrNLrPEERUNDENTsmExprr!)rrrr" indentedBlock{s@V   r)z/\*(?:[^*]|\*(?!/))*z*/zC style commentzz HTML commentz.*z rest of linez//(?:\\\n|[^\n])*z // commentzC++ style commentz#.*zPython style commentcCsg|]}t|tr|qSr!)rr)r=rr!r!r" %s r*_builtin_exprs)rFNN)N)FTF)T)\ html.entitieshtmlrdtypingrrcoreutilrrrUnionrrboolOptionalr/r#r:rJrQrtrrrrrrrrrTuplerr__annotations__r6rrrrrentitieshtml5itemsrr~r}common_html_entityrEnumrInfixNotationOperatorArgType ParseActionInfixNotationOperatorSpecListr r)rc_style_comment html_commentleave_whitespace rest_of_linedbl_slash_commentcpp_style_commentjava_style_commentpython_style_commentvarsvaluesr+ delimitedList countedArraymatchPreviousLiteralmatchPreviousExproneOfdictOforiginalTextFor nestedExpr makeHTMLTags makeXMLTags anyOpenTag anyCloseTagcommonHTMLEntityreplaceHTMLEntityopAssoc infixNotation cStyleComment htmlComment restOfLinedblSlashCommentcppStyleCommentjavaStyleCommentpythonStyleCommentr!r!r!r"sB    ; <!& ) 5$   ;        &