[ik0UddlmZddlZddlmZmZmZmZmZddl Z ddl m Z ddl m Z mZmZeefZded<ed d DZedZd ed <Gd dZGddZejeejedS)) annotationsN)MutableMappingMappingMutableSequenceIteratorIterable)Any)deprecate_argument _is_iterable_flattenztuple[type, ...]str_typec#K|]}|VdSN).0_s a/home/jenkins/workspace/simtester-sanitize/venv/lib/python3.11/site-packages/pyparsing/results.py rsarslice NULL_SLICEc:eZdZUded<dgZdd Zd Zd Zd Zd S)_ParseResultsWithOffsetztuple[ParseResults, int]tupp1 ParseResultsp2intreturnNonec||f|_dSrr)selfrrs r__init__z _ParseResultsWithOffset.__init__s.0"Xrc|j|Srr#r$is r __getitem__z#_ParseResultsWithOffset.__getitem__sx{rc|jSrr#r$s r __getstate__z$_ParseResultsWithOffset.__getstate__"s xrc |d|_dSNrr#)r$argss r __setstate__z$_ParseResultsWithOffset.__setstate__%s7rN)rrrrr r!) __name__ __module__ __qualname____annotations__ __slots__r%r)r,r0rrrrrsj!!!!I6666rrceZdZUdZdgdfZded<ded<ded<d ed <d ed <d ed<ded<dZGddeZdIdZ dddde fdJdZ dZ e fdZ dZdKdZdLdZdKdZdMd!ZdMd"Zd#Zd$Zd%ZdKd&Zd'ZdNd(Zd)Zd*Zd+Zd,Zd-ZdOd/ZdOd0Z dPd1Z!dQd2Z"dQd3Z#dRd5Z$d6d7dSd:Z%dTd<Z&dPd=Z'dPd>Z(dUd@Z)dVdQdBZ*dCZ+dDZ,dEZ-dFZ.dGZ/e0dNdPdHZ1e%Z2 e&Z3 e)Z4dS)WraStructured parse results, to provide multiple means of access to the parsed data: - as a list (``len(results)``) - by list index (``results[0], results[1]``, etc.) - by attribute (``results.`` - see :class:`ParserElement.set_results_name`) Example: .. testcode:: integer = Word(nums) 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")) # parse_string returns a ParseResults object result = date_str.parse_string("1999/12/31") def test(s, fn=repr): print(f"{s} -> {fn(eval(s))}") test("list(result)") test("result[0]") test("result['month']") test("result.day") test("'month' in result") test("'minutes' in result") test("result.dump()", str) prints: .. testoutput:: list(result) -> ['1999', '/', '12', '/', '31'] result[0] -> '1999' result['month'] -> '12' result.day -> '31' 'month' in result -> True 'minutes' in result -> False result.dump() -> ['1999', '/', '12', '/', '31'] - day: '31' - month: '12' - year: '1999' Nrztuple[Any, ...] _null_valuesstr_name_parentzset[str] _all_namesbool_modalz list[Any]_toklistzdict[str, Any]_tokdict)r9r:r;r=r>r?ceZdZdZddZdS)ParseResults.Lista9 Simple wrapper class to distinguish parsed list results that should be preserved as actual Python lists, instead of being converted to :class:`ParseResults`: .. testcode:: import pyparsing as pp ppc = pp.common LBRACK, RBRACK, LPAR, RPAR = pp.Suppress.using_each("[]()") element = pp.Forward() item = ppc.integer item_list = pp.DelimitedList(element) element_list = LBRACK + item_list + RBRACK | LPAR + item_list + RPAR element <<= item | element_list # add parse action to convert from ParseResults # to actual Python collection types @element_list.add_parse_action def as_python_list(t): return pp.ParseResults.List(t.as_list()) element.run_tests(''' 100 [2,3,4] [[2, 1],3,4] [(2, 1),3,4] (2,3,4) ([2, 3], 4) ''', post_parse=lambda s, r: (r[0], type(r[0])) ) prints: .. testoutput:: :options: +NORMALIZE_WHITESPACE 100 (100, ) [2,3,4] ([2, 3, 4], ) [[2, 1],3,4] ([[2, 1], 3, 4], ) [(2, 1),3,4] ([[2, 1], 3, 4], ) (2,3,4) ([2, 3, 4], ) ([2, 3], 4) ([[2, 3], 4], ) (Used internally by :class:`Group` when `aslist=True`.) Nc|g}t|ts+t|jdt |jt|S)Nz* may only be constructed with a list, not ) isinstancelist TypeErrorr1type__new__)cls containeds rrGzParseResults.List.__new__sb  i.. |iitT]Ogii<<$$ $rr)r1r2r3__doc__rGrrrListrAos39 9 v % % % % % %rrKc t|tr|St|}d|_d|_t |_|g|_n^t|ttfr:t|tj r |ddgnt||_n|g|_t|_ |Sr)rCrobjectrGr9r:setr;r>rD_generator_typerKdictr?)rHtoklistnamekwargsr$s rrGzParseResults.__new__s g| , , N~~c""  %% ?DMM $!8 9 9 &g|'899# ']] MM %IDM  rTr r!c ^t|ddd}|o|}|||_||dkrdS||trt|}|s|h|_||_||jvrdS||ttfr|g}|rl||tr&tt|j d||<n&tt|dd||<|||_dS |d||<dS#tttf$r||ur|||<YdS||_YdSwxYw)NasListTaslist)new_namer)r r=rr8r;r9r7rrFrrr>KeyErrorrE IndexError)r$rQrRrVmodalrCrSrUs rr%zParseResults.__init__sz$FHdXNNN"F 9 <42:: F :dC  t99D %#fDO d' ' ' F :g$/ 0 0 iG  z'<00 R4\'BR5S5SUVWWT 4\'!*5M5MqQQT #DJ  F " DJJJ)Z0 " " "d""$T !  "s1 C>> D,!D,+D,ct|ttfr |j|S||jvr|j|ddSt d|j|DS)Nrcg|] }|d S)rrrvs r z,ParseResults.__getitem__..s<<r;r?rr's rr)zParseResults.__getitem__sm a#u & & $=# # DO # #=#B'* *<<4=+;<<<===rc||tr<|j|t|gz|j|<|d}n\||tt fr ||j|<|}n7|j|gt|dgz|j|<|}||tr ||_dSdSr.) rr?getrDrrr>rr:)r$kr`rCsubs r __setitem__zParseResults.__setitem__s :a0 1 1 #}00DFF;;qcADM! A$CC ZC< ( (  DM! CC#}00B77'1--; DM! C :c< ( ( CKKK  rc \t|ttfs |j|=dS|tkr|jdSt|j}|j|=t|tr|dkr||z }t||dz}tt| |}| |j D]9}|D]4}t|D]"\}\}}t||||kz ||<#5:dS)Nrr )rCrrr?rr>clearlenrDrangeindicesreversevalues enumerater) r$r(mylenremoved occurrencesjrdvaluepositions r __delitem__zParseResults.__delitem__sM!c5\**  a F ?? M   ! ! ! FDM"" M!  a   1uuU aQAuaii../00=//11  K  ,5k,B,B(A(x%<x8a<8&&KNN   rc||jvSrr?)r$rds r __contains__zParseResults.__contains__2sDM!!rrc*t|jSr)rir>r+s r__len__zParseResults.__len__5s4=!!!rc"|jp|j Sr)r>r?r+s r__bool__zParseResults.__bool__8s 6777rrc*t|jSriterr>r+s r__iter__zParseResults.__iter__;DM"""rc<t|jdddS)Nr]r~r+s r __reversed__zParseResults.__reversed__>sDM$$B$'(((rc*t|jSr)rr?r+s rkeyszParseResults.keysArrcDfdDS)Nc3(K|] }|V dSrrrrdr$s rrz&ParseResults.values..Es'--AQ------rrr+s`rrmzParseResults.valuesDs%--------rcDfdDS)Nc3,K|]}||fVdSrrrs rrz%ParseResults.items..Hs+22DG 222222rrr+s`ritemszParseResults.itemsGs%2222diikk2222rc|j S)z Since ``keys()`` returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.rwr+s rhaskeyszParseResults.haskeysJs}$$$rc2|sdg}|D]'\}}|dkr |d|f}td|t|dtst |dks |d|vr|d}||}||=|S|d}|S)a Removes and returns item at specified index (default= ``last``). Supports both ``list`` and ``dict`` semantics for ``pop()``. If passed no argument or an integer argument, it will use ``list`` semantics and pop tokens from the list of parsed tokens. If passed a non-integer argument (most likely a string), it will use ``dict`` semantics and pop the corresponding value from any defined results names. A second default return value argument is supported, just as in ``dict.pop()``. Example: .. doctest:: >>> numlist = Word(nums)[...] >>> print(numlist.parse_string("0 123 321")) ['0', '123', '321'] >>> def remove_first(tokens): ... tokens.pop(0) ... >>> numlist.add_parse_action(remove_first) [W:(0-9)]... >>> print(numlist.parse_string("0 123 321")) ['123', '321'] >>> label = Word(alphas) >>> patt = label("LABEL") + Word(nums)[1, ...] >>> print(patt.parse_string("AAB 123 321").dump()) ['AAB', '123', '321'] - LABEL: 'AAB' >>> # Use pop() in a parse action to remove named result >>> # (note that corresponding value is not >>> # removed from list form of results) >>> def remove_LABEL(tokens): ... tokens.pop("LABEL") ... return tokens ... >>> patt.add_parse_action(remove_LABEL) {W:(A-Za-z) {W:(0-9)}...} >>> print(patt.parse_string("AAB 123 321").dump()) ['AAB', '123', '321'] r]defaultrz)pop() got an unexpected keyword argument r )rrErCrri)r$r/rSrdr`indexret defaultvalues rpopzParseResults.popPs\ 4DLLNN S SDAqI~~Q| QA Q QRRR d1gs # # s4yyA~~aDGEu+CU J7L rc||vr||S|S)as Returns named result matching the given key, or if there is no such name, then returns the given ``default_value`` or ``None`` if no ``default_value`` is specified. Similar to ``dict.get()``. Example: .. doctest:: >>> integer = Word(nums) >>> date_str = integer("year") + '/' + integer("month") + '/' + integer("day") >>> result = date_str.parse_string("1999/12/31") >>> result.get("year") '1999' >>> result.get("hour", "not specified") 'not specified' >>> result.get("hour") r)r$key default_values rrczParseResults.gets. $;;9  rc|j|||jD]4}t |D]"\}\}}t ||||kz||<#5dS)a Inserts new element at location index in the list of parsed tokens. Similar to ``list.insert()``. Example: .. doctest:: >>> numlist = Word(nums)[...] >>> print(numlist.parse_string("0 123 321")) ['0', '123', '321'] >>> # use a parse action to insert the parse location >>> # in the front of the parsed results >>> def insert_locn(locn, tokens): ... tokens.insert(0, locn) ... >>> numlist.add_parse_action(insert_locn) [W:(0-9)]... >>> print(numlist.parse_string("0 123 321")) [0, '0', '123', '321'] N)r>insertr?rmrnr)r$r ins_stringrqrdrsrts rrzParseResults.inserts2 UJ///=//11  K(1+(>(>  $$E8!88x%'78"" A   rc:|j|dS)a Add single element to end of ``ParseResults`` list of elements. Example: .. doctest:: >>> numlist = Word(nums)[...] >>> print(numlist.parse_string("0 123 321")) ['0', '123', '321'] >>> # use a parse action to compute the sum of the parsed integers, >>> # and add it to the end >>> def append_sum(tokens): ... tokens.append(sum(map(int, tokens))) ... >>> numlist.add_parse_action(append_sum) [W:(0-9)]... >>> print(numlist.parse_string("0 123 321")) ['0', '123', '321', 444] N)r>append)r$items rrzParseResults.appends , T"""""rct|tr||dS|j|dS)as Add sequence of elements to end of :class:`ParseResults` list of elements. Example: .. testcode:: patt = Word(alphas)[1, ...] # use a parse action to append the reverse of the matched strings, # to make a palindrome def make_palindrome(tokens): tokens.extend(reversed([t[::-1] for t in tokens])) return ''.join(tokens) patt.add_parse_action(make_palindrome) print(patt.parse_string("lskdj sdlkjf lksd")) prints: .. testoutput:: ['lskdjsdlkjflksddsklfjkldsjdksl'] N)rCr__iadd__r>extend)r$itemseqs rrzParseResults.extendsJ2 g| , , * MM' " " " " " M  ) ) ) ) )rcL|jdd=|jdS)z7 Clear all elements and results names. N)r>r?rhr+s rrhzParseResults.clears, M!!!  rc~ ||S#t$r(|drt|YdSwxYw)N__rX)rY startswithAttributeError)r$rRs r __getattr__zParseResults.__getattr__sU :    t$$ +$T***22 s  .<<otherc8|}||z }|Sr)copy)r$rrs r__add__zParseResults.__add__siikk u  rc^|s|S|jrut|jfd|j}fd|D}|D]2\}}|||<t |dt r ||d_3|xj|jz c_|xj|jzc_|S)Nc|dkrn|zSr.r)aoffsets rz'ParseResults.__iadd__..sAEE&&q6zrc ng|]1\}}|D])}|t|d|df*2S)rr )r)rrdvlistr` addoffsets rraz)ParseResults.__iadd__..sdAu+AaD))AaD//BBCrr)r?rir>rrCrr:r;)r$r otheritemsotherdictitemsrdr`rrs @@rrzParseResults.__iadd__s K > (''FAAAAI--//J *N ' ( (1QadL11(#'AaDL '  5++ rcjt|tr|dkr|S||zSr.)rCrr)r$rs r__radd__zParseResults.__radd__+s6 eS ! ! eqjj99;; 4< rcjt|jd|jd|dS)N(, ))rFr1r>as_dictr+s r__repr__zParseResults.__repr__3s4t**%LL LL4<<>>LLLLrcVddd|jDzdzS)N[rctg|]5}t|trt|nt|6Sr)rCrr8repr)rr(s rraz(ParseResults.__str__..:sG)L99FCFFFtAwwr])joinr>r+s r__str__zParseResults.__str__6sH ii!]   rrXcg}|jD]j}|r|r||t|tr||z }H|t |k|Sr)r>rrCr _asStringListr8)r$sepoutrs rrzParseResults._asStringListBsM & &D s  3$ -- &t))+++ 3t99%%%% rF)flattenrrDcJ|rgt|Sd|jDS)a Returns the parse results as a nested list of matching tokens, all converted to strings. If ``flatten`` is True, all the nesting levels in the returned list are collapsed. Example: .. doctest:: >>> patt = Word(alphas)[1, ...] >>> result = patt.parse_string("sldkj lsdkj sldkj") >>> # even though the result prints in string-like form, >>> # it is actually a pyparsing ParseResults >>> type(result) >>> print(result) ['sldkj', 'lsdkj', 'sldkj'] .. doctest:: >>> # Use as_list() to create an actual list >>> result_list = result.as_list() >>> type(result_list) >>> print(result_list) ['sldkj', 'lsdkj', 'sldkj'] .. versionchanged:: 3.2.0 New ``flatten`` argument. cdg|]-}t|tr|n|.Sr)rCras_list)rress rraz(ParseResults.as_list..osC",C!>!>G Cr)r r>)r$rs rrzParseResults.as_listMs@>  $Xd^^$ $= rrPchfdtfd|DS)ac Returns the named parse results as a nested dictionary. Example: .. doctest:: >>> integer = pp.Word(pp.nums) >>> date_str = integer("year") + '/' + integer("month") + '/' + integer("day") >>> result = date_str.parse_string('1999/12/31') >>> type(result) >>> result ParseResults(['1999', '/', '12', '/', '31'], {'year': '1999', 'month': '12', 'day': '31'}) >>> result_dict = result.as_dict() >>> type(result_dict) >>> result_dict {'year': '1999', 'month': '12', 'day': '31'} >>> # even though a ParseResults supports dict-like access, >>> # sometime you just need to have a dict >>> import json >>> print(json.dumps(result)) Traceback (most recent call last): TypeError: Object of type ParseResults is not JSON serializable >>> print(json.dumps(result.as_dict())) {"year": "1999", "month": "12", "day": "31"} ct|tr6|r|n fd|DS|S)Nc&g|] }|Srr)rr`to_items rraz9ParseResults.as_dict..to_item..s!;T;T;T1GGAJJ;T;T;Tr)rCrrr)objrs rrz%ParseResults.as_dict..to_itemsO#|,, (+ Ts{{}}};T;T;T;TPS;T;T;TT rc38K|]\}}||fVdSrr)rrdr`rs rrz'ParseResults.as_dict..s3==1Q O======r)rPr)r$rs @rrzParseResults.as_dicttsJB      ==== ======rct|j}|j|_|j|_|xj|jzc_|j|_|S)a Returns a new shallow copy of a :class:`ParseResults` object. :class:`ParseResults` items contained within the source are shared with the copy. Use :meth:`ParseResults.deepcopy` to create a copy with its own separate content values. )rr>r?rr:r;r9)r$rs rrzParseResults.copysQ4=))}))++ l  $/)J  rc|}t|jD]\}}t|tr||j|<8t|t tfrUt|trjt|x|j|<}| D]3\}}t|tr|n|||<4t|tr*t|d|D|j|<|S)zm Returns a new deep copy of a :class:`ParseResults` object. .. versionadded:: 3.1.0 c3lK|]/}t|tr|n|V0dSr)rCrdeepcopyr_s rrz(ParseResults.deepcopy..sN,,KLJq,$?$?FAJJLLLQ,,,,,,r) rrnr>rCrrr8bytesrrFrr)r$rr(rdestrdr`s rrzParseResults.deepcopys8 iikk ..  FAs#|,, "%,,.. QC#u.. C00 )2c4 Q$IIKKQQDAq.8L.I.IPajjlllqDGGQC** "+$s)),,PS,,,## Q r str | NonecjrjSjr<j}|j}t fd|DdSt dkrt jdkrtt t jdddvr3t t jSdS)aG Returns the results name for this token expression. Useful when several different expressions might match at a particular location. Example: .. testcode:: integer = Word(nums) ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") house_number_expr = Suppress('#') + Word(nums, alphanums) user_data = (Group(house_number_expr)("house_number") | Group(ssn_expr)("ssn") | Group(integer)("age")) user_info = user_data[1, ...] result = user_info.parse_string("22 111-22-3333 #221B") for item in result: print(item.get_name(), ':', item[0]) prints: .. testoutput:: age : 22 ssn : 111-22-3333 house_number : 221B c3:K|]\}}|D] \}}|u |VdSrr)rrdrr`locr$s rrz(ParseResults.get_name..sS 5"'3Dyy!yyyy rNr r)rr]) r9r:r?rnextrirrmr)r$parparent_tokdict_itemss` rget_namezParseResults.get_names@ : :  \  $ C#&<#5#5#7#7 $8   IINNDM""a''T$-..00112215a8GCCT]//112233 34rrcg}d}||r$|t|znd|sd|S|rt d|D}|D]\}} |r||||d|zd|dt| ts#|t| t| s#|t| || ||||dztd |Dsd|S|} d} d} t| D]\} } t| trM| ||||dz}|| || |zd | d | || |dzz| g|| || |zd | d | || |dzz| d|S) as Diagnostic method for listing out the contents of a :class:`ParseResults`. Accepts an optional ``indent`` argument so that this string can be embedded in a nested display of other data. Example: .. testcode:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parse_string('1999/12/31') print(result.dump()) prints: .. testoutput:: ['1999', '/', '12', '/', '31'] - day: '31' - month: '12' - year: '1999'  rXc3>K|]\}}t||fVdSr)r8)rrdr`s rrz$ParseResults.dump..s0@@41aCFFA;@@@@@@rz z- z: r )indentfull include_list_depthc3@K|]}t|tVdSr)rCr)rvvs rrz$ParseResults.dump../s,??B:b,//??????rrz]:) rr8rrrsortedrrCrrdumpanyrn)r$rrrrrNLrrdr`incrnlr(rvv_dumps rrzParseResults.dumps2  <G6C ////RHHH 773<<  <<>> @@4::<<@@@@@E  1#JJrNNN f>tf}>>>>>???!!\22JJtAww'''JJs1vv&&& FF%!%1%z ??$????? 773<<   q\\  EAr"l++ ''!!-!A: "  b6b4&=bb1bbbFbDFUVJDWbY`bb ]6]4&=]]1]]]F]DFUVJDW]Y[]]wws||rcTtj|g|Ri|dS)aF Pretty-printer for parsed results as a list, using the `pprint `_ module. Accepts additional positional or keyword args as defined for `pprint.pprint `_ . Example: .. testcode:: ident = Word(alphas, alphanums) num = Word(nums) func = Forward() term = ident | num | Group('(' + func + ')') func <<= ident + Group(Optional(DelimitedList(term))) result = func.parse_string("fna a,b,(fnb c,d,200),100") result.pprint(width=40) prints: .. testoutput:: ['fna', ['a', 'b', ['(', 'fnb', ['c', 'd', '200'], ')'], '100']] N)pprintr)r$r/rSs rrzParseResults.pprintGs2:  dllnn6t666v66666rc^|j|jd|j|jffSr)r>r?rr;r9r+s rr,zParseResults.__getstate__gs4 M ""$$    rcn|\|_\|_}}|_t||_d|_dSr)r>r?r9rNr;r:)r$stater inAccumNamess rr0zParseResults.__setstate__rs5HME E sL$*l++ rc|j|jfSr)r>r9r+s r__getnewargs__zParseResults.__getnewargs__ws}dj((rc~tt|t|zSr)dirrFrDrr+s r__dir__zParseResults.__dir__zs)4::diikk!2!222rc |g}|D]T\}}t|tr||||z }5|||g|t |z }U|||g|}|S)z Helper classmethod to construct a :class:`ParseResults` from a ``dict``, preserving the name-value relations as results names. If an optional ``name`` argument is given, a nested :class:`ParseResults` will be returned. )rR)rRrV)rrCr from_dictr )rHrrRrrdr`s rrzParseResults.from_dict}sc"ggKKMM @ @DAq!W%% @s}}QQ}///ssA3Q|A????  #se$'''C r)NN)r r!)r r<)r r)r rr)rrr r)r r)r r8)rX)rr<r rD)r rP)r r)rXTTr)5r1r2r3rJr7r4r5rDrKrGrCr%r)rfrurxrzr|rrrrmrrrrcrrrrhrrrrrrrrrrrrrrr,r0rr classmethodrrUasDictgetNamerrrrr)s11f&*2rNL2222JJJLLLIE%E%E%E%E%tE%E%E%N2  ."."."."."`>>>,6    :""""""""8888####))))###...333%%%% < < < |!!!!8B###0***< ,    MMMM         */%%%%%%N'>'>'>'>R    .5555nLLLLL\777@     )))333[ FFGrr) __future__r collectionscollections.abcrrrrrrtypingr utilr r r r8rrr4rFrOrrrrregisterrrrrsy#"""""" <<<<<<<<<<"5\))))$2''E$KK "s s s s s s s s l %%%&&&&&r