f gfUddlmZddlZddlmZmZmZmZmZddl Z ddl m Z ddl m Z eefZded<ed d DZGd d ZGd dZejeejedS)) annotationsN)MutableMappingMappingMutableSequenceIteratorIterable)Any)replaced_by_pep8ztuple[type, ...]str_typec#K|]}|VdSN).0_s a/home/jenkins/workspace/simtester-sanitize/venv/lib/python3.11/site-packages/pyparsing/results.py rsarc:eZdZUded<dgZdd Zd Zd Zd Zd S)_ParseResultsWithOffsetztuple[ParseResults, int]tupp1 ParseResultsp2intreturnNonec||f|_dSrr)selfrrs r__init__z _ParseResultsWithOffset.__init__s.0"Xrc|j|Srrr is r __getitem__z#_ParseResultsWithOffset.__getitem__sx{rc|jSrrr s r __getstate__z$_ParseResultsWithOffset.__getstate__ s xrc |d|_dSNrr)r argss r __setstate__z$_ParseResultsWithOffset.__setstate__#s7rN)rrrrrr) __name__ __module__ __qualname____annotations__ __slots__r!r%r(r,rrrrrsj!!!!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)Wra{Structured 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:: 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:: 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)r5r6r7r9r:r;ceZdZdZddZdS)ParseResults.Lista Simple wrapper class to distinguish parsed list results that should be preserved as actual Python lists, instead of being converted to :class:`ParseResults`:: LBRACK, RBRACK = map(pp.Suppress, "[]") element = pp.Forward() item = ppc.integer element_list = LBRACK + pp.DelimitedList(element) + RBRACK # add parse actions to convert from ParseResults to actual Python collection types def as_python_list(t): return pp.ParseResults.List(t.as_list()) element_list.add_parse_action(as_python_list) element <<= item | element_list element.run_tests(''' 100 [2,3,4] [[2, 1],3,4] [(2, 1),3,4] (2,3,4) ''', post_parse=lambda s, r: (r[0], type(r[0]))) prints:: 100 (100, ) [2,3,4] ([2, 3, 4], ) [[2, 1],3,4] ([[2, 1], 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 TypeErrorr-type__new__)cls containeds rrCzParseResults.List.__new__sb  i.. |iitT]Ogii<<$$ $rr)r-r.r/__doc__rCrrrListr=gs3$ $ L % % % % % %rrGc t|tr|St|}d|_d|_t |_|g|_n^t|ttfr:t|tj r |ddgnt||_n|g|_t|_ |Sr)r?robjectrCr5r6setr7r:r@_generator_typerGdictr;)rDtoklistnamekwargsr s rrCzParseResults.__new__s g| , , N~~c""  %% ?DMM $!8 9 9 &g|'899# ']] MM %IDM  rTrrc0|||_||dkrdS||trt|}|s|h|_||_||jvrdS||t tfr|g}|rl||tr&tt|j d||<n&tt|dd||<|||_dS |d||<dS#tttf$r||ur|||<YdS||_YdSwxYw)Nr)r9rr4r7r5r3r rBrrr:KeyErrorrA IndexError)r rMrNasListmodalr?s rr!zParseResults.__init__sZ 9 <42:: F :dC  t99D %#fDO d' ' ' F :g$/ 0 0 iG  z'<00 R4\'BR5S5SUVWWT 4\'!*5M5MqQQT #DJ  F " DJJJ)Z0 " " "d""$T !  "s C'' D DDct|ttfr |j|S||jvr|j|ddSt d|j|DS)Nrcg|] }|d S)rrrvs r z,ParseResults.__getitem__..s<<.s'--AQ------rrr's`rrgzParseResults.valuess%--------rcDfdDS)Nc3,K|]}||fVdSrrrs rrz%ParseResults.items..s+22DG 222222rrr's`ritemszParseResults.itemss%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.rqr's rhaskeyszParseResults.haskeyss}$$$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:: 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) 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()) # 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) print(patt.parse_string("AAB 123 321").dump()) prints:: ['AAB', '123', '321'] - LABEL: 'AAB' ['AAB', '123', '321'] rWdefaultrz)pop() got an unexpected keyword argument r )rrAr?rrc)r r+rOr_rZindexret defaultvalues rpopzParseResults.pop%sP 4DLLNN S SDAqI~~Q| QA Q QRRR d1gs # # s4yyA~~aDGEu+CU J7L rc||vr||S|S)a^ Returns named result matching the given key, or if there is no such name, then returns the given ``default_value`` or ``None`` if no ``default_value`` is specified. Similar to ``dict.get()``. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parse_string("1999/12/31") print(result.get("year")) # -> '1999' print(result.get("hour", "not specified")) # -> 'not specified' print(result.get("hour")) # -> None r)r key default_values rr^zParseResults.get]s$ $;;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:: 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) print(numlist.parse_string("0 123 321")) # -> [0, '0', '123', '321'] N)r:insertr;rgrhr)r r ins_stringrkr_rmrns rrzParseResults.insertts" UJ///=//11  K(1+(>(>  $$E8!88x%'78"" A   rc:|j|dS)a Add single element to end of ``ParseResults`` list of elements. Example:: 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) print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321', 444] N)r:append)r items rrzParseResults.appends  T"""""rct|tr||dS|j|dS)a Add sequence of elements to end of ``ParseResults`` list of elements. Example:: 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")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl' N)r?r__iadd__r:extend)r itemseqs rrzParseResults.extendsJ g| , , * MM' " " " " " M  ) ) ) ) )rcL|jdd=|jdS)z7 Clear all elements and results names. N)r:r;clearr's rrzParseResults.clears, M!!!  rc~ ||S#t$r(|drt|YdSwxYw)N__rQ)rR startswithAttributeError)r rNs 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)rr_vlistrZ addoffsets rr[z)ParseResults.__iadd__..sdAu+AaD))AaD//BBCrr)r;rcr:rr?rr6r7)r r otheritemsotherdictitemsr_rZrrs @@rrzParseResults.__iadd__s K > (''FAAAAI--//J *N ' ( (1QadL11(#'AaDL '  5++ rcjt|tr|dkr|S||zSr*)r?rr)r rs r__radd__zParseResults.__radd__s6 eS ! ! eqjj99;; 4< rcjt|jd|jd|dS)N(, ))rBr-r:as_dictr's r__repr__zParseResults.__repr__s4t**%LL LL4<<>>LLLLrcVddd|jDzdzS)N[rctg|]5}t|trt|nt|6Sr)r?rr4repr)rr$s rr[z(ParseResults.__str__..sG)L99FCFFFtAwwr])joinr:r's r__str__zParseResults.__str__sH ii!]   rrQcg}|jD]j}|r|r||t|tr||z }H|t |k|Sr)r:rr?r _asStringListr4)r sepoutrs rrzParseResults._asStringListsM & &D s  3$ -- &t))+++ 3t99%%%% rF)flattenrr@cNfd}|r g|SdjDS)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:: 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 print(type(result), result) # -> ['sldkj', 'lsdkj', 'sldkj'] # Use as_list() to create an actual list result_list = result.as_list() print(type(result_list), result_list) # -> ['sldkj', 'lsdkj', 'sldkj'] c3Ktjg}|rP|}t|tr||dddn|V|NdSdSr}) collectionsdequepopleftr?r extendleft)prto_visitto_dor s r flattenedz'ParseResults.as_list..flatteneds"(411H  ((**e\22 ''ddd 4444KKK      rcdg|]-}t|tr|n|.Sr)r?ras_list)rress rr[z(ParseResults.as_list..sC",C!>!>G Cr)r:)r rrs` rrzParseResults.as_lists\"       %YYt__% %= rrLchfdtfd|DS)a Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parse_string('12/31/1999') print(type(result), repr(result)) # -> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) result_dict = result.as_dict() print(type(result_dict), repr(result_dict)) # -> {'day': '1999', 'year': '12', 'month': '31'} # even though a ParseResults supports dict-like access, sometime you just need to have a dict import json print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable print(json.dumps(result.as_dict())) # -> {"month": "31", "day": "1999", "year": "12"} ct|tr6|r|n fd|DS|S)Nc&g|] }|Srr)rrZto_items rr[z9ParseResults.as_dict..to_item..7s!;T;T;T1GGAJJ;T;T;Tr)r?rrr)objrs rrz%ParseResults.as_dict..to_item5sO#|,, (+ Ts{{}}};T;T;T;TPS;T;T;TT rc38K|]\}}||fVdSrr)rr_rZrs rrz'ParseResults.as_dict..;s3==1Q O======r)rLr)r rs @rrzParseResults.as_dict sI*      ==== ======rct|j}|j|_|j|_|xj|jzc_|j|_|S)a Returns a new shallow copy of a :class:`ParseResults` object. `ParseResults` items contained within the source are shared with the copy. Use :class:`ParseResults.deepcopy()` to create a copy with its own separate content values. )rr:r;rr6r7r5)r rs rrzParseResults.copy=sQ4=))}))++ 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)zL Returns a new deep copy of a :class:`ParseResults` object. c3lK|]/}t|tr|n|V0dSr)r?rdeepcopyrYs rrz(ParseResults.deepcopy..[sN,,KLJq,$?$?FAJJLLLQ,,,,,,r) rrhr:r?rrr4bytesrrBrr)r rr$rdestr_rZs rrzParseResults.deepcopyKs8iikk ..  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)a Returns the results name for this token expression. Useful when several different expressions might match at a particular location. Example:: 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:: age : 22 ssn : 111-22-3333 house_number : 221B c3:K|]\}}|D] \}}|u |VdSrr)rr_rrZlocr s rrz(ParseResults.get_name..sS 5"'3Dyy!yyyy rNr r)rrW) r5r6r;rnextrcryrgr)r parparent_tokdict_itemss` rget_namezParseResults.get_name`s2 : :  \  $ 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) aM 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:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parse_string('1999/12/31') print(result.dump()) prints:: ['1999', '/', '12', '/', '31'] - day: '31' - month: '12' - year: '1999'  rQc3>K|]\}}t||fVdSr)r4)rr_rZs rrz$ParseResults.dump..s0@@41aCFFA;@@@@@@rz z- z: r )indentfull include_list_depthc3@K|]}t|tVdSr)r?r)rvvs rrz$ParseResults.dump..s,??B:b,//??????rrz]:) rr4rrrsortedrr?rrdumpanyrh)r rrrrrNLrr_rZincrnlr$rvv_dumps rrzParseResults.dumps*  <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)a$ Pretty-printer for parsed results as a list, using the `pprint `_ module. Accepts additional positional or keyword args as defined for `pprint.pprint `_ . Example:: ident = Word(alphas, alphanums) num = Word(nums) func = Forward() term = ident | num | Group('(' + func + ')') func <<= ident + Group(Optional(DelimitedList(term))) result = func.parse_string("fna a,b,(fnb c,d,200),100") result.pprint(width=40) prints:: ['fna', ['a', 'b', ['(', 'fnb', ['c', 'd', '200'], ')'], '100']] N)pprintr)r r+rOs rrzParseResults.pprints22  dllnn6t666v66666rc^|j|jd|j|jffSr)r:r;rr7r5r's rr(zParseResults.__getstate__s4 M ""$$    rcn|\|_\|_}}|_t||_d|_dSr)r:r;r5rJr7r6)r stater inAccumNamess rr,zParseResults.__setstate__s5HME E sL$*l++ rc|j|jfSr)r:r5r's r__getnewargs__zParseResults.__getnewargs__s}dj((rc~tt|t|zSr)dirrBr@rr's r__dir__zParseResults.__dir__ s)4::diikk!2!222rc  d}|g}|D]P\}}t|tr||||z }5|||g|||z }Q|||g|}|S)z Helper classmethod to construct a ``ParseResults`` from a ``dict``, preserving the name-value relations as results names. If an optional ``name`` argument is given, a nested ``ParseResults`` will be returned. cp t|t|t S#t$rYdSwxYw)NF)ryr?r Exception)rs r is_iterablez+ParseResults.from_dict..is_iterablesK 5S &c84444    uu s ' 55)rN)rNrT)rr?r from_dict)rDrrNrrr_rZs rrzParseResults.from_dict s 5 5 5c"ggKKMM ? ?DAq!W%% ?s}}QQ}///ssA3Q{{1~~>>>>  #se$'''C r)NN)rr)rr8)rr)rrr)rrrr)rr)rr4)rQ)rr8rr@)rrL)rr)rQTTr)5r-r.r/rFr3r0r1r@rGrCr?r!r%rarorrrtrvrzr~rrgrrrr^rrrrrrrrrrrrrrrrrrr(r,rr classmethodrrTasDictgetNamerrrrr's++Z&*2rNL2222JJJLLLI0%0%0%0%0%t0%0%0%d0d$:%"%"%"%"%"N>>>,6    0""""""""8888####))))###...333%%%% 6 6 6 p!!!!.2###"***( ,    MMMM         */      D>>>>:    *....`HHHHHT7778     )))333[4F+ F+G,,rr) __future__rrcollections.abcrrrrrrtypingr utilr r4rr r0rBrKrrregisterrrrrsR""""""" """""""5\))))$2''"E -E -E -E -E -E -E -E -P %%%&&&&&r